Category Archives: VB.NET

PHPHOST BLOG

Web Hosting Related Articles You May Need

Random File Names using .NET

It helps to have knowledge of .NET classes. I was recently working on a requirement where some files were to be generated on the fly and stored on the disk. The requirement was that the files had to be generated with random characters and random extensions, to add extra security to the files. System.IO.Path.GetRandomFileName() returns a random folder name or file name which makes the task very simple, as shown below:

C#

static void Main(string[] args){    for (int i = 1; i < 10; i++)        Console.WriteLine(System.IO.Path.GetRandomFileName());    Console.ReadLine();}

VB.NET

Shared Sub Main(ByVal args() As String)    For i As Integer = 1 To 9        Console.WriteLine(System.IO.Path.GetRandomFileName())    Next i    Console.ReadLine()End Sub

Note: If you want to physically create some files on the disk, just pass these random names to a FileStream object inside the for loop. GetRandomFileName() does not create a physical file like GetTempFileName() does.

OUTPUT

image

Continue reading

Posted in C#, Syndicated, VB.NET | Leave a comment

Free C# and VB.NET Training Videos

When you are in the need of learning a new programming language or technology, a training video can do wonders! Here are some free C# and VB.NET Training Videos for both the novice and experienced.

So grab some popcorn this weekend, sit back and learn!

C# Training Videos

“How Do I?” Videos for Visual C#

C# Training on Google Videos

C# Training Videos on YouTube

MSDN C# On-Demand Webcast

Channel 9 C# Videos

VB.NET Training Videos

“How Do I” Videos — Visual Basic

VB.NET Training on Google Videos

VB.NET Training Videos on You Tube

MSDN Visual Basic On-Demand Webcasts

Channel 9 VB.NET Videos

Other Free Videos

PDC 2009 Sessions – sessions presented by some of Microsoft’s best speakers.

MIX 2010 Videos – MIX10 session recordings

dnrTV – dnrTv is a fusion of a training video and an interview show. Training videos are typically sterile and one-way

DimeCasts.net – Short ~10 minutes screencasts

MSDN Screencasts – webcast that takes you step-by-step to discovering new functionality or exploring a hot developer topic, all in 10-15 minutes

Visual Studio 2010 and .NET Framework 4 Training Kit – presentations, hands-on labs, and demos

Zeollar – Technical Webcasts

WindowsClient.net – many pages of tutorials and hours of video training sessions that help you learn how to create Windows Client applications

General ASP.NET Videos – dozens of videos designed for all ASP.NET developers, from the novice to the professional.

Continue reading

Posted in C#, Free Learning, Syndicated, VB.NET | Leave a comment

Enum.TryParse in .NET 4.0

If you are using .NET 4.0, then Enum.TryParse<TEnum> is now provided out of the box and support flags enumeration. As given in the documentation, Enum.TryParse<> ‘Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

Here’s how to use it:

[Flags]enum Result { Fail = 0, Pass = 1, Grace = 2 };

static void Main(string[] args){    string a = (Result.Pass || Result.Grace).ToString();    Result b;    bool success = Enum.TryParse<Result>(a, out b);    Console.WriteLine("{0} = {1}", success, b);    Console.ReadLine();}

OUTPUT

image

Continue reading

Posted in C#, Syndicated, VB.NET | Leave a comment

Concatenate Items of a List

Here’s a simple way to concatenate items of a List<string>

C#

static void Main(string[] args){    List<string> strList = new List<string>()    {        "Jake", "Brian", "Raj", "Finnie", "Carol"    };

    string str = string.Join(";", strList.ToArray());

    Console.WriteLine(str);    Console.ReadLine();}

VB.NET

Sub Main(ByVal args() As String)    Dim strList As New List(Of String)() _              From {"Jake", "Brian", "Raj", "Finnie", "Carol"}

    Dim str As String = string.Join(";", strList.ToArray())

    Console.WriteLine(str)    Console.ReadLine()End Sub

OUTPUT

image

Continue reading

Posted in C#, Syndicated, VB.NET | Leave a comment

Programmatically determine Total Free Space available on your Hard Drive

The DriveInfo.AvailableFreeSpace property indicates the amount of available free space on a drive. Here’s how to use this property to programmatically retrieve the total free space of all logical drives (including CD/DVD drives) on your machine.

C#

static void Main(string[] args){    foreach (DriveInfo drive in DriveInfo.GetDrives())    {        try        {            Console.WriteLine("{0} has {1} MB free space available",            drive.RootDirectory, (drive.AvailableFreeSpace / 1024) / 1024);        }        catch (IOException io)        {            Console.WriteLine(io.Message);        }        catch (Exception ex)        {            Console.WriteLine(ex.Message);        }    }    Console.ReadLine();}

VB.NET

Shared Sub Main(ByVal args() As String)    For Each drive As DriveInfo In DriveInfo.GetDrives()        Try            Console.WriteLine("{0} has {1} MB free space available", _drive.RootDirectory, (drive.AvailableFreeSpace \ 1024) / 1024)        Catch io As IOException            Console.WriteLine(io.Message)        Catch ex As Exception            Console.WriteLine(ex.Message)        End Try    Next drive    Console.ReadLine()End Sub

OUTPUT

FreeSpace C#

Continue reading

Posted in C#, Syndicated, VB.NET | Leave a comment

Detect an Empty String in .NET 4.0

In the previous versions of .NET, we used the String.IsNullOrEmpty method to find out whether the specified string is null or an Empty string. However this method did not tell us if the string contained only whitespaces. You had to use the Trim().Length method to detect that.

.NET 4.0 makes this simpler by introducing the String.IsNullOrWhiteSpace method to find out whether a specified string is null, empty, or consists only of white-space characters.

So the following piece of code

static void Main(string[] args){    string str = new String(' ', 10);    Console.WriteLine(String.IsNullOrWhiteSpace(str));    Console.ReadLine();}

will return True.

Continue reading

Posted in C#, Syndicated, VB.NET | Leave a comment

Generate Stronger Random Numbers using C# and VB.NET

The RNGCryptoServiceProvider Class implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). Here’s how to generate random numbers using this class. Make sure you import the System.Security.Cryptography namespace before using this sample code

C#

static void GenerateRandomNumber(){    byte[] byt = new byte[4];    RNGCryptoServiceProvider rngCrypto =        new RNGCryptoServiceProvider();    rngCrypto.GetBytes(byt);    int randomNumber = BitConverter.ToInt32(byt, 0);    Console.WriteLine(randomNumber);}

VB.NET

Shared Sub GenerateRandomNumber()    Dim byt As Byte() = New Byte(4) {}    Dim rngCrypto As New RNGCryptoServiceProvider()    rngCrypto.GetBytes(byt)    Dim randomNumber As Integer = BitConverter.ToInt32(byt, 0)    Console.WriteLine(randomNumber)End Sub

image

Continue reading

Posted in C#, Syndicated, VB.NET | Leave a comment

Programmatically determine if a Windows Service is running and stop it

The ServiceController class makes it easy to retrieve information about a windows service and manipulate it. Here’s some code. Before running this example, make sure you have added a reference to System.ServiceProcess

C#

static void Main(string[] args){    try    {       ServiceController controller = new ServiceController("SERVICENAME");

        if (controller.Status.Equals(ServiceControllerStatus.Running)            && controller.CanStop)        {            controller.Stop();            Console.WriteLine("Service Stopped");        }                 Console.ReadLine();    }    catch (Exception ex)    {        Console.WriteLine(ex.Message);    }}

VB.NET

Shared Sub Main(ByVal args() As String)    Try        Dim controller As New ServiceController("SERVICENAME")

        If controller.Status.Equals(ServiceControllerStatus.Running)_
          AndAlso controller.CanStop Then            controller.Stop()            Console.WriteLine("Service Stopped")        End If        Console.ReadLine()    Catch ex As Exception        Console.WriteLine(ex.Message)    End TryEnd Sub

Make sure you have permission to stop the service or else you will get an exception.

Continue reading

Posted in C#, Syndicated, VB.NET | Leave a comment

Create Nested Directories in C# and VB.NET

A lot of developers do not know that Directory.CreateDirectory() can be used to create directories and subdirectories as specified by the path. Here’s an example

C#

static void Main(string[] args){    try    {        Directory.CreateDirectory(@"D:\ParentDir\ChildDir\SubChildDir\");        Console.WriteLine("Directories Created");        Console.ReadLine();    }    catch (Exception ex)    {        Console.WriteLine(ex.Message);    }}

VB.NET

Shared Sub Main(ByVal args() As String)    Try        Directory.CreateDirectory("D:\ParentDir\ChildDir\SubChildDir\")        Console.WriteLine("Directories Created")        Console.ReadLine()    Catch ex As Exception        Console.WriteLine(ex.Message)    End TryEnd Sub

OUTPUT

CreateNestedDirectories

Continue reading

Posted in C#, Syndicated, VB.NET | Leave a comment