Tuesday, December 7, 2010

Gridview check all and post form data with jquery

I am going to show an example of doing some cool stuff using jquery and VS2010.

Thursday, December 2, 2010

Client Side Sortable Gridview with JQuery

It is fantastic to be able to sort the asp.net gridview on client side using jquery. I am going to make an example.

Friday, November 19, 2010

Simulate disable or readonly textbox with no focus

if we make the textbox disabled="true" then its value does not post back to the server and if we make it readonly="true" then it depends on browser to post back the value or not but any value change we make on client side, will be lost on the server side.

Wednesday, November 10, 2010

WCF Data Services with Custom Data Source and Reflection Data Service Provider

I am going to show an example how to expose custom data source using wcf data services and OData. This is just a simple test.

Tuesday, November 2, 2010

HMAC MD5 in Flex and .Net

Regarding to my previous post, HMAC is a message authentication code (MAC) and can be used to verify the integrity and authentication of a message. I was trying to consume WCF Rest services from Flex.

Saturday, October 16, 2010

Sending multiple values in XML to database from application and parse using XQuery in SQL Server 2005

SQL Server 2005 has XML support, it means we can process XML on database side. There are some scenarios that we want to insert, update or delete multiple rows or send some different values to the database, one way is using delimited values and then on database side, we have to parse that string to retrieve the values, another way is using XML to send data to database, then in the stored procedure we can use XQuery and easily parse that XML.(the names are all case sensitive)

Friday, October 15, 2010

Digital Signature in REST Services to maintain the integrity of sensitive data in URI

When we think about REST web service, we all have heard this recommendation that we had better keep the application state on the client side, if the data regarding to the application state is not that large, then we can put that data in the URI, if you decide to do that to manage the state, then you need to have some kind of checking to make sure that state data has not been tampered. one option is using digital signature.

Thursday, September 23, 2010

How to parse large XML files efficiently using LINQ

Sometimes we want to parse a very large xml file and populate our custom objects and we need to do it efficiently, because the file is so large, we dont want to load the whole file in memory, using XmlReader looks good but needs a lot of coding and we have to take care of every details when parsing.

Tuesday, September 21, 2010

How to measure the time the method takes to run in C#

.Net framework provides StopWatch class in (System.Diagnostics.StopWatch). we can use this class to measure the time for a method takes to finish executing.

Friday, September 17, 2010

How to pass DateTime object from .Net to Flex using json

I have a wcf rest service in .net that needs to serialize an object to json that has a DateTime property and send it back to my flex application.

Friday, September 10, 2010

How to get the generated sql query sending to server by entity framework

This is a sample linq query in EF,
for example, we have 2 tables:
Contents, Tags (one to many, each content has zero or more tags)

Saturday, September 4, 2010

Consuming .Net WCF Rest in different ways

There are different ways to consume wcf rest services in .net, The basic idea is first creating the http request and include the message body and message header. we need to serialize the objects we are going to send, then we need to send the request and then get the response and deserialize to get the response objects.

Saturday, August 28, 2010

Wrapped BodyStyle in WCF Rest

I m going to explain the difference between BodyStyle = WebMessageBodyStyle.Bare and BodyStyle = WebMessageBodyStyle.Wrapped in WCF Rest Services.
Bare can only support one parameter that is not included in the TemplateUri but Wrapped can support multiple parameters and have some extra XML tags in the body.
I m going to show you an example:

Saturday, August 21, 2010

How to load assembly and its references ignoring version number using Reflection

I want to load an assembly A.BC.dll that has a reference to A.XZ.dll and I dont care about the version number for A.BNM.dll, these two assemblies are located in a /ref folder.

Saturday, July 31, 2010

Translate<T> method in ObjectContext in Entity Framework 4

In Entity Framework 4, ObjectContext has a nice Translate<T> method. This method will materialize the result type. It takes your DbDataReader and materializes the data back into entities, the T can be a primitive type, an entity type, or any custom type you like, That type does not have to be defined in the Entity Framework conceptual model.

LINQ Join in Entity Framework 4

I want to explain a simple linq join in entity framework 4.

Thursday, July 29, 2010

How to install the latest Flex SDK into Flex builder 3

Installing the latest flex SDK into flex builder 3 is pretty simple. after you download the new version of SDK from Adobe website, then unzip that zip file and copy the content to a new folder created on a location
like C:\Program Files\Adobe\Flex Builder 3\sdks or any location you like, But I prefer that location.
From the main menu, select Window > Preferences > Flex > Installed SDKs and click Add to add a your new sdk and you can select the default SDK you want Flex builder to use to compile your program.

Wednesday, July 28, 2010

How to get only date part in T-sql DateTime




Thursday, June 3, 2010

What is System.Lazy<T>

there is a new class in .Net framework 4.0 Called Lazy<T> that provides lazy initialization. Lazy initialization occurs the first time the Lazy<T>.Value property is accessed or the Lazy<T>.ToString method is called and the return value will be cached, it means the second time you access its value, the expression or function does not get executed.

Friday, April 23, 2010

URL with port number in Firefox

Firefox will block url containing port number for security reasons.
we can configure firefox to access url with port numbers.
we can override the blocked ports as follow:
first type "about:config" into the address bar and press Enter.
then right click anywhere on the page and choose choose New -> String.
then type "network.security.ports.banned.override" in the textbox and click OK.
and in the value textbox we can enter port numbers seperated by comma., like 86,87,88
and then click OK.

How to decouple your application from IoC container implementation

As we all know, DI(Dependency Injection) is a form of IoC(Inversion of Control). when I use IoC Containers like Unity or Autofac to implement dependency injection, my application will be dependent on that framework, so if i decide to go for another IoC Container, I need to change a lot of things.what I want to achieve is how to make this change easier and how to decouple my application from any specific container. what i did is creating an interface to work with.

I need to add a reference to Microsoft.Practices.ServiceLocation.dll
and I make use of IServiseLocator interface in that assembly.
using Microsoft.Practices.ServiceLocation;

public abstract class IocContainer
   public static IServiceLocator Locator;

   protected IocContainer()
      Locator = CreateServiceLocator();

  protected abstract IServiceLocator CreateServiceLocator();

public class IocContainerInitialization
  private static IocContainer _iocContainer;

  public static void Initialize(IocContainer iocContainer)
    _iocContainer = iocContainer;

  public static IocContainer IocContainer
    get { return _iocContainer; }

//then for every IoC Container I want to use, I need to create a container //inheriting from that base IoCContainer class.

//for example, for using Autofac

using Autofac.Integration.Web;
using Autofac.Integration.Web.Mvc;
using AutofacContrib.CommonServiceLocator;
using Microsoft.Practices.ServiceLocation;

public class AutofacIocContainer : IocContainer
  protected override IServiceLocator CreateServiceLocator()
    var containerBuilder = new ContainerBuilder();

    //For MVC-------------

    ContainerProvider containerProvider = new ContainerProvider(containerBuilder.Build());

    //For MVC-------------------------------
    System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new  AutofacControllerFactory(containerProvider));

    return new AutofacServiceLocator(containerProvider.ApplicationContainer);

  private static void RegisterTypes(ContainerBuilder container)
    //Cache per request
    container.Register(c => new DbHelper("MyConnectionString")).As().InstancePerLifetimeScope();

    container.Register(c => new DbMapper(c.Resolve())).As();
    container.Register(c => new TagRepository()).As();
    container.Register(c => new UserRepository()).As();

//Then, in your Global.asax file we need to initialize our Container.

void Application_Start(object sender, EventArgs e)
  IocContainerInitialization.Initialize(new AutofacIocContainer());

Now, if you want to switch to another IoC Container, you only need to change one line and initialize another container.


Thursday, April 22, 2010

ASP.NET ReportViewer problems on IIS 7

today we were trying to move our asp.net application to IIS 7, and there were some pages using ReportViewer in local mode. we had some problems to make it working.
The first thing to consider is that IIS7 need a new web.config structure. you have to register your httpModules and httpHandlers under system.webServer element instead of system.web

1- register the handler in the web.config file under system.webServer element

<add name="ReportViewerWebControl" path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

2- make sure on the aspx page using ReportViewer control you have registered the correct version. it must be like this:

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>


Friday, April 16, 2010

URL Routing in ASP.NET 3.5 Webform

URL Routing decouples the URL from a physical file on the disk, we can define routing rules to specify what URL maps to what physical files. ASP.NET Routing is not only for MVC and is independent library so ASP.NET Routing can be used in a traditional ASP.NET web forms.

First, add a reference to System.Web.Routing and make sure that web.config has UrlRoutingModule HTTP Module registered in httpModules section.

then, we create this class,

public class CustomRouteHandler : IRouteHandler
public CustomRouteHandler(string virtualPath)
this.VirtualPath = virtualPath;

public string VirtualPath { get; private set; }

public IHttpHandler GetHttpHandler(RequestContext requestContext)
foreach (var paramUrl in requestContext.RouteData.Values)
requestContext.HttpContext.Items[paramUrl.Key] = paramUrl.Value;
var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
Then in Global.asax file and in Application_Start event, I will define my routing rules.

void Application_Start(object sender, EventArgs e)

private void RegisterRoutes(System.Web.Routing.RouteCollection routes)


routes.Add("IndexPage", new Route("index/{page-num}", new CustomRouteHandler("~/Home/index.aspx")));
routes.Add("Index", new Route("index", new CustomRouteHandler("~/Home/index.aspx")));
routes.Add("ContactUs", new Route("contactus", new CustomRouteHandler("~/Home/contactus.aspx")));


The Route Data will be stored in HttpContext.Item (cache per request)
You can get the Route Data from HttpContext.Current.Items["name"] on the page.


Wednesday, April 14, 2010

Some Useful Design Principles

I am a big fan of design patterns and like these principles much, they can really help us decide better when facing design issues, even they can help in normal life when you don't program.

DRY : (Don't Repeat Yourself)
SOC : (Separation of Concerns)
KISS: (Keep it Simple and Stupid)
YAGNI : (You ain't gonna need it)
CQS : (Command-Query Separation)

SOLID Principles:
SRP:(single responsibility principle)
OCP:(Open Close Principle)
LSP: (Liskov substitution principle - Design By Contract)
ISP:(Interface-segregation principle)
DIP:(Dependency inversion principle)

Inheritance --> A is a kind of B
Composition --> A is a part of B
Aggregation --> A has a B


Friday, April 9, 2010

How to Format Decimal numbers in C# and remove extra zero digits

Sometimes you want to show the decimal numbers and you do not want to show the extra zero digits after decimal point.
for below code, if there are one or two digits to the right of the decimal point, that shows up, but, if there are digits of zero to the right of the decimal point, the number is formatted as a whole number

decimal d = 2.340M;
string result = string.Format("{0:0.##}",d); // result will be 2.34


How to Detect Refresh in ASP.Net web forms

I use this code to detect refresh in asp.net web forms. This methods uses Session.

I create a static class
public static class RefreshDetectionTools
#region Constants
private const string KEY_REF_DEC_HID = "RefDecHid";
private const string KEY_REF_DEC_STAMP = "RefDecStamp";

#region Methods
public static bool IsPageRefresh()
Page page = HttpContext.Current.CurrentHandler as Page;

string val = HttpContext.Current.Request[KEY_REF_DEC_HID];

if ((val == null) || (val.Length == 0)) return false;

string stamp = HttpContext.Current.Session[KEY_REF_DEC_STAMP] as string;
if (stamp == null)
HttpContext.Current.Response.Write("Session Expired.");
if (stamp != val)
return true;
return false;
/// You need to call this method in Page_PreRender to make the
/// refresh detection working

public static void StampRefreshDetection()
Page page = HttpContext.Current.CurrentHandler as Page;

string stamp = HttpContext.Current.Server.UrlEncode(DateTime.Now.ToString());

HttpContext.Current.Session[KEY_REF_DEC_STAMP] = stamp;

page.ClientScript.RegisterHiddenField(KEY_REF_DEC_HID, stamp);

Then in any asp.net web form that needs to detect refresh, in Page_PreRender handler we need to call RefreshDetectionTools.StampRefreshDetection() and then any where you want to detect the refresh, we check StampRefreshDetection.IsPageRefresh()

Hope you enjoy, Cheers

Using ASP.Net User Controls to Create Code Generator

I m a big fan of code generators. It can help us minimize the errors and reduces the development time. Although we can use T4(text template transformation toolkit) in .Net to create code generators, But I sometimes feel like to create my own tools because I enjoy the full control over my home made tool, and I know what is going on in my code. Do not get me wrong, I don't want to reinvent the wheel, it is just for learning purpose.
I want to use the power of User Controls in ASP.Net.
What I want to achieve is generating Entity class for every table in our database.

First, I create a asp.net user control for my entity class template called EntityTemplate.ascx

and Create the required properties in the code behind:
public string MyClassName {get; set;}
public DataColumnCollection MyColumns {get; set;}
public string MyNamespace { get; set;}

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EntityTemplate.ascx.cs" Inherits="Templates_EntityTemplate" %>
using System;
using System.Collections.Generic;
using Common.Core;

namespace <%=MyNamespace %>.BOL.Entities
public class <%= MyClassName %>
#region Members
<% for (int i = 0; i < MyColumns.Count; i++)
{ %>
public <%= MyColumns[i].DataType.Name%> <%= MyColumns[i].ColumnName%> {get;set;}

<%} %>
#endregion Members

Second, we create a asp.net web from to grab the list of all tables from our Database and for every table we grab the table schema to get the list of columns for that table. then for each table, we dynamically load that template user control and we set the properties, then we Use RenderControl method to get the output of that rendering user control and save it on the hard disk.

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlCilent");
DbConnection cn= factory.CreateConnection();

cn.ConnectionString = "Your Connection String";
DbDataAdapter da = factory.CreateDataAdapter();
DbCommand cmd = factory.CreateCommand();
cmd.Connection = cn;
da.SelectCommand = cmd;
cmd.CommandText = "SELECT name FROM sysobjects where type = 'U'";
cmd.CommandType = CommandType.Text;
DataTable dtTables = new DataTable();

System.Text.StringBuilder output = new System.Text.StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(output);
HtmlTextWriter htw = new HtmlTextWriter(sw);

for(int i = 0; i< dtTables.Rows.Count; i++)
cmd.CommandText = "SELECT * FROM " + dtTables.Rows[i]["name"];
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
Control ctrl = Page.LoadControl("Templates/EntityTemplate.ascx");
EntityTemplate EnCtrl = (EntityTemplate) ctrl;
EnCtrl.MyTableName = dtTables.Rows[i]["name"];
EnCtrl.MyClassName = dtTables.Rows[i]["name"];
EnCtrl.MyNamespace = "";
EnCtrl.MyColumns = dt.Columns;

System.IO.File.WriteAllText("BOL\\Entities\\" + dtTables.Rows[i]["name"] + ".cs", output.ToString());
output.Remove(0, output.Length);

hope you enjoy, Cheers!

Hi Mate

This is my first post, I m a passionate .Net web developer currently living in Australia and i will blog about everything that catches my eyes and is interesting to me.
cheers mate!!!

گر تو سبزی، سبزم.. گر تو شادی ،شادم..من از شیرینی تو فرهادم وطنم..ایرانم..عید آن روزمبارک بادم که تو آبادی و من آزادم