.NET Programming for Absolute Beginners [Free Video Series]
Remove all Lower Case Letters using C#
using System; using System.Text.RegularExpressions; namespace WordCapital { class Program { static void Main(string[] args) { string fulltext = "We Love DevCurry.com"; Console.WriteLine("Full Text: {0}", fulltext); Regex rgx = new Regex("[^A-Z]"); Console.WriteLine("Abbreviated Text : {0}", rgx.Replace(fulltext, "")); Console.ReadLine(); } } }
In the code above, we are using Regex to match all characters that are not capitalized and then replace it with an empty string.
OUTPUT
Use Anonymous Method with a Delegate in C#
A colleague of mine asked me a question - ‘How can we use an Anonymous method with a Delegate and when should we do it”.
By using anonymous methods, you reduce the coding overhead in instantiating delegates, by eliminating the need to create a separate method. You can use it to run code snippets that would otherwise require a named method or use it as a quick event-handler with no name.
Here’s the code that shows how to do it. Comments have been placed inline to understand the code
namespace ConsoleApplication2
{
// Define a Delegate
delegate int AddThenMultiply(int i, int j);
class Class1
{
static void Main(string[] args)
{
// Instatiate delegate type using anonymous method
AddThenMultiply atm = delegate(int i, int j)
{
return (i + j) * 2;
};
// Anonymous delegate call
int result = atm(2, 3);
Console.WriteLine("Result is: " + result);
Console.ReadLine();
}
}
}
OUTPUT
Determine if your Laptop is Running on battery using C# or VB.NET
Here’s some code to programmatically find out if your laptop is currently running on battery power. I have created a Windows Form application and added the following code on a button click event which uses the SystemInformation.PowerStatus property
C#
private void btnPower_Click(object sender, EventArgs e)
{
PowerLineStatus status = SystemInformation.PowerStatus.PowerLineStatus;
if (status == PowerLineStatus.Offline)
MessageBox.Show("Running on Battery");
else
MessageBox.Show("Running on Power");
}
VB.NET (Converted Code)
Private Sub btnPower_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim st As PowerLineStatus = SystemInformation.PowerStatus.PowerLineStatus
If st = PowerLineStatus.Offline Then
MessageBox.Show("Running on Battery")
Else
MessageBox.Show("Running on Power")
End If
End Sub
Check Database connection using C# or VB.NET
As a programmer, one of the most common tasks in your application is to connect to the database. Here’s a very simple way to check your database connection before you start any task or use this as a service to check the connection and pause tasks if the connection breaks.
C#
private static bool DBConnectionStatus()
{
try
{
using (SqlConnection sqlConn =
new SqlConnection("YourConnectionString"))
{
sqlConn.Open();
return (sqlConn.State == ConnectionState.Open);
}
}
catch (SqlException)
{
return false;
}
catch (Exception)
{
return false;
}
}
VB.NET (Converted Code)
Private Function DBConnectionStatus() As Boolean
Try
Using sqlConn As New SqlConnection("YourConnectionString")
sqlConn.Open()
Return (sqlConn.State = ConnectionState.Open)
End Using
Catch e1 As SqlException
Return False
Catch e2 As Exception
Return False
End Try
End Function
The code above opens a connection to the database and returns a boolean depending on the database status.
Programmatically find CLR version for a .NET assembly
When it comes to extracting information from an assembly, Red Gate’s Reflector or the .NET Framework ILDASM tool are two obvious choices.
However if you have to programmatically determine the CLR version of an assembly it was compiled against, then use the Assembly.ImageRuntimeVersion property as shown below
Note: Add a namespace reference to System.Reflection
static void Main(string[] args)
{
Assembly asmbly = null;
asmbly = Assembly.ReflectionOnlyLoadFrom(@"C:/FckEdit/FredCK.FCKeditorV1.dll");
Console.WriteLine("CLR version of 1st Assembly " + asmbly.ImageRuntimeVersion);
asmbly = Assembly.ReflectionOnlyLoadFrom(@"C:/FckEdit/FredCK.FCKeditorV2.dll");
Console.WriteLine("CLR version of 2nd Assembly " + asmbly.ImageRuntimeVersion);
Console.ReadLine();
}
As you can see, we use ReflectionOnlyLoadFrom to load an assembly into reflection only context and then use the ImageRuntimeVersion property to get the version of the CLR saved in the assembly’s manifest.
OUTPUT
Convert DateTime to Different TimeZones
The TimeZoneInfo.ConvertTimeBySystemTimeZoneId in .NET 3.5 and 4.0, converts a time to the time in another time zone, based on a time zone identifier. Here’s how to use this method using different time zone identifiers like “India Standard Time”, “Pacific Standard Time” and so on:
C#
static void Main(string[] args)
{
DateTime dt = DateTime.Now;
Console.WriteLine("Time in Different TimeZones:\n");
Console.WriteLine("Indian Standard Time (IST): {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
TimeZoneInfo.Local.Id, "India Standard Time"));
Console.WriteLine("Eastern Standard Time (EST): {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
TimeZoneInfo.Local.Id, "Eastern Standard Time"));
Console.WriteLine("Pacific Standard Time (PST): {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
TimeZoneInfo.Local.Id, "Pacific Standard Time"));
Console.WriteLine("Greenwich Mean Time (GMT): {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
TimeZoneInfo.Local.Id, "GMT Standard Time"));
Console.ReadLine();
}
VB.NET (Converted Code)
Imports Microsoft.VisualBasic
Sub Main()
Dim dt As Date = Date.Now
Console.WriteLine("Time in Different TimeZones:" & vbLf)
Console.WriteLine("Indian Standard Time (IST): {0}", TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TimeZoneInfo.Local.Id, "India Standard Time"))
Console.WriteLine("Eastern Standard Time (EST): {0}", TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TimeZoneInfo.Local.Id, "Eastern Standard Time"))
Console.WriteLine("Pacific Standard Time (PST): {0}", TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TimeZoneInfo.Local.Id, "Pacific Standard Time"))
Console.WriteLine("Greenwich Mean Time (GMT): {0}", TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TimeZoneInfo.Local.Id, "GMT Standard Time"))
Console.ReadLine()
End Sub
OUTPUT
Programmatically Determine the Operating System using .NET
Here’s how to programmatically determine the Windows OS you are using. I will make use of the ManagementObjectSearcher class here
C#
using System;
using System.Management;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
string winos = "Select Name from Win32_OperatingSystem";
ManagementObjectSearcher mos =
new ManagementObjectSearcher(winos);
foreach (ManagementObject mo in mos.Get())
{
Console.WriteLine("OS Name: {0}", mo["Name"]);
}
Console.ReadLine();
}
}
}
VB.NET
Imports System
Imports System.Management
Namespace ConsoleApplication1
Friend Class Program
Public Shared Sub Main()
Dim winos As String = "Select Name from Win32_OperatingSystem"
Dim mos As New ManagementObjectSearcher(winos)
For Each mo As ManagementObject In mos.Get()
Console.WriteLine("OS Name: {0}", mo("Name"))
Next mo
Console.ReadLine()
End Sub
End Class
End Namespace
Here the Win32_OperatingSystem WMI class represents a Windows-based operating system installed on a computer.
OUTPUT
Detect if a String contains Special Characters
There are many ways to detect if a String contains Special Characters. In this code snippet, I will show a quick way to detect special characters using Regex.
C#
static void Main(string[] args)
{
string str = "Th!s $tri^g c@n$ist $pecial ch@rs";
Match match = Regex.Match(str, "[^a-z0-9]",
RegexOptions.IgnoreCase);
while (match.Success)
{
string key = match.Value;
Console.Write(key);
match = match.NextMatch();
}
Console.ReadLine();
}
VB. NET
Shared Sub Main(ByVal args() As String)
Dim str As String = "Th!s $tri^g c@n$ist $pecial ch@rs"
Dim match As Match = Regex.Match(str, "[^a-z0-9]", _
RegexOptions.IgnoreCase)
Do While match.Success
Dim key As String = match.Value
Console.Write(key)
match = match.NextMatch()
Loop
Console.ReadLine()
End Sub
Regex.Match searches the input string for the first occurrence of the regular expression specified. The Success property of the Match object tells us whether the regular expression pattern has been found in the input string. If yes, then print the first match and retrieve subsequent matches by repeatedly calling the Match.NextMatch method.
OUTPUT
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
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#
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
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.
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
Concatenate Items of a List<String>
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
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
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.
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
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 Try
End Sub
Make sure you have permission to stop the service or else you will get an exception.
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 Try
End Sub
OUTPUT
C# 4.0 New Features, Videos, Articles and Books
I was collecting some learning material on C# 4.0 and stumbled across some useful videos, articles and documents available on C# 4.0. I am just listing a few of them. Check them out!
Samples and Documents
New features of C# 4.0 (Beta 2)
Download C# 4.0 Beta 2 samples and documents
Articles
Use C# 4.0 dynamic to drastically simplify your private reflection code
C# 4.0 Optional Parameters – Exploration
Looking Ahead to C# 4.0: Optional and Named Parameters
Books
C# 4.0 in a Nutshell: The Definitive Reference
Visual C# 2010 Recipes: A Problem-Solution Approach
Introducing .NET 4.0: with Visual Studio 2010
Training Videos
C# 4.0 Dynamic with Chris Burrows and Sam Ng
How to Use Named and Optional Arguments in Office Programming (C#)
Dynamic C# and a New World of Possibilities
Update: Also check out Visual Studio 2010 and .NET Framework 4 Training Kit – Updated (February Edition)
Please note that C# 4.0 is in Beta as of this writing.
Convert String to Base64 and Base64 to String
The System.Text.Encoding class provides methods to convert string to Base64 and vice versa
String to Base64
The conversion involves two processes:
a. Convert string to a byte array
b. Use the Convert.ToBase64String() method to convert the byte array to a Base64 string
C#
byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);
// convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt);
VB.NET
Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)
' convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt)
Base64 string to Original String
In order to convert a Base64 string back to the original string, use FromBase64String(). The conversion involves two processes:
a. The FromBase64String() converts the string to a byte array
b. Use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();
C#
byte[] b = Convert.FromBase64String(strModified);
strOriginal = System.Text.Encoding.UTF8.GetString(b);
VB.NET
Dim b As Byte() = Convert.FromBase64String(strModified)
strOriginal = System.Text.Encoding.UTF8.GetString(b)
Check out some additional String functions over here 30 Common String Operations in C# and VB.NET