Archive for the ‘C#’ Category

C# 5.0 – Caller Information

November 27, 2013 Leave a comment

Caller information is introduced in C# 5. This feature is directly available in Visual Studio 2012. As the name suggests, caller information is a set of attributes which can be used to obtain information about caller to a method.

Attributes include, path of the source code, line number, and the member name of the caller. This information is vital in case of debugging or tracing application issues.

CallerFilePathAttribute – String type attribute, this will provide the file path at compile time.

CallerLineNumberAttribute – Integer type attribute, this will provide the line number at which the method is invoked.

CallerMemberNameAttribute – String type attribute, this will provide the Method/Property name of the caller.

Caller information attributes can be specified only to optional parameters. We should also specify a default value. Below example show a typical logging method

Log("Log this");
public void Log(string messageToLog,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string filePath = "",
        [CallerLineNumber] int lineNumber = 0)
    //Log the details

To make this working, we should include following using statements

using System.Runtime.CompilerServices 
using System.Diagnostics;
Categories: C# Tags: ,

C# – Binding ComboBox with Enum

November 5, 2013 Leave a comment

A simple snippet that can be used to bind enum values to a combobox control

public enum RequestDept
    CallCenter = 0,
    Development = 1,
    Enrollment = 2,
    Implementation = 3,
    Sales = 4,
    Support = 5


comboBox1.DataSource = Enum.GetValues(typeof(RequestDept))
                        .Select(p => new { Key = (int)p, Value = p.ToString() })
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

//Selecting an Item

comboBox1.SelectedValue = 3;

Categories: C# Tags:

Windows 8 – Downloading File

Here is a snippet for downloading file using C#

    async Task<bool> DownloadFile(Uri source, StorageFile destination)
            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download 
             = downloader.CreateDownload(source, destination);
            await download.StartAsync();

            return true;
            return false;

If you want to show progress indicator, then add a ProgressBar object into the UI. And use StartAsync().AsTask(Progress)

Windows 8 – Validate URL

Sample code for validating URL’s.

Invoke below method and pass the URL.

private async Task<bool> UriExists(string url)
        //Validate whether url has a valid uri pattern
        if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
            return false;

        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = 
            await request.GetResponseAsync() as HttpWebResponse;

        if (response.StatusCode == HttpStatusCode.OK || 
            response.StatusCode == HttpStatusCode.Forbidden)
            return true;
    catch(WebException ex)
        HttpWebResponse r = ex.Response as HttpWebResponse;
        if (r.StatusCode == HttpStatusCode.Forbidden)
            return true;
    return false;

Windows 8 – Display ToolTip

Tool tips are important for a user friendly application. In this post I am going to explain how we can set tool tip for Windows Store Applications

Option #1 – Using Properties Window

In design mode, open the control properties. And set the “ToolTipService.ToolTip” property


Option #2 – By Editing XAML

In XAML mode, set control property as shown below


Option #3 – Using Code Behind

        ToolTip textUriTip = new ToolTip();
        textUriTip.Content = "New ToolTip";
        ToolTipService.SetToolTip(usr, textUriTip);


C# – Regular Experssion Match Pattern Exclude Words

Recently I got a problem for parsing html tags and replacing with different tags.

For example: Find all b tags and replace them with strong

<b>This is a bold text</b> Lorem Ipsum is simply dummy text 
<b>some more bold text</b> 
Lorem Ipsum is simply dummy text <b> again bold text </b>

Convert above to

<strong>This is a bold text</strong> Lorem Ipsum is simply dummy text 
<strong> some more bold text </strong> 
Lorem Ipsum is simply dummy text <strong> again bold text </strong>

First I thought of using simple string replacement, but that won’t work in all cases.
Then I thought of splitting and parsing each token to solve. This require lots of code
and in some corner cases fails. Now only option left with me is Regular expressions.
Here again I got into several issues, but finally I came up with below.

    string strRegex = @"\<b\>((.|\n)*?)\<\/b\>";
    RegexOptions myRegexOptions = RegexOptions.Multiline;
    Regex myRegex = new Regex(strRegex, myRegexOptions);
    string strReplace = @"<strong>$1</strong>";
    string newstring = myRegex.Replace(inputstring, strReplace);
Categories: C#, Misc Tags: , ,

Windows 8 – How to save & retreive application settings

February 26, 2013 Leave a comment

Windows 8 store applications don’t have application configuration files. Hence storing application level settings is done in a different way.

Each application has an ApplicationDataContainer. Its mutable and specific for each application. System internally manages the data by isolating it from other applications settings. Hence its more secure & reliable.

Current architecture offers 3 types of storage

  • Local – Here data is stored locally on the device
  • Roaming – Here data exists on all devices
  • Temporary – Temporary data

Here are two methods which you can use for saving and retrieving application data.

using Windows.Storage;

bool SaveSettings(string key, string value)
        var applicationData = Windows.Storage.ApplicationData.Current;
        applicationData.LocalSettings.Values[key] = value;
        return true;
        return false;
string RetrieveSettings(string key)
        var applicationData = Windows.Storage.ApplicationData.Current;
        if (applicationData.LocalSettings.Values[key] != null)
            return applicationData.LocalSettings.Values[key].ToString();
        return null;
        return null;

SharePoint – Using C# change workflow task owner

February 13, 2013 2 comments

Assume we have a workflow task as below


Currently its assigned to “Amal Hashim”. We can change this to another user say, “Administrator” using following snippet

using (SPSite site = new SPSite("http://myteamsite:2012/"))
    using (SPWeb web = site.OpenWeb())
        SPUser user = web.SiteUsers["myad\\administrator"];
        SPListItem taskItem = web.Lists["Shared Documents"].Items[0];

        SPWorkflowTaskCollection taskCollection = new 
SPWorkflowTaskCollection(taskItem, new SPWorkflowFilter());

        foreach (SPWorkflowTask task in taskCollection)
            Hashtable ht = new Hashtable();
            ht[SPBuiltInFieldId.AssignedTo] = user;
            SPWorkflowTask.AlterTask((task as SPListItem), ht, true);

After executing this, we will get


Categories: C#, SharePoint, SharePoint 2010 Tags:

Windows 8 Store App Development – Pre Requisites

January 20, 2013 Leave a comment

App Development for Windows 8 is all together a new story for developers. So I thought to outline the steps here so it will benefit the community.

  1. Windows 8 Operating System
  2. Visual Studio 2012
  3. Developer License

On my laptop I am using Windows 7, since its configured with all software I don’t want to do a fresh install or upgrade to Windows 8. So my options left are either use a VPC or dual boot windows 8. Dual booting needs a new dedicated drive. In order to create a new drive, I shrink one of my drive using Windows disk management tool. The new drive should have

  • Enough storage space to accommodate Windows 8 installation
  • Either Primary or Logical drive (Dynamic drives won’t work)

This setup helps me to keep my current environment intact and it give me the flexibility to play with Windows 8.

Installation Process was straight forward. And it completed pretty quickly. The installer was Windows Enterprise edition, hence I was unable to enter the product key. After searching on this topic, I found a command Slui.exe 0x3 which enables this. Read this KB article.

Next, installed Visual Studio 2012.

From Visual Studio, New Project


Once Visual Studio finishes creating the Project, it will try to get the developer license. First a popup window is displayed, on this we should read and accept the terms and condition. Next another popup asks for Microsoft logon credentials. Finally a success message showing the license information such as validity etc.

Normally the license is valid for 30 days, after that we can renew it for next 30 days and so on. On the other hand if you have a Store account, then the developer license validity is 90 days.

I started developing my first app on Windows 8. I will be explain my experience on next post.

Categories: C#, Windows, Windows 8

C# FileSystemWatcher

October 16, 2012 Leave a comment

Here is a code sample which explains the concept of FileSystemWatcher class

using System;
using System.IO;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            FileSystemWatcher watcher = new 
FileSystemWatcher("c:\\LogFiles\\", "log.txt");
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.EnableRaisingEvents = true;

        static void watcher_Changed(object sender, FileSystemEventArgs e)
            if (e.ChangeType == WatcherChangeTypes.Changed)
                using (TextWriter writer = new 
StreamWriter("C:\\ModifiedHistory.txt", true))
Categories: C#