Extension Methods in C#

What are extension methods?

Extension methods in C# are used to extend the functionality of a class which is not provided by the class itself, without altering the definition of the original type. An extension method is a static method of a static class, where the this modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Rules to Use Extension Methods

We need to import the namespace in which the static class is defined which contains the extension methods. Suppose I have defined my method in a class which is again defined under namespace. In that case, we need to include the namespace using the keyword using wherever we want to use the method.
C# only supports extension methods, it does not support extension properties, extension events, extension operators.
Extension methods must be declared in non-generic and static classes.
C# compiler looks only for the extension methods defined in static classes that are themselves defined at the file scope. In other words, if we define a static class in some class and then define our extension methods, in that case, we will get a compile time error as shown below.

C# New Features

1- Auto-properties, and their improvements

Auto-properties have been available in C# for a long time by now, the thing is that Microsoft now introduce a new feature. “Initializers” can be used to initialize these properties to their defaults. A few of the ways that they can be used is like this:

private string Name { get; set; } = “C# Learners”;

// Without a setter, a readonly
private string Name { get; } = “C# Learners”;

// Simply read-only
private readonly string Name = “C# Learners”;

2- Null-conditional operator

Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced “Nullable of Int32,” can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

Nullable types have the following characteristics:

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

The syntax T? is shorthand for Nullable<T>, where T is a value type. The two forms are interchangeable.
Assign a value to a nullable type just as you would for an ordinary value type, for example int? x = 10; or double? d = 4.108. A nullable type can also be assigned the value null: int? x = null.

Use the Nullable<T>.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();

Use the HasValue and Value read-only properties to test for null and retrieve the value, as shown in the following example: if(x.HasValue) j = x.Value;

The HasValue property returns true if the variable contains a value, or false if it is null.

The Value property returns a value if one is assigned. Otherwise, a System.InvalidOperationException is thrown.

The default value for HasValue is false. The Value property has no default value.

You can also use the == and != operators with a nullable type, as shown in the following example: if (x != null) y = x;

Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;


OLE Stripper








Display an Image (OLE Object) from a Microsoft Access database by using OLE Stripper

In database programming, it happens a lot that you need to bind a picture box to a field with type of photo or image. For example, if you want to show an Employee’s picture from Northwind.mdb database, you might want to try the following code:

picEmployees.DataBindings.Add(“Image”, bsEmployees, “Photo”, true);

This code works if the images are stored in the database with no OLE header or the images stored as a raw image file formats. As the pictures stored in the Northwind database in are not stored in raw image file formats and they are stored as an OLE image documents, then you have to strip off the OLE header to work with the image properly.

Binding imageBinding = new Binding("Image", bsEmployees,
                                   "ImageBlob.ImageBlob", true);
imageBinding.Format += new ConvertEventHandler(this.PictureFormat);

private void PictureFormat(object sender, ConvertEventArgs e)
    Byte[] img = (Byte[])e.Value;
    MemoryStream ms = new MemoryStream();
    int offset = 78;
    ms.Write(img, offset, img.Length - offset);
    Bitmap bmp = new Bitmap(ms);
    // Writes the new value back
    e.Value = bmp;

Fortunately, there are some overload methods in .NET Framework to take care of this mechanism, but it cannot be guaranteed whether you need to strip off the OLE object by yourself or not. For example, you can use the following technique to access the images of the Northwind.mdb that ships with Microsoft Access and they will be rendered properly.

picEmployees.DataBindings.Add(“Image”, bsEmployees, “Photo”, true,
DataSourceUpdateMode.Never, new Bitmap(typeof(Button), “Button.bmp”));

Unfortunately, there are some scenarios that you need a better solution. For example, the Xtreme.mdb database that ships with Crystal Reports has a photo filed that cannot be handled by the preceding methods. For these complex scenarios, you can download the OLEStripper classes from here and re-write the PictureFormat method as it is shown below:

private void PictureFormat(object sender, ConvertEventArgs e)
     // photoIndex is same as Employee ID
     int photoIndex = Convert.ToInt32(e.Value);
     // Read the original OLE object
     ReadOLE olePhoto = new ReadOLE();

     string PhotoPath = olePhoto.GetOLEPhoto(photoIndex);

     // Strip the original OLE object
     StripOLE stripPhoto = new StripOLE();

     string StripPhotoPath = stripPhoto.GetStripOLE(PhotoPath);

     FileStream PhotoStream = new FileStream(StripPhotoPath
                                           , FileMode.Open);

     Image EmployeePhoto = Image.FromStream(PhotoStream);

     e.Value = EmployeePhoto;



Ole and Accessing Files Embedded in Microsoft Access








Ole and Accessing Files Embedded in Microsoft Access

The Microsoft Access team in 1990 needed a way to not only store files in an Access database, but also to present it to the user, with other software installed on the user’s computer. Because back then, there was no reliable way to find out through the OS what software handled what file type, they had to come up with a new solution which was called Object Linking and Embedding (OLE).

How a file is stored inside Microsoft Access (OLE Structure)?

1. Package header
2. Ole header
3. Datablock length
4. Data
5. Metafilepict block
6. Ole footer

The Package Header structure:
A Signature (short): this indicates that the file is a package
The header size (short)
An object type (uint): 0 = linked, 1= embedded, 2 = either
The length of the friendly name in the header (short)
The length of the class name in the header (short)
The offset of the friendly name (short)
The offset of the class name (short)
The size of the object (int)
The friendly name (string, variable length)
The class name (string, variable length)

The Ole Header structure:
The Ole version (uint)
The Format (uint)
The object type name length (int)
The object type name (string, variable length)
The Ole header actually ends with 8 empty bytes followed by 4 bytes that make up the length of the Datablock as an int.

The Datablock and Data structures:
Inside the datablock can be the actual file, but also there can be a structured storage. To determine if this is a structured storage, there is actually an 8 byte signature at the start of the storage.

The Metafilepict block
When you work with images, there is another block called the metafilepict block. You are not likely to find a CONTENTS element if you need to read the metafilepict block.

Where is the Metafilepict block?

The start position of the Metafilepict can be calculated by using the following formula:

Metefilepict start position = total Package Header length + total Ole Header length + 8 (empty bytes) + 4 (Data length bytes) + Data length + 45 (Metafilepict header length)

The stream at this position contains the actual image file.

Face Recognation in C#








Emgu CV is a cross platform .Net wrapper to the Intel OpenCV image processing library. Allowing OpenCV functions to be called from .NET compatible languages such as C#, VB, VC++, IronPython etc. The wrapper can be compiled in Mono and run on Linux / Mac OS X. Unlike other wrappers such as OpenCVDotNet, SharperCV which use unsafe code, Emgu CV is written entirely in C#. The benefit is that it can be compiled in Mono and therefore is able to run on any platform Mono supports, including Linux, Solaris and Mac OS X. A lot of efforts has been spend to have a pure C# implementation since the headers have to be ported, compared with managed C++ implementation where header files can simply be included. But it is well worth it if you see Emgu CV running on Fedora 10! Plus it always gives you the comfort knowing that your code is cross-platform.

Face Recognation

1- Create a Windows Form Application
2- Add a PictureBox and a Timer (and Enable it)
3- Run it on a x86 system
4- Be sure you have the OpenCV relevant dlls (included with the Emgu CV download) in the folder where you code executes.
5- Adjust the path to find the Haarcascade xml (last line of the code)

using System;
using System.Windows.Forms;
using System.Drawing;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;

namespace opencvtut
    public partial class Form1 : Form
        private Capture cap;
        private HaarCascade haar;

        public Form1()

        private void timer1_Tick(object sender, EventArgs e)
            using (Image<Bgr, byte> nextFrame = cap.QueryFrame())
                if (nextFrame != null)
                    // There is only one channel (gray scale), hence the zero index
                    // var faces = nextFrame.DetectHaarCascade(haar)[0];
                    Image<Gray, byte> grayframe = nextFrame.Convert<Gray, byte>();
                    var faces =
                    grayframe.DetectHaarCascade(haar, 1.4, 4,
                    new Size(nextFrame.Width/8, nextFrame.Height/8))[0];

                    foreach (var face in faces)
                        nextFrame.Draw(face.rect, new Bgr(0,double.MaxValue,0), 3);
                    pictureBox1.Image = nextFrame.ToBitmap();
        private void Form1_Load(object sender, EventArgs e)
            // passing 0 gets zeroth web cam
            cap = new Capture(0);
            // adjust path to find your xml
            haar = new HaarCascade(“..\\..\\..\\..\\lib\\haarcascade_frontalface_alt2.xml”);

Retrieve and Update YouTube Content in C#


The YouTube Google API for .NET developers can be used in C# or ASP.NET applications to authenticate a YouTube user, to extract information about a single video from a list of videos or a set of search results, to fetch a list of videos, to upload videos to YouTube, to interact with YouTube videos, to access, create and update favorite videos, and to subscribe to YouTube channels.

Example 1. Authenticating a YouTube User

YouTubeRequestSettings settings = new YouTubeRequestSettings(“example app”, clientID, developerKey);
YouTubeRequest request = new YouTubeRequest(settings);

Example 2.Displaying a Feed of Videos

Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
static void printVideoFeed(Feed<Video> feed)
foreach (Video entry in feed.Entries)

Example 3. Searching YouTube Videos

YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
//order results by the number of views (most viewed first)
query.OrderBy = “viewCount”;
// search for puppies and include restricted content in the search results
// query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
query.Query = “C# Learners”;
query.SafeSearch = YouTubeQuery.SafeSearchValues.None;
Feed<Video> videoFeed = request.Get<Video>(query);

Example 4. Uploading Videos to YouTube

Video newVideo = new Video();
newVideo.Title =”Serialization”;
newVideo.Tags.Add(new MediaCategory(“Autos”, YouTubeNameTable.CategorySchema));
newVideo.Keywords = “Programming, C#”;
newVideo.Description = “This video explains how to use Serialization in C#”;
newVideo.YouTubeEntry.Private = false;
newVideo.Tags.Add(new MediaCategory(“mydevtag, anotherdevtag”,
newVideo.YouTubeEntry.setYouTubeExtension(“location”, “Vancouver, BC”);
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(“c:\\Serialization.mov”,
Video createdVideo = request.Upload(newVideo);

Example 5. Adding a Favorite Video to YouTube

YouTube users can choose to mark videos that they watch as favorite videos. A user’s favorite videos feed can be retrieved from the following URL:


To add a favorite video, insert a YouTubeEntry object that identifies the video to the authenticated user’s favorite videos feed:

string videoEntryUrl = “http://gdata.youtube.com/feeds/api/videos/CSharplearners”;
YouTubeEntry videoEntry = (YouTubeEntry) service.Get(videoEntryUrl);
service.Insert(new Uri(feedUrl), videoEntry);

Cryptographic Algorithms by Applications in .NET Framework 4.0








Different implementations are available for cryptographic algorithms. For example, the base for all symmetric algorithms is SymmetricAlgorithm, which is inherited by the following algorithms: Aes, DES, RC2, Rijndael, and TripleDES.

What is AES?
Aes is inherited by two classes: AesCryptoServiceProvider and AesManaged. The AesCryptoServiceProvider class is a wrapper around the Windows Cryptography API (CAPI) implementation of Aes, whereas the AesManaged class is written entirely in managed code.

What is CNG?
There is also a third type of implementation, Cryptography Next Generation (CNG), in addition to the managed and CAPI implementations. An example of a CNG algorithm is ECDiffieHellmanCng. CNG algorithms are available on Windows Vista and later.

You can choose which implementation is best for you. The managed implementations are available on all platforms that support the .NET Framework. The CAPI implementations are available on older operating systems, and are no longer being developed. CNG is the very latest implementation where new development will take place. However, the managed implementations are not certified by the Federal Information Processing Standards (FIPS), and may be slower than the wrapper classes.

What is Stream Design?
The common language runtime uses a stream-oriented design for implementing symmetric algorithms and hash algorithms. The core of this design is the CryptoStream class, which derives from the Stream class. Stream-based cryptographic objects support a single standard interface (CryptoStream) for handling the data transfer portion of the object. Because all the objects are built on a standard interface, you can chain together multiple objects and you can perform multiple operations on the data without needing any intermediate storage for it. The streaming model also enables you to build objects from smaller objects. For example, a combined encryption and hash algorithm can be viewed as a single stream object, although this object might be built from a set of stream objects.

What is Cryptographic Configuration?
Cryptographic configuration lets you resolve a specific implementation of an algorithm to an algorithm name, allowing extensibility of the .NET Framework cryptography classes. You can add your own hardware or software implementation of an algorithm and map the implementation to the algorithm name of your choice. If an algorithm is not specified in the configuration file, the default settings are used.

How to Choose a Suitable Cryptographic Algorithm by Application?
You can select an algorithm for different reasons: for example, for data integrity, for data privacy, or to generate a key. Symmetric and hash algorithms are intended for protecting data for either integrity reasons (protect from change) or privacy reasons (protect from viewing). Hash algorithms are used primarily for data integrity. Here is a list of recommended algorithms by application:

Data privacy: Aes

Data integrity: HMACSHA256 – HMACSHA512

Digital signature: ECDsa – RSA

Key exchange: ECDiffieHellman – RSA

Random number generation: RNGCryptoServiceProvider

Generating a key from a password: Rfc2898DeriveBytes

Installed Windows Services in C#











The following code checks whether a windows services installed on your machine or not.

public static void ISWindowsServiceInstalled(string serviceName)
    // get list of Windows services
    ServiceController[] services = ServiceController.GetServices();

    foreach (ServiceController service in services)
        if (service.ServiceName == serviceName)
            return true;
    return false;

Zip Archive Class in .NET 4.5

In .NET 4.5, the System.IO.Compression namespace contains the following new classes for compressing and decompressing the streams:

1- ZipArchive which represents a Zip archive.

2- ZipArchiveEntry which represents an entry in the zip archive.

The ExtractToDirectory and CreateFromDirectory methods of ZipArchive class can be used to handle the following most used scenarios:

Scenario 1 – Unzipping: Use ExtractToDirectory method to extract all the contents of a zip archive to the specified directory

Scenario 2 – Zipping: the contents: Use CreateFromDirectory to take the contents of the directory and to zip it’s content to a zip file

Example 1. ZipArchive.CreateFromDirectory(@”docs\attach”, “attachment.zip”);

Example 2. ZipArchive.ExtractToDirectory(“Photos.zip”, @”photos\January2012″);

What is ZipArchiveEntry?

ZipArchive represents a zip archive, which is a collection of entries, and ZipArchiveEntry represents an archived file entry.
A ZipArchive class (representing a zip file ) can have one or more ZipArchiveEntry class (representing normal files like text file, doc file, pdf file etc)

The following example extracts only the text files from an archive:

using (var archive = new ZipArchive(“data.zip”))

foreach (var entry in archive.Entries)

if (entry.FullName.EndsWith(“.txt”, StringComparison.OrdinalIgnoreCase))

entry.ExtractToFile(Path.Combine(directory, entry.FullName));




Copyright © All Rights Reserved - C# Learners