JQGrid methods

I am listing here some useful methods of JqGrid (Jquery data grid plugin). you can read more about JqGrid here. You can also see demo of this grid here.

Html tag to declare JqGrid on web page

<table id="<nameofgrid>"></table> <div id="pager1"></div>

Grid Hide & Show

$(‘#<nameofgrid>’).hide();

$(‘#<nameofgrid>’).show();

Clear JQGrid Data

$(‘#<nameofgrid>’).clearGridData(false);

Fade In & Fade Out

$(‘#<nameofgrid>’).fadeIn("fast");

Align Column Header Text

$(‘#<nameofgrid>’).jqGrid(‘setLabel’, <Column Name>, ”, { ‘text-align’: ‘right’ });

Throwing Exceptions from WCF Service (FaultException)

Handling exceptions in WCF service is different than usual exceptions handling in .Net. If service raise exception it should propagate to clients and properly handle by client application. Since Exception object is .Net specific so it cannot propagate to clients because clients can be of different technologies, so to propagate to all kinds of clients it should be converted to generic exceptions which can be understand by clients.SoapFault is technology independent and industry accepted based exception which can be any clients. SoapFault Carries error and status information within a SOAP message.

.Net has FaultException<T> generic class which can raise SoapFault exception. Service should throw FaultException<T> instead of usual CLR Exception object. T can be any type which can be serialized.

Now I’ll cover one example to show how service can throw fault exception and same can catch on client.

First I create Service Contract IMarketDataProvider which is having operation contract GetMarketPrice which provide market data of instrument.

IMarketDataProviderService

[ServiceContract]
    public interface IMarketDataProvider
    {

        [FaultContract(typeof(ValidationException))]
        [OperationContract]
        double GetMarketPrice(string symbol);
       
    }

Here is implementation of IMarketDataProviderService interface

public class MarketDataProviderService : IMarketDataProvider
    {
        
       public double GetMarketPrice(string symbol)
        {
            //TODO: Fetch market price
            //sending hardcode value
            if (!symbol.EndsWith(".OMX"))
                throw new FaultException(
		new ValidationException { ValidationError = "Symbol is not valid" }, 
		new FaultReason("Validation Failed"));

            return 34.4d;
        }
    }

Operation contract which might raise exception should have FaultContract attribute

[FaultContract(typeof(ValidationException))]

ValidationException is class which will be encapsulated in FaultException object

To raise exception you need to throw FaultException object in which you need to provide ValidationException in constructor and you can also supply FaultReason.

throw new FaultException(new ValidationException { 
ValidationError = "Symbol is not valid" }, 
new FaultReason("Validation Failed"));

NOTE: ValidationException class should have DataContract to serialize and send to client.

 

[DataContract]
public class ValidationException
  {
       [DataMember]
       public string ValidationError { get; set; }
 }

Catch exception in client Application

You should catch exception as FaultException for service exception.

 

	    try
            {
                var client = new ServiceReference1.MarketDataProviderClient();
                double price=client.GetMarketPrice("MSFT");
                
            }
            catch (FaultException ex)
            {
                Console.WriteLine(ex.Detail.ValidationError);
            }

Output

image

Throwing Exceptions from WCF Service (FaultException)

Handling exceptions in WCF service is different than usual exceptions handling in .Net. If service raise exception it should propagate to clients and properly handle by client application. Since Exception object is .Net specific so it cannot propagate to clients because clients can be of different technologies, so to propagate to all kinds of clients it should be converted to generic exceptions which can be understand by clients.SoapFault is technology independent and industry accepted based exception which can be any clients. SoapFault Carries error and status information within a SOAP message.

.Net has FaultException<T> generic class which can raise SoapFault exception. Service should throw FaultException<T> instead of usual CLR Exception object. T can be any type which can be serialized.

Now I’ll cover one example to show how service can throw fault exception and same can catch on client.

First I create Service Contract IMarketDataProvider which is having operation contract GetMarketPrice which provide market data of instrument.

IMarketDataProviderService

[ServiceContract]
    public interface IMarketDataProvider
    {

        [FaultContract(typeof(ValidationException))]
        [OperationContract]
        double GetMarketPrice(string symbol);
       
    }

Here is implementation of IMarketDataProviderService interface

public class MarketDataProviderService : IMarketDataProvider
    {
        
       public double GetMarketPrice(string symbol)
        {
            //TODO: Fetch market price
            //sending hardcode value
            if (!symbol.EndsWith(".OMX"))
                throw new FaultException(new ValidationException { ValidationError = "Symbol is not valid" }, new FaultReason("Validation Failed"));

            return 34.4d;
        }
    }

Operation contract which might raise exception should have FaultContract attribute

[FaultContract(typeof(ValidationException))]

ValidationException is class which will be encapsulated in FaultException object

To raise exception you need to throw FaultException object in which you need to provide ValidationException in constructor and you can also supply FaultReason.

throw new FaultException(new ValidationException { ValidationError = "Symbol is not valid" }, new FaultReason("Validation Failed"));

NOTE: ValidationException class should have DataContract to serialize and send to client.

 

[DataContract]
public class ValidationException
  {
       [DataMember]
       public string ValidationError { get; set; }
 }

Catch exception in client Application

You should catch exception as FaultException for service exception.

 

	    try
            {
                var client = new ServiceReference1.MarketDataProviderClient();
                double price=client.GetMarketPrice("MSFT");
                
            }
            catch (FaultException ex)
            {
                Console.WriteLine(ex.Detail.ValidationError);
            }

Output

image

Refactoring of C# Code

What is Refactoring?

Refactoring of code helps to restructure the code to enhance performance, scalability, reusability and code readability. There could be chances that refactoring can result in breaking of application flow when you do refactoring of big chunks of code. It is better to do refactoring of small chunks of code on regular basis.

Refactoring can includes improvements like: adhere to coding guidelines, OO principles, increase type safety, improving performance, increasing code readability and maintainability. Refactoring can be done manually and automated.

Tools to Help in Refactoring

  • VSTS
  • Re Sharper
  • Code Rush

Following are some of common refactoring operations which we do for refactoring code:

  • Extract method.
  • Extract Interface.
  • Segregate code in layers (logical or physical).
  • Convert looping (foreach) in LINQ expressions.
  • Re-Ordering of Parameters.
  • Encapsulate Field.
  • Rename method, class.
  • Put independent code which is independent of any object into static method.
  • Use of Extension methods.
  • Adhere to coding guidelines (naming, design, behavioral etc).

Extract Method

It is an easy way to extract method out of code fragment. This is useful when any block has many lines of code which can leads to maintainability problem. In this case it is advised to segregate lines of code in methods which gives better clarity of code, reusability of code,

Benefits

  • Encourage best coding practices
  • Encourage reusability of methods
  • Encourage finer grained methods to simplify overriding
  • Minimize code duplicity.
  • Unit testing can be more effective.

Code

Following is code which calculate area of rectangle:

public void Method1()
        {

            double length = 3.4d;

            double width = 4.5d;

            double a = length * width;

            Console.WriteLine("Area :{0}", a);

        }

public void Method2()
        {

            double length = 6.7d;

            double width = 42.3d;

            double a = length * width;

            Console.WriteLine("Area :{0}", a);

        }

In above code, same code has used (calculation of area) in Method2. This situation demands in refactoring of code by extracting method which will reduce duplicity of code. You can do refactored above code like below:

public void Method1()
        {

            double length = 3.4d;

            double width = 4.5d;

            CalculateAreaAndPrint(length, width);

        }

        private static void CalculateAreaAndPrint(double length, double width)
        {
            double a = length * width;

            Console.WriteLine("Area :{0}", a);
        }

        public void Method2()
        {

            double length = 6.7d;

            double width = 42.3d;

            double a = length * width;

            CalculateAreaAndPrint(length, width);
        }

You can refactored above code manually but VSTS also has commands which can easily extract method effectively.

  • Select code you want to refactor, right click and select refactor menu and then Extract Method.
  • Dialog will open to ask to for method name.

image

image

It will refactor code by extracting method.

Extract Interface

VSTS provides operation to extract interface from concrete class.

public class CandidateForInterface
    {
        public void DoSomething(int a, int b)
        {
            //do something
        }
        public void ExtractMe(double d)
        {
            //do something
        }

    }

After refactoring

 interface ICandidateForInterface
    {
        void DoSomething(int a, int b);
        void ExtractMe(double d);
    }
public class CandidateForInterface:ICandidateForInterface
    {
	....
    }

image

ForEach Loop Refactoring

Adding item from one collection to another:

Sample Code

Before Refactoring

List coll1 = new List {28,31,43,59,89,2,43,20,56};

            List coll2 = new List();

            //conventional approach
            foreach (int i in coll1)
                coll2.Add(i * 5);

After Refactoring

           coll2 = coll1.Select(i => i * 5).ToList();

Sample Code

public class Employee
        {
            public string Name { get; set; }
        }
        public class ModifiedEmployee
        {
            public string ModifiedName { get; set; }
        }
static void Main(string[] args)
        {
 	    //Transformation of one entity to another
            List list = new List ();
            Employee obj=new Employee{Name="Neeraj"};
            list.Add(obj);
            obj = new Employee{Name ="Rajeev"};
            list.Add(obj);

            // Before Refactoring
            List ModifiedList = new List();
	}

After Refactoring

  ModifiedList.AddRange(list.Select(x=> new ModifiedEmployee{ModifiedName="Mr"+x.Name}));

Reordering of Parameters

While writing code sometimes you would need to reorder parameters of methods to make it consistent across project. VSTS provide command to reorder parameters of method and also rearranged parameters where method is calling.

	public int ReturnDays(DateTime endDate, DateTime fromDate)
            {
                return endDate.Subtract(fromDate).Days;
            }

ReturnDays method has two parameters endDate and fromDate. To increase readability of code, ordering of parameters could be fromDate and endDate. To reorder parameters :

  1. Place cursor on method “ReturnDays”.
  2. Do right click, select Refactor or On the Refactor menu.
  3. Click Reorder Parameters. A Dialog box will appear.
  4. Move fromDate to up or endDate to down.
  5. Click.

image

Preview changes

image

After Refactoring Code will like this:

public int ReturnDays(DateTime fromDate, DateTime endDate)
            {
                return endDate.Subtract(fromDate).Days;
            }

Encapsulate Field

Sometimes we need to create properties from existing field. When a field is public, other objects have direct access to that field and can modify it, undetected by the object that owns that field. By using properties to encapsulate that field, you can disallow direct access to fields.

public class Employee
    {
        public string Name { get; set; }

        public string EmployeeId;
}

Above class has field EmployeeId which is public. We need to convert it into property.

  1. Place cursor on method “ReturnDays”.
  2. Do right click, select Refactor or On the Refactor menu.
  3. Click Encapsulate Field. A Dialog box will appear.
  4. Put property name if you want to give custom name.
  5. Click OK.

image

Convert into Static Method

Extract method command extract code and put into static method if selected code is not dependent on any class. For instance we are doing mathematical operation, it will extract into static method.

 int a=5,b=5;
 int d = a + b/10;

To refactor int d = a + b/10

  1. Select source code to refactor.
  2. Do right click, select Refactor or On the Refactor menu.
  3. Click Extract method. A Dialog box will appear.
  4. Give method name if you want to give custom name.
  5. Click OK.

image

After refactoring:

private static void Calculate(int a, int b){    int d = a + b / 10;}

WCF Free Training Videos

 

Here is list of WCF free training videos. This is topic wise listing of videos:

Topics

URL

Creating Your First WCF Service

Video

Configuring WCF Services with Endpoints

Video

Hosting WCF Services in IIS

Video

Self-hosting WCF Services

Video

Creating Your First WCF Client

Video

Configuring WCF Service References

Video

WCF Web API with Glenn Block

Video

WCF Web API – Content Types

Video

WCF Web APis: "There’s a URI for That"

Video

Troubleshooting WCF Performance Part 1

Video

Troubleshooting WCF Performance Part 2

Video

ASP.NET WF4 / WCF and Async Calls

Video

WCF Web HTTP (REST) Test Tool Preview

Video

Take some REST with WCF

Video

WCF Service Data Validation Design

Video

Glenn Block on WCF HTTP

Video

WCF AppFabric Caching Behavior Sample

Video

WCF Complex Type AJAX Service Sample

Video

WCF Extensibility

Video

Duplex Communication with WCF in Silverlight 4

Video

Hosting WCF and Inter-Role Communication

Video

WCF Data Services Beyond the Basics

Video

What’s New in WCF4

Video

Improving SharePoint Development with WCF Services

Video

Intro to WCF Data Services & OData

Video

The New WCF Routing Service

Video

Something WCF This Way Comes

Video

WCF Deployment Strategies

Video

Using WCF with Silverlight 3.0

Video

What’s new in WF/WCF 4.0

Video

Service Discovery with WCF

Video

Connected Applications with WCF and WF

Video

Silverlight with WCF, WCF REST, and ADO.NET Data Services

Video

Getting started with the WCF REST Starter Kit Preview 2

Video

Exposing and consuming errors from your WCF RESTful services

Video

AJAX-Enabling your WCF Service

Video

Calling RESTful Services in WCF

Video

Building RESTful Services with WCF Part 1

Video

Building RESTful Services with WCF Part 2

Video

Windows HPC Server Development, the WCF Application Model

Video

WCF and WF 4.0 First Look

Video

Using the WCF to Consume Services in Windows Workflow Foundation (WF)

Video

Tunneling a PUT through POST with RESTful WCF Services

Video

Using the WCF Receive Activity in Windows Workflow Foundation (WF)

Video

WCF and WF 4.0 First Look with Richard Blewett

Video

WCF: Zen of Performance and Scale

Video

WCF: Developing RESTful Services

Video

WCF 4.0: Building WCF Services with WF in Microsoft .NET 4.0

Video

Getting Started with the WCF REST Starter Kit

Video

Essential WCF

Video

The Total Noobs Guide to WCF My First WCF Service

Video

Programming JSON with WCF

Video

AppFabric WCF Data Service

Video

Reference: http://dotnetrobert.com/?q=node/282