Tuesday, November 30, 2010

Method overloading in WCF

Shout it kick it on DotNetKicks.com
Problem
I found scenario where I have to implement two method with the same name i.e Function overloading. But when I implement that I got error "System.InvalidOperationException"

System.InvalidOperationException: Cannot have two operations in the same 
contractwith the same name, methods GetData and GetData in type 
WcfServiceLibrary.IService1 violate this rule.



Solution
To resolve this issue you just need to use meaning full name for the method by using NAME field available in OperationContract attribute. So you need to give name to both or one of the method to avoid this problem. As you can see in below code that I did in control IService.cs interface

        [OperationContract(Name = "GetIntegerData")]
        string GetData(int value);

        [OperationContract(Name = "GetStringData")]
        string GetData(string value);


So after doing the change I get live service but the name of the method get change by the name specified in the  Name attribute which you can see in below image


So to consume service in my client application you need to use the method name you specified in the Name attribute. The code in my client application is

            ServiceReference1.Service1Client client = new Client.ServiceReference1.Service1Client();
            Console.WriteLine(client.GetIntegerData(5));
            Console.WriteLine(client.GetStringData("pranay"));

Summary
You can easily resolve issue of method over loading in WCF service with the help of Name field in OperationContract attribute.

Monday, November 29, 2010

Visual Representation of SQL JOINS

Shout it kick it on DotNetKicks.com
In this post I am going to show the types of join available in SQL by the van diagram representation


Basic types of join
  • INNER JOIN
  • OUTER JOIN
    1. LEFT OUTER JOIN
    2. RIGHT OUTER JOIN
    3. FULL OUTER JOIN
  • CROSS JOIN
Following table we are going to use in this discussion
TableA Structure
TableA Data

TableB Structure
TableB Data



INNER JOIN
A Join return tose data which are match condition applied in ON clause of the query so it display data which is common in bot TableA and TableB as you see in below image  
SELECT select_column_list FROM
TableA INNER JOIN TableB
ON TableA.ID = TableB.TableA_Id
Example:



LEFT OUTER JOIN
A Join return all rows which match condition of ON clause as well as all row form left table i.e TableA. Un-match row of right table i.e TableB replace by the NULL value which you can see in below image of output window

SELECT select_column_list FROM
TableA LEFT OUTER JOIN TableB
ON TableA.ID = TableB.TableA_Id
Example :



RIGHT OUTER JOIN
A Join return all rows which match condition of ON clause as well as all row form right table i.e TableB. Un-match row of left table i.e TableA replace by the NULL value which you can see in below image of output window

SELECT select_column_list FROM
TableA RIGHT OUTER JOIN TableB
ON TableA.ID = TableB.TableA_Id
Example:



FULL OUTER JOIN
A Join return all rows which match condition of ON clause as well as all row form both table. Un-match row of left table i.e TableA replace by the NULL value and Un-match row of right table i.e TableB replace by the
Null value, which you can see in below image of output window

SELECT select_column_list FROM
TableA FULL OUTER JOIN TableB
ON TableA.ID = TableB.TableA_Id
Example:



CROSS JOIN
A join wose result set includes one row for eac possible pairin of rows form te two tables.
SELECT select_column_list FROM
TableA CROSS JOIN TableB

Handle Printing Data with HTML

Shout it kick it on DotNetKicks.com
Problem :
In my project I need to implement functionality where I have to print Order print receipt. But the real thing is I have to hide some part of page when I print page i.e hide  and I have to use same page for this.


Solution:
The easy solution for this problem is you need to give one more style sheet for the print purpose by which you can hide those element which are not required. For this you require to use attribute
media = print
of the STYLE element. Following is small code for this issue 




or when you linking style sheet






Summary
So by using media type as print you can print only those element that you want. Even you can print element with the different style.

Thursday, November 25, 2010

Handling long text using TEXT-OVERFLOW : ECLLIPSIS

Shout it kick it on DotNetKicks.com
Problem :
1. I got requirement from the client that if the text is longer than text get truncated and display "..." at the end of the string.
2. But the twist is I have to display "..." in ASP.NET GridView control for each cell.

Example :
I am working on my blog post formatting this day.

I have to display this as
I am working on my blog post formatting this day.

Solution:

Make use of avaialbe CSS property
text-overflow: ellipsis;
which truncate text form the point where text is wraping and display "..." as we require to resolve our issue.

Solution for the fist problem :
So out css class for DIV element to get "..." will be like :
div
{
   border-bottom: 1px solid; 
   border-left: 1px solid; 
   border-right: 1px solid; 
   border-top: 1px solid;        
   overflow: hidden; 
   text-overflow: ellipsis; 
   width: 150px;
   white-space:nowrap;
}

Output:
I am working on my blog post formatting this day.

This property is that its works for div, p type element. i.e for the block element. So it resolves my first problem.

Solution for the problem 2
But the CSS text-overflow not working for the html table element directly. And GridView control get converted in table structure when its render on client browser.

So to resolve this issue we have to use another CSS property call
table-layout : fixed;
more about table-layout : http://www.w3schools.com/Css/pr_tab_table-layout.asp

table
{
table-layout: fixed; 
width: 200px;
}

table td
{
overflow: hidden; 
text-overflow: ellipsis;
white-space:nowrap;
}

Output:

My WebSite :

http://pranayamr.blogspot.com/

My WebSite2 :

http://ww.stackoverflow.com/


Support
text-overflow : ecllipsis is supported by IE6+, Google Chrome 

Summary
So text-overflow:eclipse reduce the cost of calculating no. char we can display in a given width and write some custom login to display "..." append with the string.

Wednesday, November 24, 2010

Create, Host(Self Hosting, IIS hosting) and Consume WCF servcie

Shout it kick it on DotNetKicks.com
Download SourceCode


What is WCF ?

Windows Communication foundation API allows to build distributed architecture in such manner that once created service code can be utilize by the in-house application which using tcp/ip to communicate, web application using http protocol to communicate to web services, application using msmq. WCF Services also works with the application developed other than .net framework.

Create WCF Service

Follow the below listed step to create Service

Step 1:
Create service from the Visual Studio select the go to c# or vb than select project type WCF Service library or WCf service website project template.


the first one create the *.dll and app.config file for after the compilation which you can than use in your host application and expose the service to clients.


the second one create the project with the proper web.config file and *.svc file which is get hosted on IIS via virtual directly and service get explose to client via HTTP protocol. so by that service can not be expose to tcp client. The benefit of this option is no need to create host application you can directly host it on iis via virtual directory.

For this discussion first I am creating WCF service library and than I am going to discuss about iis deployment also.

Step 2:
Create contract by specifing proper attributes. This contract tells the client what are the method get expose by the service and custom type expose by the service. You can decorate your contract by the list of attribute in System.ServiceModel namespace.

you can create you own files or after selecting proper project type its create two files for you Iservcie.cs and Service.cs. If you are going to create your own files its recommanded that you can create you interface and implement it in your class.

[ServiceContract] - defines the interface participate in provided service.


[OperationContract] - defines the method going to be expose by the service.


[DataMember] - defines the property expose via service.



[DataContract] - defines the custom data type expose via service.


After you done with the creation of the web service you code should look as below


Library app.config file
This file contains infomation about the metadata exchange defines endpoint of metadata. its also contains information about the endpoints where client talk with service.

Endpoints are ABC means Address, Binding and Contract. as you see in above config file service expose for tcp communication by following line



Binding details : http://www.c-sharpcorner.com/UploadFile/pjthesedays/bindwcf05032009012251AM/bindwcf.aspx


IService.Cs file



Service.cs


Hosting WCF Service
  • Self Host
  • IIS hosting
  • Windows service
  • WAS
Demo of Self hosting and IIS hosting.

Self hosting
 Step 1:
  Create new project >> Class Library >> name this project as Host

  Step 2:
  Add referance to the host application
  Right click on Referance >> Add Referance

Step 3:
After adding referance to the host application to expose webservice for client to consume
as you see below line of the code create the object of the host and which is of type Service1 Which we created in the WCF Service library project


as you can see we used using block over so that it depose host object when we close application.

Step 4:

to start the service to hadle request coming form the client of ther service  you need to call open method
        

and to stop receiving request you need to call close method
      


Host.cs



IIS hosting
  1. To host same WCF library in your application create WCF Web application project using WCF web application template as we discuss in start.
  2. Delete the files created in the IService.cs and Service.cs file from App_Code folder
  3. Include WCF library *.dll file which we created. 
  4. Open Service.svc file and modify the single line in it 


  5. Change the web service WEB.Config file to to expose service to client. i.e you need to create Same element as listed above in in the app.config file of service library.   
Consuming WCF Service


 Step 1:
 Create new project >> Class Library >> name this project as Client as we created Host application
     If you want to consume webservice hosted in you web application start directly for the 2 step listed below.

 Step 2:
 Add Service Referance to the client by Right click on project >> Add Service Referance



















which atomatically create the proxy files to consume web service.
or
Make use of ServiceModel Metadata Utility Tool (Svcutil.exe)  the is command-line tool to generate proxy code from metadata.
   svcutil /t:code http://<service_url> /out:<file_name>.cs /config:<file_name>.config

 Step 3:
  To send request to service form the client

So as you see in above code you need to create object of Service1Client and than you can easily call the method expose by the Service. If you want to see the auto-generated code press F12 on the Service1Client it show the proxy code to you.

Summary :


As you follow the process listed process step by step its quite easy to create, consume and host WCF Service.

Friday, November 19, 2010

Sql Server CASE/WHEN return type

Shout it kick it on DotNetKicks.com
This post is related to how the Case/When statement return value after the executing condition available.

Problem
Recently I am working on the query where I have to sort data based on the user input but each column in table has different datatype. So to meet with this type of requirement I use case when.. block of the sql server. something as below..

there is not syntax error when you check for the syntax error but when execute code you find there is error

ERROR:Conversion failed when converting datetime from character string.

the problem here is first two having databype Varchar and last one having datatype DateTime. So when you executing its found that one branch having datetime so its gives error even its not executing that.


Solution

Solution 1. 

So to avoid this problem you require to convert dateTime to the string



Solution 2.

Divide the Case when in multiple statement

Wednesday, November 17, 2010

Lambda Expressions

Shout it kick it on DotNetKicks.com
What is Lambda expression ?
  • Lambda expression is replacement of the anonymous method avilable in C#2.0 Lamda expression can do all thing which can be done by anonymous method.
  • Lambda expression are sort and function consist of single line or block of statement.
Lambda expression syntax

=> is lambda expression operator which indicate that the code is lambda expression.
( param ) => expr(int x) = > { return x + 1 };
or
param => exprx=> x + 1;>
Note :
Here param is option you can also write as below
()=> Console.WriteLine()

Use of Lambda expression
Consider programmer where I have to find list of all even number from the list of interger.
List<int> 
lstNumber = new List<int>();
lstNumber.Add(20)
lstNumber.Add(1);
lstNumber.Add(5);
lstNumber.Add(26);

   C#2.0 by using anonymous method
List<int> even = 
    lstNumber.FindAll( delegate(int i) { if(i%2==) return i; }
   But for the C#3.0 with the lambda expression it will
List<int> even 
    = lstNumber.FindAll( i => (i%2) ==0 }  

As we can see the lambda expression are replacement of the anonymous method. But it more use full when you are playing with the objects collection and using linq in your application.

Consider a case where you have set of CustomerOrder(s) and you have to find out the orders which are having process status completed.

  Linq quey:
var order 
  = for o in orders where o.ProcessStatus
       = ProcessStatus.Completed select o;

  But with Lambda expression combine with the extension method where  
var order 
  = orders.where( o=> o.ProcessStatus  = ProcessStatus.Completed); 

Summary

Lambda expression one of the cool feature of the C#3.0 which replaces the anonymous method of C#2.0 and also more important to support LINQ.


Monday, November 15, 2010

ExecuteReader with CommanBehavior ( automatically close connection after reading data)

Shout it kick it on DotNetKicks.com
Here in this post I am going to explain about the CommandBehavior which plays important role when your are getting data with the DataReader object from database.

Datareader object has method ExecuteReader, which has overload version that takes CommandBehavior enumeration as parameter.


- CommandBehavior.CloseConnection
   When you pass above values as argument to ExecuteReader
     1. there is no need to close connection explicitly connection get close when you close your reader.

     //No need to close connection you just have to write
     reader.Close();

     2. It usefull when you pass reader to another method for processing data.

- CommandBehavior.SinglerRow
   passing this as parameter , increase performance when you are executing query and retriving single row for exmaple by id field of table.

- CommandBehavior.SequentialAccess
   usefull when reading binary field data, which reduces the memory overhead for large binary fields.

COALESCE - Dynamic where clause

Shout it kick it on DotNetKicks.com
Syntax

COALESCE ( expression [ ,...n ] )
Arguments expression
Is an expression of any type.
n

To search data when there is no of parameter is not fix. i.e Dynamic search fields. Returns the first nonnull expression among its arguments. Consider case when you want to put search on each field of your table

Example:
Table structure

Suppose you have requirement to search data from the table with each field and you don’t have to consider field in search when the value is blank or null.

So to achieve this task first thing you do is take variable for each field and check the value of the variable weather its blank or null and then build where condition for the query something as below.


But thing is to simple with the COALESCE
Advantages 
  • Eliminate to check the value for each variable your defined 
  • There is no need of exec procedure to execute value 
  • Execution plan get stored by sql server because it's not a dynamic query. 

Summary 
So this kind of function more help full when your are building dynamic search functionality or building reports with dynamic search fields of table.

Saturday, November 13, 2010

jQuery Plugin- How and when to use it

Shout it kick it on DotNetKicks.com
What is jQuery plugin ?

jQuery plugin is like extension to the jquery existing function. If you are c# developer plugin likes the extension function to add more functionality existing types or to dlls. Extending jQuery with plugins and methods is very powerful and can save you and your peers a lot of development time by abstracting your most clever functions into plugins.

Steps to make jquery plug

You can start writing your jQuery plugin as you can see below.

Step 1:

Always wrap your plugin in
(
     function( $ )
     { 
          // plugin goes here 
     }
) ( jQuery );
By passing jQuery to a function that defines the parameter as $, $ is guaranteed to reference jQuery within the body of the function.

Step 2:

Create function assign name to function as below
(
     function( $ )
     {
          $.fn.pluginName = function ()
          {
               // there's no need to do $(this) because
               // "this" is already a jquery object
          }; 
     }
) ( jQuery );

Use of jquery plugin

After the end of my last article related to validating fields based on datatype which is more relay on Javascript/jQuery function. I found to much lengthy and repeated code for textbox and for the textarea validation. Something as below

Example:
$("input[isRequired=true]").each(
     function(n)
     {
          $('#' +this.id).addClass('mandatory');

          if(this.value==='')
          {
               $('#' +this.id).removeClass('normal');
               $('#' +this.id).addClass('mandatory');
          }
          else
          {
               $('#' +this.id).removeClass('mandatory');
               $('#' +this.id).addClass('normal');
          }
     }
);

$("textarea[isRequired=true]").each(
     function(n)
     {
          $('#' +this.id).addClass('mandatory');
          if(this.value==='')
          {
               $('#' +this.id).removeClass('normal');
               $('#' +this.id).addClass('mandatory');
          }
          else
          {
               $('#' +this.id).removeClass('mandatory');
               $('#' +this.id).addClass('normal');
          }
}
);
But after use of the jquery this code gets reduce as shown below

$("input[isRequired=true]").ApplyCSSClass();
$("textarea[isRequired=true]").ApplyCSSClass();

(function ($) {

     $.fn.ApplyCSSClass = function () {
               this.each(
                    function () {

                         $('#' + this.id).addClass('mandatory');
                         if (this.value === '') {
                              $('#' + this.id).removeClass('normal');
                              $('#' + this.id).addClass('mandatory');
                         }
                         else {
                              $('#' + this.id).removeClass('mandatory');
                              $('#' + this.id).addClass('normal');
                         }
     });
    };
}
)(jQuery);

So as you can see in above code bunch of line code et related by jQuery plugin which can be applied to the input and textarea field and can be used for other type of fields.

Summary

jQuery plugins allows you to make the most out of the library and abstract your most clever and useful functions out into reusable code that can save you time and make your development even more efficient.

Thursday, November 11, 2010

Extension Methods

Shout it kick it on DotNetKicks.com
What is Extesion Methods ?

Method allow programmer to "add" methods to existing types without creating a new derived type, recompiling, or by modifying the original type. Methods are static methods they are called as if they were instance methods on the extended type.

Example : 

public static class Utilities
{
    public static string encryptString(this string str)
    {
           System.Security.Cryptography.MD5CryptoServiceProvider x = new      System.Security.Cryptography.MD5CryptoServiceProvider();
           byte[] data = System.Text.Encoding.ASCII.GetBytes(str);
           data = x.ComputeHash(data);

           return System.Text.Encoding.ASCII.GetString(data);
     }
}



How to call Extension Method ?
As you can see in below image IDE intelligence shows the extension method with the down arrow when you want to call on the given datatype. 



As you can see in above example I have created a function encryptString to encrypt the string which is having sensitive data and want to store its in encrypted form in database.

So the common use of extenstion method is when you are creating utility functions in your project which can extend functionality of the existing .net type or of the existing dll available in your project.