Sponsors

Thứ Năm, 8 tháng 8, 2013

Project Euler

I came across the Project Euler site the other day. If you enjoy solving mathematical/programming problems then I recommend this site. You're given a number of problems to solve with each problem in the series getting progressively more difficult. If you sign up, you can submit your answer and if your answer is correct then you'll get access to the message boards for the problem you worked on. The problem message boards are where you can share your solution and see solutions by other people who may have used a different programming language. It's interesting to see the C# solutions compared to the solutions in other languages. Worth a look if you have time!

Chủ Nhật, 28 tháng 7, 2013

Implicit/Explicit Conversion Operators

I saw some code yesterday which at first glance looked odd. A method was accepting a parameter of a custom type named Money and the calling code was passing in a double value. After a bit of confusion I recalled that the C# language natively supports conversion operators.

If you have a custom type, you have the option to define conversion operators on your type which let you convert from your custom type to a target type and from the target type back to the custom type. Conversion can be implicit or explicit. Implicit conversion means that users of your custom type can convert to the target type without having to perform a type cast operation. Explicit conversion forces a type cast to be performed.

To demonstrate this, we'll use the case I came across. Imagine we have a Money class which is composed of a currency and a value that the money represents. We may initially decide that we want the Money class to be flexible so that users of the class can treat it is a value (a double type in this case). This means that when a double is expected (e.g. as an argument to a method), the user of the class can pass the Money instance which will implicitly be converted to its value form. Moreover, we can also make the conversion from double to Money implicit, meaning that whenever a Money instance is expected, we can pass in a double. Our initial attempt at the Money class implementation would therefore look something like:
public class Money
{
    public string Currency { get; set; }
    public double Value { get; set; }

    // Implicit conversion from Money to double
    public static implicit operator double(Money money)
    {
        return money.Value;
    }

    //  Implicit conversion from double to Money
    public static implicit operator Money(double @double)
    {
        return new Money { Value = @double };
    }
}
With the above class, the following code would therefore compile:
var money = new Money() { Currency = "GBP", Value = 10.5 };
            
// Implicitly convert Money to a double
double moneyValue = money;

// Convert a double to Money (Money.Currency will be null!)
Money moneyInstance = moneyValue;
Notice that when converting a Money instance to a double, we would lose information on the Money instance (the currency in this case). Also, when converting a double to a Money, the currency is never set. It would therefore make more sense in this scenario to use explicit conversion operators so that the user is forced to be aware that they could lose information in the conversion or have a partially initialised Money instance (it isn't a straight-forward conversion). To define explicit conversion on the Money class, the only change required would be to replace the "implicit" keyword with the "explicit" keyword on the two conversion methods. The Money class would now look like:
public class Money
{
    public string Currency { get; set; }
    public double Value { get; set; }

    // Explicit conversion from Money to double
    public static explicit operator double(Money money)
    {
        return money.Value;
    }

    //  Explicit conversion from double to Money
    public static explicit operator Money(double @double)
    {
        return new Money { Value = @double };
    }
}
After making this change, the example calling code above would fail to compile with the following two compile-time error messages:

Cannot implicitly convert type 'ConversionOperators.Money' to 'double'. An explicit conversion exists (are you missing a cast?)
Cannot implicitly convert type 'double' to 'ConversionOperators.Money'. An explicit conversion exists (are you missing a cast?)

As the errors point out, we now need to explicitly cast between the types - as demonstrated in the code below.
var money = new Money() { Currency = "GBP", Value = 10.5 };
            
double moneyValue = (double) money;

Money moneyInstance = (Money) moneyValue;

You can download the example code by clicking here.

Chủ Nhật, 7 tháng 7, 2013

JQuery DataTables Editable in Asp.net c#


Asp.Net How To Edit JQuery DataTables Using Asp.Net GridView , C#

The purpose of this article is to show how you can implement JQuery DataTables   with Asp.net Gridview Control. The jQuery DataTables plugin is an excellent client-side component. This plugin adds lots of functionalities to the plain HTML tables that are placed in web pages such as  sorting, searching, pagination, changing page length etc

HTML Markup:
Here you will see in html markup theres a pencil image which on click becomes editable  and so user can edit the values also look at classname .i.e set classname as update_ + id  using string.Concat().   where id is  database rowId.

<asp:GridView ID="myGridview" runat="server" BackColor="White"   AutoGenerateColumns="False" CssClass="gvmyalign"    
       BorderColor="Gray" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"  ForeColor="Black" GridLines="None" Width="500px"
       AllowPaging="True"  ShowFooter="false"  >
       <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#A86E07" Font-Bold="True" ForeColor="White" />
           <Columns>
            <asp:TemplateField HeaderText="Id" Visible="false">
              <ItemTemplate>
                    <asp:Label ID="lblid" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
              </ItemTemplate>
              </asp:TemplateField>
               <asp:TemplateField HeaderText="Name"   ItemStyle-Width="230">
                 <ItemTemplate>
                       <asp:Label ID="lblname" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                 </ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField ShowHeader="False" ItemStyle-Width="90" >
               <ItemTemplate>
                 <asp:Image ID="Image1" ToolTip="Edit" style="cursor:pointer;" CssClass=' <%# string.Concat("update_",Eval("Id")) %>' ImageUrl="~/images/pencil.png" runat="server" />
                </ItemTemplate>
           </asp:TemplateField>
        </Columns>
       <PagerStyle BackColor="#A86E07" ForeColor="White" HorizontalAlign="Center" />
    <EditRowStyle BackColor="#d9d9d9" />
  <AlternatingRowStyle BackColor="White" ForeColor="#A86E07" />
</asp:GridView>

Code Behind: DefaultPage.aspx
You need to add Page_PreRender event on .cs where we set gridview's UseAccessibleHeader=true .
protected void  (object sender, EventArgs e)
{
if (myGridview.Rows.Count > 0) {
myGridview.UseAccessibleHeader = true;
myGridview.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}

protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) { gvBind(); }
}

public void gvBind() {
myGridview.EmptyDataText = "No Record";
DataTable dt = getData();
myGridview.DataSource = dt;
myGridview.DataBind();
}

Now the Real coding part comes here using JQuery Datatables .
Add JqueryDatable Script Files 
<link href="jquery.dataTables_themeroller.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery.dataTables.js" type="text/javascript"></script>
<script src="../js/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var oTable;
$(".gvmyalign span").contents().unwrap();
oTable = $(".gvmyalign").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"

});
});
</script>
Now after apply JQuery DataTable Gridview look like below image. ScreenShot:
Now:


Edit Mode:


Edit Row:On Click of pencil image we convert Lable into Textboxes and place it inside JQueryDatables which we stored using variable oTable. Here on EDIT mode we replace pencil image with SAVE and CANCEL image button, also set respected ids into classes as same we did for pencil img. On cancle img click we Undo editmode, when the user finishes editing an click Save img button a AJAX call is sent to the server-side page that updates the records into database. Also u need to check some JQuery Datatable's method which have used like fnUpdate(),  fnDraw(),  fnGetData(nRow);

Client Side:

<script type="text/javascript">

var oTable;
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
var gtval = aData[1];
var absValue = $("#hdid").val();
var mySav_Class = absValue.replace('update_', 'sav_');
var myCnl_Class = absValue.replace('update_', 'cnl_');
var sname = $("#hdname").val();

jqTds[0].innerHTML = '<input class="edt1" type="text" value="' + sname + '">';
jqTds[1].innerHTML = '<img class="' + mySav_Class + '" title="Save" src="save.png" /><img class="' + myCnl_Class + '" title="Cancel" src="cancle.png" />';
}

function restoreRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
oTable.fnUpdate(aData[i], nRow, i, false);
}
oTable.fnDraw();
}

function updatevalidDatarow() {
if ($('.edt1').val() == "") {
alert("Enter name.");
return false
}
return true;
}

$(document).ready(function () {

//One Pencil Img click make it editable mode
var nEditing = null;
$("img[class^='update_']").live('click', function (event) {
event.preventDefault;
var getId = $(this).attr("class");
$("#hdid").val(getId); // hdid is hidden field
var nRow = $(this).parents('tr')[0];
var setName = $.trim($(this).closest('tr').find('td').eq(0).text());
$("#hdname").val(setName); // hdname is hidden field

if (nEditing !== null && nEditing != nRow) {
restoreRow(oTable, nEditing);
editRow(oTable, nRow);
nEditing = nRow;
}
else {
editRow(oTable, nRow);
nEditing = nRow;
}
});

//On cancle Img click undo editable mode ie not editable
$("img[class^='cnl_']").live('click', function (event) {
var abc = $(this).attr("class");
var datetxt = $("#hdname").val();
$('.edt1').replaceWith(datetxt);
var arr = [];
arr = abc.split('_');
var id = arr[1];
var updateclass = "update_" + id;
var updatebtn = '<img src="pencil.png" style="cursor:pointer;" title="Edit" class="' + updateclass + '">';
$('.' + abc).replaceWith(updatebtn);
$('.sav_' + id).replaceWith("");
});


//On save Img Click update Query fire and saves the record into database.
$("img[class^='sav_']").live('click', function (event) {
var s = $(this).attr('class');
var arr = [];
arr = s.split('_');
var id = arr[1];
var updateclass = "update_" + id;
var updatebtn = '<img src="pencil.png" title="Edit" style="cursor:pointer;" class="' + updateclass + '">';
var upName = $(".edt1").val();
var dataString = id+"="+upName;
var nposition = $(this).closest("td").get(0);
var aPosition = oTable.fnGetPosition(nposition);

if (updatevalidDatarow()) {

$.ajax({
type: "POST",
url: "ajax_function/updatefn.asmx/updateName",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var success = data.d;
if (success == "Record Updated") {
alertify.alert("Record is updated successfully.");
$('.edt1').replaceWith(upName);
$('.' + s).replaceWith(updatebtn);
$('.cnl_' + id).replaceWith("");
nEditing = null;
oTable.fnUpdate(upName, aPosition[0], 0, false);
oTable.fnDraw();
}
},
error: OnErrorCall
});
}
});
function OnErrorCall(response) {
alert(response.statusText);
}

$(".gvmyalign span").contents().unwrap();
oTable = $(".gvmyalign").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"

});
});
</script>

Server Side: 

Code Behind : updatefn.asmx 
In updatefn.asmx  we have a WebMethod  updateName(), whicih fires Update query and return result stuatus. which we will display as resulting message on ajax call of success.
[WebMethod]
public string[] updateName(string prefix)
{
List d = new List();
string resultmessage = "";
string[] value = prefix.Split('=');
int update_id = Convert.ToInt32(value[0]);
string update_name = value[1];
int result = updateIndustry_Query(update_id, update_name);
if (result > 0)
{ resultmessage = "Record Updated"; }

d.Add(string.Format("{0}",resultmessage));
return d.ToArray();
}



Soundex Algorithm in C#

I caught the end of a conversation about the Soundex algorithm at work the other day which inspired me to write an implementation of it in C#. If you are not familiar with what Soundex is then the Wikipedia article on Soundex is a good place to start. I first came across this algorithm in a Natural Language Processing module during my university education. In a nutshell, when the Soundex algorithm is applied to a word, a Soundex Code is produced as output. Words that differ in spelling but sound the same (homophones) should produce the same Soundex Codes. For instance, "to" and "two" are spelt differently, but sound the same and therefore produce the same Soundex Code of "T000".

This is a useful little algorithm and I particularly like it for its simplicity and the fact that the heuristics used in the algorithm work well in most cases (one limitation of Soundex is that it falls short of covering words that sound the same but have a different first letter, e.g. "site" and "cite" produce different Soundex codes). Soundex is useful when writing search functionality where you want to account for misspellings in the users query. It's worth pointing out that SQL Server natively supports Soundex (see the Soundex function in T-SQL, for example).

My C# implementation is below - I opted to implement it in a static class that exposes one public method "For". You can download the Visual Studio solution from here (the zip contains a class library project with a corresponding test project). Note that the downloadable solution includes code comments.

public static class Soundex
{
    public static string For(string word)
    {
        const int MaxSoundexCodeLength = 4;

        var soundexCode = new StringBuilder();
        var previousWasHOrW = false;

        word = Regex.Replace(
            word == null ? string.Empty : word.ToUpper(),
                @"[^\w\s]", 
                    string.Empty);

        if (string.IsNullOrEmpty(word)) 
            return string.Empty.PadRight(MaxSoundexCodeLength, '0');

        soundexCode.Append(word.First());

        for (var i = 1; i < word.Length; i++)
        {
            var numberCharForCurrentLetter = 
                GetCharNumberForLetter(word[i]);

            if (i == 1 && 
                    numberCharForCurrentLetter == 
                        GetCharNumberForLetter(soundexCode[0]))
                continue;

            if (soundexCode.Length > 2 && previousWasHOrW && 
                    numberCharForCurrentLetter == 
                        soundexCode[soundexCode.Length - 2])
                continue;

            if (soundexCode.Length > 0 && 
                    numberCharForCurrentLetter == 
                        soundexCode[soundexCode.Length - 1])
                continue; 

            soundexCode.Append(numberCharForCurrentLetter);

            previousWasHOrW = "HW".Contains(word[i]);
        }

        return soundexCode
                .Replace("0", string.Empty)
                    .ToString()
                        .PadRight(MaxSoundexCodeLength, '0')
                            .Substring(0, MaxSoundexCodeLength);
    }

    private static char GetCharNumberForLetter(char letter)
    {
        if ("BFPV".Contains(letter)) return '1';
        if ("CGJKQSXZ".Contains(letter)) return '2';
        if ("DT".Contains(letter)) return '3';
        if ('L' == letter) return '4';
        if ("MN".Contains(letter)) return '5';
        if ('R' == letter) return '6';

        return '0';
    }
}
Example:

// Both lines below output R100
Console.WriteLine(Soundex.For("Ravi"));
Console.WriteLine(Soundex.For("Ravee"));

Chủ Nhật, 9 tháng 6, 2013

C# Set Implementation (pre-.NET 3.5)

I was recently working on a .NET 3.0 project and found that this version of the framework didn't have any support for a mathematical Set collection. As of .NET 3.5 there is the System.Collections.Generic.HashSet implementation, however, I was working on a WinForms project and updating the framework on the client machines was out of scope for this piece of work.

I had some spare time available and thought it would be a good exercise to write a custom generic Set collection. The first step was to define an interface:

using System.Collections.Generic;

...

public interface ISet<T> : ICollection<T>
{
    void UnionWith(ISet<T> set);
    void IntersectWith(ISet<T> set);
}

By inheriting from ICollection, we get all of the generally useful collection-based methods included in the ISet interface (e.g. Add, Clear, Contains etc.). I just had two methods to add to those, these were the set union and set intersection operations.

The next step was the implementation of the set. To keep things simple, I opted for a list-based implementation. I used the adapter pattern to map the ISet interface to a list interface. Therefore, the internal representation of the Set was actually an instance of System.Collections.Generic.List. By using this approach, I could delegate a lot of the method logic to use the list method implementations (i.e. Clear, Contains, CopyTo and Remove). The only custom logic I needed to write was the Add method (to avoid adding items already within the set), UnionWith method, IntersectWith method, ToString method and the readonly indexer. The implementation is below:

/// <summary>
/// A list-based implementation of a mathematical set.
/// </summary>
public sealed class ListBasedSet<T> : ISet<T>
{
    private IList<T> _thisSet = new List<T>();

    /// <summary>
    /// Gets the number of elements contained in this set.
    /// </summary>
    public int Count { get { return _thisSet.Count; } }

    /// <summary>
    /// Gets a value indicating whether this set is readonly.
    /// </summary>
    public bool IsReadOnly { get { return false; } }

    /// <summary>
    /// Gets the item at the specified index in the set.
    /// </summary>
    /// <param name="i">
    /// Index of the item to retrieve from the set.
    /// </param>
    /// <returns>Item at the specified index</returns>
    public T this[int i] { get { return _thisSet[i]; } }

    /// <summary>
    /// Adds item into the set if this set does not already
    /// contain the item.
    /// </summary>
    /// <param name="item">Item to add to the set.</param>
    public void Add(T item)
    {
        if (!Contains(item))
            _thisSet.Add(item);
    }

    /// <summary>
    /// Clears the items from the set resulting in an empty set.
    /// </summary>
    public void Clear()
    {
        _thisSet.Clear();
    }

    /// <summary>
    /// Determines if the specified item is within the set.
    /// </summary>
    /// <param name="item">
    /// The object to locate in the set.
    /// </param>
    /// <returns>
    /// true if item is found in the set; false otherwise.
    /// </returns>
    public bool Contains(T item)
    {
        return _thisSet.Contains(item);
    }

    /// <summary>
    /// Copies the entire set to a one-dimensional array, 
    /// starting at the specified target index of the target 
    /// array.
    /// </summary>
    /// <param name="array">
    /// The one-dimensional array to copy to.
    /// </param>
    /// <param name="arrayIndex">
    /// The zero-based index in array at which copying begins.
    /// </param>
    public void CopyTo(T[] array, int arrayIndex)
    {
        _thisSet.CopyTo(array, arrayIndex);
    }

    /// <summary>
    /// Removes the specified item from the set.
    /// </summary>
    /// <param name="item">Item to remove.</param>
    /// <returns>
    /// true if item is successfully removed; otherwise, false. 
    /// This method also returns false if item was not found 
    /// in the set.
    /// </returns>
    public bool Remove(T item)
    {
        return _thisSet.Remove(item);
    }

    /// <summary>
    /// Returns an enumerator that iterates through the set.
    /// </summary>
    /// <returns>
    /// An IEnumerator object that can be used to iterate 
    /// through the set.
    /// </returns>
    public IEnumerator<T> GetEnumerator()
    {
        return _thisSet.GetEnumerator();
    }

    /// <summary>
    /// Returns an enumerator that iterates through the set.
    /// </summary>
    /// <returns>
    /// An IEnumerator object that can be used to iterate 
    /// through the set.
    /// </returns>
    System.Collections.IEnumerator 
        System.Collections.IEnumerable.GetEnumerator()
    {
        return _thisSet.GetEnumerator();
    }

    /// <summary>
    /// Modifies this set to contain all elements that are 
    /// present in itself, the specified collection, or both.
    /// </summary>
    /// <param name="otherSet">The set to union with.</param>
    public void UnionWith(ISet<T> otherSet)
    {
        foreach (var item in otherSet)
            Add(item);
    }

    /// <summary>
    /// Modifies this set to contain only the elements that are 
    /// present in it and in the specified collection.
    /// </summary>
    /// <param name="otherSet">The set to intersect with.</param>
    public void IntersectWith(ISet<T> otherSet)
    {
        var itemsToRemove = new List<T>();

        for (int i  = 0; i < Count; i++)
        {
            T item = this[i];

            if (!otherSet.Contains(item))
                itemsToRemove.Add(item);
        }

        foreach (var itemToRemove in itemsToRemove)
            Remove(itemToRemove);
    }

    /// <summary>
    /// Returns a string representation of this set
    /// </summary>
    /// <returns>A string representation of this set</returns>
    public override string ToString()
    {
        var setStringBuilder = new StringBuilder();
        setStringBuilder.Append("{");

        foreach (var item in _thisSet)
            setStringBuilder.Append(
                string.Format(" {0},", item));
            
        return string.Format("{0} }}", 
            setStringBuilder.ToString().TrimEnd(','));
    }
}

Example usage:
ISet<string> set = new ListBasedSet<string> 
    { "Mars", "Earth", "Pluto" };
ISet<string> otherSet = new ListBasedSet<string> 
    { "Jupiter", "Earth", "Pluto", "Venus" };
ISet<string> earthSet = new ListBasedSet<string> 
    { "Earth" };
ISet<string> emptySet = new ListBasedSet<string>();

set.UnionWith(otherSet);
Console.WriteLine("set UNION otherset = {0}", set);

Console.WriteLine("|set| (cardinality of set) = {0}", set.Count);

set.IntersectWith(earthSet);
Console.WriteLine("set INTERSECTION earthSet = {0}", set);

set.UnionWith(emptySet);
Console.WriteLine("set UNION emptySet = {0}", set);

set.IntersectWith(emptySet);
Console.WriteLine("set INTERSECTION emptySet = {0}", set);

You can download the source files for the ISet interface and the ListBasedSet class from here.

Thứ Tư, 15 tháng 5, 2013

Gridview Sorting on Header Click with Paging bind with DataTable in Asp.Net C#

Gridview Sorting on Column Header Click in Ascending / Decending order binding DataTable ASp.net c# with Paging

In this article im going to give some overview on how to  SORT the data when user click on Gridview Header cell. Also I recommend you have a look at my Previous Article about Gridview Add/Update/Delete functionality.

Though there are lot of articles on web which explains paging and sorting, theres some reasons which differs this article from other articles. ie Here Gridview control is bind with Datatable as in other article you found using ObjectDataSource also Paging not supported.

Recently I was working with GridView control and I was having manupulated Datatable as a DataSource to it. While solving this, I developed a good piece of code which I do feel will help most of you in your development activity.

HTML Markup :
  1. Set AllowPaging="True" and AllowSorting="True" Properties of GridView to enable paging and sorting respectively.
  2. Set PageSize property to mention how many records will be display on each page.
  3. Set SortExpression property of each column.
<asp:GridView ID="gvSortingPaging" runat="server" BorderColor="#999999"  AutoGenerateColumns="False"
  BorderWidth="1px" CellPadding="4" ForeColor="#333333" GridLines="None"
 AllowSorting="true" AllowPaging="true" PageSize="5" onsorting="gvSortingPaging_Sorting"
 onpageindexchanging="gvSortingPaging_PageIndexChanging">
  <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
      <asp:TemplateField HeaderText="Id">
        <ItemTemplate>
          <asp:Label ID="Label3" runat="server" Text='<%# Eval("id") %>'></asp:Label>
         </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="First  Name" SortExpression="FullName">
         <ItemTemplate>
           <asp:Label ID="Label4" runat="server" Text='<%# Eval("FullName") %>'></asp:Label>
         </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
           <ItemTemplate>
              <asp:Label ID="Label1" Text='<%# Eval("LastName") %>' runat="server"></asp:Label>
           </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="MatchCount" SortExpression="matchCount">
           <ItemTemplate>
              <asp:Label ID="Label2" runat="server" Text='<%# Eval("matchCount") %>'></asp:Label>
            </ItemTemplate>
      </asp:TemplateField>
    </Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>


Code Behind:
protected void Page_Load(object sender, EventArgs e){
if (!Page.IsPostBack)
{
gvSortingPaging.DataSource = populateGridView();
gvSortingPaging.DataBind();
}
}

public DataTable populateGridView()
{
string myQuery = "select id,FullName,LastName,matchCount from myTable";
SqlDataAdapter dap = new SqlDataAdapter(myQuery, con);
DataSet ds = new DataSet();
dap.Fill(ds);
return ds.Tables[0];
}

protected void gvSortingPaging_Sorting(object sender, GridViewSortEventArgs e)
{
string sortingDirection = string.Empty;
if (direction == SortDirection.Ascending)
{
direction = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
direction = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(populateGridView());
sortedView.Sort = e.SortExpression + " " + sortingDirection;
Session["objects"] = sortedView;
gvSortingPaging.DataSource = sortedView;
gvSortingPaging.DataBind();

}

Now here we  we store direction in ViewState ie(Ascending or Decending).
 
public SortDirection direction

{
get
{
if (ViewState["directionState"] == null)
{
ViewState["directionState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["directionState"];
}
set
{ ViewState["directionState"] = value; }
}

protected void gvSortingPaging_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSortingPaging.PageIndex = e.NewPageIndex;
gvSortingPaging.DataSource = Session["objects"];
gvSortingPaging.DataBind();
}

Thứ Hai, 6 tháng 5, 2013

Aspect-Oriented Programming in C# with PostSharp - Logging Aspect Example

I was looking at some code in a class library project with a colleague recently. One thing that stood out was that a lot of methods across the various classes in the library were using a "Logger" class to persist runtime information (things like actual parameters and exception messages). There was a clear pattern in how these methods were structured, they logged the fact that they were called (with parameter information) and then had logic specific to what they were supposed to do. Any exceptions raised by the main logic of the methods were also logged. The "Logger" instance was not being injected into each of these classes, it was a concrete implementation without an interface. In the end, we came to the conclusion that we could improve this code as follows:

  • We could de-couple the logger from all the classes by using dependency injection. This would involve creating an interface for the logger, ensuring the current logging class implements this interface and then rearchitecting the classes that use the logger so that they are IoC friendly. An IoC container such as Ninject could then be used to inject a specific implementation of the logger into the various classes at runtime.
  • Or, we can make use of Aspect-Oriented Programming (AOP)

The latter of these points is the subject of this blog post. AOP is a programming paradigm just like Object-Oriented Programming (OOP). But instead of focusing on classes, objects and methods - AOP focuses more on separating concerns through "aspects". AOP typically deals with concerns that "cross-cut" a codebase. Luckily for us, the most popular example of a cross-cutting concern seems to be logging. As my colleague and I witnessed in the class library project, logging was being applied across a number of classes, therefore tightly coupling the logger with these classes. Furthermore, it was clear that each method that was logging wasn't adhering to the single responsibility principle.

The goal was therefore to seperate these concerns in a clean way. AOP enables this by letting you implement cross-cutting concerns as aspects which are then applied to existing code through aspect weaving. The C# programming language doesn't have any first-class support for AOP as it is primarily an OOP language. But there are libraries that allow you to apply AOP concepts using existing C# language constructs. One such library is PostSharp, which makes it easy to write an aspect and then apply the aspect to existing code. In the example below, we'll make use of PostSharp to write an aspect for logging method call information to the debug output.

PostSharp Logging Aspect Example

The PostSharp library allows you to define aspects as standard C# attributes. You can do this by deriving from one of the aspect classes from the library and override the methods that are of interest to your aspect. In the logging aspect example below, we derive from the PostSharp.Aspects.OnMethodBoundaryAspect class and override the OnEntry, OnExit and OnException methods.

[Serializable]
public class LogAspectAttribute : OnMethodBoundaryAspect
{
    private Guid _methodCallIdentifier;
                
    public override void OnEntry(MethodExecutionArgs args)
    {
        _methodCallIdentifier = Guid.NewGuid();

        Debug.WriteLine("{0} - Entering method {1} with arguments: {2}",
            _methodCallIdentifier,
            args.Method.Name,
            string.Join(", ", args.Arguments));
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        Debug.WriteLine("{0} - Exited method {1}",
            _methodCallIdentifier,
            args.Method.Name);
    }

    public override void OnException(MethodExecutionArgs args)
    {
        Debug.WriteLine("{0} - Method {1} raised exception with message: {2}",
            _methodCallIdentifier,
            args.Method.Name,
            args.Exception.Message);
    }
}

Note that PostSharp contains a number of predefined aspect classes that you can derive from depending on your particular use case. For instance, the class PostSharp.Aspects.MethodInterceptionAspect is particularly useful for implementing security on methods (i.e. you can decide in your aspect whether to allow the intercepted call to proceeed through).

Back to the example above, the OnEntry method is called just before the target method (the method that we'll annotate with this attribute) is called. The OnExit method is called once the target method completes executing and the OnException method is called if the target method raises an exception. Each of these three methods provide useful points for us to do some logging. The MethodExecutionArgs instance passed to each method also contains some useful context information for us to add to the log.

To now use this aspect, it's a simple case of annotating the methods you want to log with the [LogAspect] attribute, as shown below.

[LogAspect]
void SayHelloToWithoutException(string name)
{
    Console.WriteLine("Hello, {0}!", name);
}

[LogAspect]
void SayHelloToWithException(string name)
{
    Console.WriteLine("Hello, {0}!", name);
    throw new Exception("Oops! Something went wrong...");
}

The logging logic is now neatly encapsulated in one location. If we call the two methods above, one after the other, we'll get the debug output: