Sponsors

Thứ Sáu, 11 tháng 10, 2013

The ExpandoObject Stringified

I had a requirement to output some data as part of a number of pages in an e-commerce site. This data would change from page to page and typically get richer as a user would go through an order path in the application. The data needed to be in JSON format and was going to be used by the marketing guys to help track information about user behaviour across the order process. The data was also subject to change regularly depending on what the marketing team wanted to track. In short, I had to construct a JSON string on the server side in C#.

I had seen something like this done before where a StringBuilder was used to construct a large JSON string which was then pushed out in the response with the rest of the page markup. This approach seemed messy and difficult to maintain. I did a bit of research on some approaches to constructing a potentially complex and changing JSON object using C# and came across the ExpandoObject class. MSDN has a nice succinct explanation of ExpandoObject:
"Represents an object whose members can be dynamically added and removed at run time."
You can find this class in .NET 4 in the System.Dynamic namespace. ExpandoObject lets you effectively "model" an object on the fly with properties that don't really exist (just like using the ViewBag in ASP.NET MVC). In my case, it saved me from writing a number of classes or complex strings just to hold data that was to be output in page responses. Instead, I could use ExpandoObject and then use a JSON serializer to stringify the object.

The example below shows how easy and flexible it is to use ExpandoObject with the Newtonsoft .NET JSON library (available as a NuGet package):
dynamic orderInfo = new ExpandoObject();

orderInfo.OrderDate = DateTime.Today;

orderInfo.ProductTypesAdded = new List<dynamic>();
orderInfo.ProductTypesAdded.Add("Radio");
orderInfo.ProductTypesAdded.Add("Television");
orderInfo.ProductTypesAdded.Add("Recorder");

orderInfo.ReachedCheckout = true;
orderInfo.PaymentMethod = "Card";
            
orderInfo.DeliveryInfo = new ExpandoObject();
orderInfo.DeliveryInfo.Method = "First";
orderInfo.DeliveryInfo.Country = "UK";

var json = JsonConvert.SerializeObject(orderInfo);
The resulting JSON is:
{
    "OrderDate":"2013-10-11T00:00:00+01:00",
    "ProductTypesAdded":[
        "Radio",
        "Television",
        "Recorder"
    ],
    "ReachedCheckout":true,
    "PaymentMethod":"Card",
    "DeliveryInfo":{
        "Method":"First",
        "Country":"UK"
    }
}

Thứ Bảy, 14 tháng 9, 2013

Jquery set HTML attributes CSS classes and HTML form values and element content and data

# 2- Element Get and Set-

How to set HTML attributes: CSS styles and classes,  HTML form values, and element content and data

Some of the simplest and most common operations on jQuery objects are to get or set the value of HTML attributes, CSS styles, element content here we learn those methods.


#2.1 -  Get and Set HTML Attributies:

The attr() method is the jQuery getter/setter for HTML attributes,
$("#BannerImg").attr("src", "icon.gif");     // Set the src attribute of element with id banner
$("a").attr("target", "_blank");   // Make all links load in new windows
$("#banner").attr({src:"banner.gif",          // Set 4 attributes at once
alt:"Advertisement",
width:720,
height:64});

The  attr() is jQuery’s master attribute-setting function, and you can use it to set things other than normal HTML attributes. If you use the attr() method to set an attribute named “css”, “val”, “html”, “text”, “data”, “width”, “height”, or “offset”, jQuery invokes the method that has the same name as that attribute and passes whatever value you specified as the argument.

For example, calling attr ("css", {backgroundColor:"gray"}) is the same as calling css({backgroundColor:"gray"}) .  
We’ll learn about css(), val(), html(), and other methods in later article.


#2.2 -  Get and Set CSS Attributies:

The  css() method is very much like the attr() method, but it works only with the CSS styles of an element ie sets or returns one or more style properties for the selected elements.
Sample Code:

$("h3").css("font-weight"); // Get font weight of 1st <h3>
$("h3").css("fontWeight"); // Camel case works, too
$("h3").css("font"); // ERROR: can't query compound style

$("h3").css("font-variant","smallcaps"); // Set style on all <h1> tags 

Thứ Sáu, 6 tháng 9, 2013

Learn jQuery in 11 Days

Learn jQuery in 11 Days


Hi, my name is Satinder Singh .  Here’s the tutorial “  Learn JQuery in 11 days “If you promise to give me thirty minitues a day, for an eleven day regularly , then I promise that you’ll come out the other side as a jQuery pro .

Introduction:  JQuery is the “write less, do more” JavaScript Library.   Its powerfull features and ease of use have made it the most popular client-side JavaScript framework for the Web.

JQuery makes developer life easy,  because using JQuery is easy to find the elements of a document, and then manipulate those elements by adding content, editing HTML attributes and CSS properties,  defining event handlersm and performing animations. It also has Ajax utilities for dynamically making  HTTP requests, and general-purpose utility functions for working with objects and arrays.

  1. Jquery Basic
  2. Element Set and get
  3. Altering document structure
  4. Events
  5. Effect Animation
  6. Ajax
  7. Utility funtions
  8. Selectors and selection method

#1- Basic of JQuery-

First you have to add Jquery to your web page .i.e HTML page.

Download jQuery from jQuery.com The jQuery Library is a single JavaScript file, and you reference it with the HTML <script> tag and that script tag should be inside the <head> tag.

CODE:


<head>
<script src="jquery-1.10.2.min.js"></script>
</head>


Or alternative to  downloading  you can include it from CDN .  I use google libraries Click Here .

CODE:


<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>

The Jquery Library Defines a single global function named JQuery(). This function is so Frequently used that the library also defines the global symbol $ as a shortcut for it.
The jQuery() function (a.k.a. $()) is the most important one in the jQuery library. When you pass a jQuery selector string to $(), it returns a jQuery object that represents the set of matched (or “selected”) elements. jQuery selectors are very much like the CSS selectors you use in stylesheets.


For example:
div // all <div> elements
#content // the element with id="content"
.warning // all elements with class="warning"


Live Demo

Explanation:

First we write this piece of code, which ensure that the document is ready for manipuulation. ie it prevent any jQuery code running before the document is finished loading.


$( document ).ready(function() {
   // Your code logic here.
 });

Example 1:  Display hello world alert message on click of a div
$(document).ready(function(){
$("#btnhelloworld").click(function(){
alert("Hello world!");
});
});

Example 2 : Change background-color of a element
$(document).ready(function(){
$("#btnchangebgColor").click(function(){
$("#content").css("background-color","#BDEA74");
});
});

Complete Code:
<html>
 <title>Learn JQuery in 11 days with satinder singh</title>
<head>
<style type="text/css">
#content{
  position:absolute;width:900px;height:600px;}

#btnhelloworld{
  border-radius: 2px;  cursor:pointer;  background: none repeat scroll 0 0 #FF5454;
  color: #FFFFFF;font-size: 17.5px; padding: 5px 10px;
  width:100px; float:left; margin-right:10px; border: 1px solid red ;}


#btnchangebgColor  { border-radius: 2px;cursor:pointer; background: none repeat scroll 0 0 #78CD51;   color: #FFFFFF; font-size: 17.5px; padding: 5px 10px; width:190px;  float:left;  margin-right:10px; border: 1px solid green;}
#btnchangebgColortowhite  { 
border-radius: 2px; cursor:pointer;   background: none repeat scroll 0 0 #67C2EF;
color: #FFFFFF; font-size: 17.5px;
padding: 5px 10px; width:130px; 
float:left;  margin-right:10px;
border: 1px solid green;}
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
   $("#btnhelloworld").click(function(){
     alert("Hello world!");
  });

    $("#btnchangebgColor").click(function(){
     $("#content").css("background-color","#BDEA74");
  });

    $("#btnchangebgColortowhite").click(function(){
     $("#content").css("background-color","#fff");
});
});
</script>
</head>
<body>
  <div id="content">
    <div id="btnhelloworld"> Click for alert  </div>
     <div id="btnchangebgColor"> Change BG color to green</div>
    <div id="btnchangebgColortowhite"> Change to white </div>
     </div>
</body>
</html>

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

C# MongoDB Repository Implementation

I recently started a small project with a friend and we opted for MongoDB as our data store. One of the initial tasks was to write a repository class that allowed us to store, retrieve, update and search for entities in MongoDB. In the past, I've worked on codebases where there was one repository per entity, it didn't take long to discover that this resulted in a lot of code duplication across the data layer. So the goal here was to write the repository generically enough so that we only have one implementation that can be reused for any entity within our application. This meant that each entity would have its own MongoDB collection (if you're not familiar with MongoDB, a collection can be thought of as a table in the relational world - see this page for a comparison).

One of the first steps in this task was to write an interface for the repository - this is in case we decide to use a different data store in the future. A while back, I found a repository interface on the Redmondo blog which covers everything I'd want from a repository, so we'll use a slightly modified version of that interface (I've removed comments for brevity, you can download the code using a link further below and that'll contain the comments):
public interface IRepository<TEntity> where TEntity : EntityBase
{
    bool Insert(TEntity entity);
    bool Update(TEntity entity);
    bool Delete(TEntity entity);
    IList<TEntity> 
        SearchFor(Expression<Func<TEntity, bool>> predicate);
    IList<TEntity> GetAll();
    TEntity GetById(Guid id);
}
To paraphrase the code, this is a generic repository interface for an entity of type TEntity that must derive from a base class called EntityBase. The EntityBase class is a very simple abstract class and contains just one property, the identifier property:
/// <summary>
/// A non-instantiable base entity which defines 
/// members available across all entities.
/// </summary>
public abstract class EntityBase
{
    public Guid Id { get; set; }
}
The idea is for any entity that we want to manage in our data store, that entity must derive from EntityBase. So the infrastructure is all in place for our "MongoDbRepository". I used the official 10gen MongoDB C# driver (available as a NuGet package) and arrived at the following repository implementation:
/// <summary>
/// A MongoDB repository. Maps to a collection with the same name
/// as type TEntity.
/// </summary>
/// <typeparam name="T">Entity type for this repository</typeparam>
public class MongoDbRepository<TEntity> : 
    IRepository<TEntity> where 
        TEntity : EntityBase
{
    private MongoDatabase database;
    private MongoCollection<TEntity> collection;

    public MongoDbRepository()
    {
        GetDatabase();
        GetCollection();
    }

    public bool Insert(TEntity entity)
    {
        entity.Id = Guid.NewGuid();
        return collection.Insert(entity).Ok;
    }

    public bool Update(TEntity entity)
    {
        if (entity.Id == null)
            return Insert(entity);
        
        return collection
            .Save(entity)
                .DocumentsAffected > 0;
    }

    public bool Delete(TEntity entity)
    {
        return collection
            .Remove(Query.EQ("_id", entity.Id))
                .DocumentsAffected > 0;
    }

    public IList<TEntity> 
        SearchFor(Expression<Func<TEntity, bool>> predicate)
    {
        return collection
            .AsQueryable<TEntity>()
                .Where(predicate.Compile())
                    .ToList();
    }

    public IList<TEntity> GetAll()
    {
        return collection.FindAllAs<TEntity>().ToList();
    }

    public TEntity GetById(Guid id)
    {
        return collection.FindOneByIdAs<TEntity>(id);
    }

    #region Private Helper Methods
    private void GetDatabase()
    {
        var client = new MongoClient(GetConnectionString());
        var server = client.GetServer();

        database = server.GetDatabase(GetDatabaseName());
    }

    private string GetConnectionString()
    {
        return ConfigurationManager
            .AppSettings
                .Get("MongoDbConnectionString")
                    .Replace("{DB_NAME}", GetDatabaseName());
    }

    private string GetDatabaseName()
    {
        return ConfigurationManager
            .AppSettings
                .Get("MongoDbDatabaseName");
    }

    private void GetCollection()
    {
        collection = database
            .GetCollection<TEntity>(typeof(TEntity).Name);
    }
    #endregion
}
In case you're interested, a while ago I wrote a separate blog post on how to perform CRUD operations against MongoDB using the C# driver. To use the repository implementation, you'll need two application configuration settings defined - one that stores the name of the MongoDB database and the other that contains the MongoDB connection string (with a placeholder for the database name). You should have something like:
<appSettings>
  <add key="MongoDbDatabaseName" value="MyCarsDatabase" />
  <add key="MongoDbConnectionString" 
         value="mongodb://localhost/{DB_NAME}?safe=true" />
</appSettings>
Hopefully this repository is useful to someone else who is working with MongoDB in C#. Any questions or suggestions for improvements are always welcome via comments. You can download a console project from here which shows how to use the repository.

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

CRM Blog World Updated

One of the most viewed pages on my blog is still the Blog World. When Dynamics CRM wasn't called Dynamics CRM yet, I have started to gather a list of blogs which targeted this software. Over the years this list has grown and I have just updated the list with the blogs which I have been requested to add. I guess soon I'll need to do a full review of this list as I've noticed that some people have

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: