Graph Plotting in C#








Plotting a graph from a set of test-related data is a common software-development task. In my experience, the most common approach is to import data into an Excel spreadsheet, then produce the graph manually using the Excel built-in graphing features. This works well in most situations, but if the underlying data changes frequently, creating graphs by hand can quickly become tedious.
You can automate the process using Windows Presentation Foundation (WPF) technology.

Preparing the Project for Graph Plotting 
Launch Visual Studio and create a new C# project using the WPF Application template. Although you can programmatically generate graphs using WPF primitives, I suggest using the convenient Dynamic Data Display (D3) library developed by a Microsoft Research lab.

You can download the library for free from the CodePlex open source hosting site at You should save a copy of this library in the root directory of your project, then add a reference to the DLL in your project by right-clicking on the project name, select the Add Reference option and point to the DLL file in your root directory.

Next you need to double-click on the file Window1.xaml to load the UI definitions for the project. You should add a reference to the graphic library DLL as follows:

Title="Window1" Height="500" Width="800" Background="Wheat">

After that, you can add the key plotting object:

<d3:ChartPlotter Name="plotter" Margin="10,10,20,10">
    <d3:HorizontalDateTimeAxis Name="dateAxis"/>
    <d3:VerticalIntegerAxis Name="countAxis"/>
  <d3:Header FontFamily="Arial" Content="Bug Information"/>
  <d3:VerticalAxisTitle FontFamily="Arial" Content="Count"/>
  <d3:HorizontalAxisTitle FontFamily="Arial" Content="Date"/>

The techniques that I presented here can be used to programmatically generate graphs. The key to the technique is the Dynamic Data Display (D3) library from Microsoft Research. This approach is very useful if the underlying data changes frequently.

The Model-View-ViewModel Design Pattern

The Model-View-ViewModel (MVVM) pattern helps you to cleanly separate the business and presentation logic of your application from its user interface (UI). Maintaining a clean separation between application logic and UI helps to address numerous development and design issues and can make your application much easier to test, maintain, and evolve. It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of the application.

Using the MVVM pattern, the UI of the application and the underlying presentation and business logic is separated into three separate classes:

1- The view, which encapsulates the UI and UI logic

2- The view model, which encapsulates presentation logic and state

3- The model, which encapsulates the application’s business logic and data

The MVVM pattern is a close variant of the Presentation Model pattern, optimized to leverage some of the core capabilities of WPF, such as data binding, data templates, commands, and behaviors. In the MVVM pattern, the view interacts with the view model through data binding, commands, and change notification events. The view model queries, observes, and coordinates updates to the model, converting, validating, and aggregating data as necessary for display in the view.

The following illustration shows the three MVVM classes and their interaction.







The View Class

The view’s responsibility is to define the structure and appearance of what the user sees on the screen. Ideally, the code-behind of a view contains only a constructor that calls the InitializeComponent method. The view usually has the following key characteristics:

– The view is a visual element, such as a window, page, user control, or data template.
– The view defines the controls contained in the view and their visual layout and styling.
– The view references the view model through its DataContext property.
– The controls are data bound to properties and commands exposed by the view model.
– The view may customize the data binding behavior between the view and the view model.
– The view defines and handles UI visual behavior, such as animations.
– The view’s code-behind may implement visual behavior that is difficult to express in XAML.

The View Model Class

The view model in the MVVM pattern encapsulates the presentation logic for the view. It has no direct reference to the view or any knowledge about the view’s specific implementation or type. The view model implements properties and commands to which the view can data bind and notifies the view of any state changes through change notification events. The properties and commands that the view model provides define the functionality to be offered by the UI, but the view determines how that functionality is to be rendered.

The view model is responsible for coordinating the view’s interaction with any model classes that are required. Typically, there is a one-to many-relationship between the view model and the model classes. The view model may choose to expose model classes directly to the view so that controls in the view can data bind directly to them. The view model may convert or manipulate model data so that it can be easily consumed by the view.

The view model may also define logical states the view can use to provide visual changes in the UI. The view may define layout or styling changes that reflect the state of the view model. For example, the view model may define a state that indicates that data is being submitted asynchronously to a web service. The view can display an animation during this state to provide visual feedback to the user.

Typically, the view model will define commands or actions that can be represented in the UI and that the user can invoke. A common example is when the view model provides a Submit command that allows the user submit data to a web service or to a data repository. The view may choose to represent that command with a button so that the user can click the button to submit the data. Typically, when the command becomes unavailable, its associated UI representation becomes disabled. The view model usually has the following key characteristics:

– The view model is a non-visual class. It encapsulates the presentation logic.
– The view model is testable independently of the view and the model.
– The view model typically does not directly reference the view.
– The view model implements properties and commands to which the view can data bind.
– The view model notifies the view of any state changes via change notification events:
INotifyPropertyChanged and INotifyCollectionChanged
– The view model coordinates the view’s interaction with the model.
– The view model may define logical states that the view can represent visually to the user.

The Model Class

The model in the MVVM pattern encapsulates business logic and data. Business logic is defined as any application logic that is concerned with the retrieval and management of application data and for making sure that any business rules that ensure data consistency and validity are imposed. To maximize re-use opportunities, models should not contain any use case–specific or user task–specific behavior or application logic.

Typically, the model represents the client-side domain model for the application. The model may also include the code to support data access and caching, though typically a separate data repository or service is employed for this. Often, the model and data access layer are generated as part of a data access or service strategy, such as the ADO.NET Entity Framework, WCF Data Services, or WCF RIA Services.

The model implements the facilities that make it easy to bind to the view. This usually means it supports property and collection changed notification through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Models classes that represent collections of objects typically derive from the ObservableCollection<T> class, which provides an implementation of the INotifyCollectionChanged interface.

The model may also support data validation and error reporting through the IDataErrorInfo (or INotifyDataErrorInfo) interfaces. These interfaces allow WPF data binding to be notified when values change so that the UI can be updated. The model usually has the following key characteristics:

– Model classes are non-visual classes that encapsulate the application’s data.
– The model classes do not directly reference the view or view model classes.
– The model classes have no dependency on how they are implemented.
– The model classes typically provide property and collection change events through:
INotifyPropertyChanged/INotifyCollectionChanged interfaces.
– The Model classes typically derive from the ObservableCollection<T> class.
– The model classes typically provide data validation and error reporting through:
– The model classes are typically used with a service that encapsulates data access.

TPL Performance Improvements in .NET 4.5

Task.WaitAll and Task.WaitAny

Task’s waiting logic in .NET 4.5 has been changed. The performance gain for this change is most apparent when waiting on multiple Tasks, such as when using Task.WaitAll and Task.WaitAny.

Let’s explore the extent of this performance boost with this benchmark code for Task.WaitAll:

public static Tuple TestWaitAll(int ntasks)
            Task[] tasks = new Task[ntasks];
            Action action = () => { };
            for (int i = 0; i < ntasks; i++) tasks[i] = new Task(action);
            Stopwatch sw = new Stopwatch();
            long startBytes = GC.GetTotalMemory(true);
            Task.WaitAll(tasks, 1);
            long endBytes = GC.GetTotalMemory(true);
            return Tuple.Create(sw.ElapsedMilliseconds, endBytes - startBytes);

The code above times the overhead of setting up a WaitAll for ntasks uncompleted Tasks, plus a one millisecond timeout. This test is admittedly less than perfectly precise, as the actual time before the WaitAll call times out could be anywhere from 1 millisecond to the scheduler quantum of the underlying operating system. Nevertheless, the test results still shed some light on the performance differences between .NET 4 and .NET 4.5 for this scenario:

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.

Visual Basic 6 and LINQ






Is it possible to use LINQ and Lambda Expressions in Visual Basic 6?

One solution is to use COM Interop. When a COM client like Visual Basic 6 calls a .NET COM object, the common language run-time creates the managed object and a COM callable wrapper (CCW) for the object.

What is COM callable wrapper (CCW) ?

Code that operates within the .NET Common Language Runtime (CLR) is called managed code. This code has access to all the services that the CLR brings to the table, such as cross-language integration, security and versioning support, and garbage collection. Code that does not operate within the CLR is called unmanaged code. Because COM was designed before the CLR existed, and COM code does not operate within the infrastructure provided by the CLR, it can’t use any of the CLR services. All of your COM components are, by definition, unmanaged code.
Managed code components not only depend on the CLR, they require the components with which they interact to depend on the CLR. Because COM components don’t operate within the CLR, they are unable to call managed code components directly. The unmanaged code simply cannot reach into the CLR to directly call managed components. The way out of this dilemma is to use a proxy. In general terms, a proxy is a piece of software that accepts commands from a component, modifies them, and forwards them to another component. The particular type of proxy used in calling managed code from unmanaged code is known as a COM callable wrapper, or CCW.

If you need to use LINQ and Lambda Expressions in your Visual Basic 6 code, you can create a .NET component and expose it to the COM environment using CCW process. For creating .NET components, you can use a class library template and you need to follow the following steps to register your .NET COM for COM interop.

Step 1. With a project selected in Solution Explorer, on the Project menu, click Properties.
Step 2. Click the Compile tab in Visual Basic. Click the Build tab in C#.
Step 3. Select the Register for COM interop check box.

When you build your project, it creates a dll file together with a type library file (tlb) that COM client such as VB6 requires to establish the communication. The following example shows how to create a .NET COM with the required interfaces assuming the Register for COM interop is already checked.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace VB6andLINQ
    public interface _BrowseDirectory
        Int32 GetFilesUsingLINQ(string sourceDir);

    public class BrowseDirectory : _BrowseDirectory
        static int MatchedCount = 0;
        public Int32 GetFilesUsingLINQ(string sourceDir)  
            string[] fileNames = null;
                fileNames = Directory.GetFiles(sourceDir, "*.txt",
            catch (UnauthorizedAccessException e)
                Console.WriteLine("You do not have permission to access one or more" +
                                     " folders in this directory tree.");
            catch (FileNotFoundException)
                Console.WriteLine("The specified directory {0} was not found.", 
            string searchTerm = "binding";
            var fileContents = from file in fileNames.AsParallel()
                               from line in File.ReadLines(file)
                               where line.Contains(searchTerm)
                               select new { File = file, Line = line };
                foreach (var item in fileContents)
            catch (AggregateException ae)
                ae.Handle((ex) =>
                    if (ex is UnauthorizedAccessException)
                        return true;
                    return false;
            Console.WriteLine("\nFound {0} match(es) for the word \"{1}\" in {2}.",
                                                MatchedCount, searchTerm, sourceDir);
            return MatchedCount;

Task Creation Performance in .NET 4.5

In this post, I will compare the Task creation performance in .NET 4 and .NET 4.5.

I will measure both time and memory consumption associated with Task creation:

public static Tuple<long, long> CreateTasks(int ntasks)
    Task[] tasks = new Task[ntasks];
    Stopwatch sw = new Stopwatch();
    Action action = () => { };
    long startBytes = GC.GetTotalMemory(true);
    for (int i = 0; i < ntasks; i++) tasks[i] = new Task(action);
    long endBytes = GC.GetTotalMemory(true);
    return Tuple.Create(sw.ElapsedMilliseconds,endBytes-startBytes);

The results on my test machine are as follows:



The benchmark results do indeed show the smaller footprint of a Task in .NET 4.5, in addition to the decreased amount of time that it takes to create Tasks.

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:\\”,
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 = “”;
YouTubeEntry videoEntry = (YouTubeEntry) service.Get(videoEntryUrl);
service.Insert(new Uri(feedUrl), videoEntry);

Copyright © All Rights Reserved - C# Learners