Archive

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
}

//BINDING

comboBox1.DataSource = Enum.GetValues(typeof(RequestDept))
                        .Cast<RequestDept>()
                        .Select(p => new { Key = (int)p, Value = p.ToString() })
                        .ToList();
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)
    {
        try
        {
            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download 
             = downloader.CreateDownload(source, destination);
            await download.StartAsync();

            return true;
        }
        catch
        {
            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)
{
    try
    {
        //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

T1

Option #2 – By Editing XAML

In XAML mode, set control property as shown below

T2

Option #3 – Using Code Behind

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

T3

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)
{
    try
    {
        var applicationData = Windows.Storage.ApplicationData.Current;
        applicationData.LocalSettings.Values[key] = value;
        return true;
    }
    catch
    {
        return false;
    }
}
string RetrieveSettings(string key)
{
    try
    {
        var applicationData = Windows.Storage.ApplicationData.Current;
        if (applicationData.LocalSettings.Values[key] != null)
            return applicationData.LocalSettings.Values[key].ToString();
        return null;
    }
    catch
    {
        return null;
    }
}