Sunday, 3 February 2013

Basics of WCF


Basics of WCF
Definition of WCF 
Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF we can build secure, reliable, transacted solutions that integrate across platforms.
WCF is a unified framework which provides :
1. NET Remoting 2.Distributed Transactions 3.Message Queues and 4.Web Services into a single service-oriented programming model for distributed computing.
WCF interoperate between WCF-based applications and any other processes that communicate via SOAP (Simple Object Access Protocol) messages.

Features of WCF
  1. Service Orientation
  2. Interoperability
  3. Multiple Message Patterns
  4. Service Metadata
  5. Data Contracts
  6. Security
  7. Multiple Transports and Encodings
  8. Reliable and Queued Messages
  9. Durable Messages
  10. Transactions
  11. AJAX and REST Support
  12. Extensibility
To know more about features of WCF see: http://msdn.microsoft.com/en-us/library/ms733103.aspx

Terms of WCF
A WCF service is exposed to the outside world as a collection of endpoints.
1. Endpoint: Endpoint is a construct at which messages are sent or received (or both). Endpoint comprises of ABC’s       
What are ABC’s of WCF ? 
A. Address - Address is a location that defines where messages can be sent
B. Binding - Binding is a specification of the communication mechanism (a binding) that described how messages should be sent
C. Contract - Contract is a definition for a set of messages that can be sent or received (or both) at that location (a service contract) that describes what message can be sent.
2. Service: A construct that exposes one or more endpoints, with each endpoint exposing one or more service operations.
3. Contracts: A contract is a agreement between two or more parties for common understanding and it is a is a platform-neutral and standard way of describing what the service does. In WCF, all services expose contracts.
Types of Contracts:
1) Operation Contract: An operation contract defines the parameters and return type of an operation.
1[OperationContract]
2double Add(double i, double j);
2) Service Contract: Ties together multiple related operations contracts into a single functional unit.
01[ServiceContract] //System.ServiceModel
02public interface IMath
03{
04    [OperationContract]
05    double Add(double i, double j);
06    [OperationContract]
07    double Sub(double i, double j);
08    [OperationContract]
09    Complex AddComplexNo(Complex i, Complex j);
10    [OperationContract]
11    Complex SubComplexNo(Complex i, Complex j);
12}
3) Data Contract: The descriptions in metadata of the data types that a service uses.
01// Use a data contract
02[DataContract] //using System.Runtime.Serialization
03public class Complex
04{
05    private int real;
06    private int imaginary;
07 
08    [DataMember]
09    public int Real { getset; }
10 
11    [DataMember]
12    public int Imaginary { getset; }
13}

WCF Step by Step Tutorial


This is the Basic WCF Tutorial ‘wcfMathSerLib’ will be created in a step by step approach. This ‘wcfMathSerLib’ will be tested by ‘ConsoleMathClient’ and with ‘WCF Test Client’
Steps for creating wcfMathSerLib
1. Open Visual Studio 2010 and File->NewProject
2.select WCF in ‘Recent Templates’
3.select ‘WCF Service Library’
4.Give Name as wcfMathServiceLibrary
5.Click OK
Image(1)
2. Delete IService1.cs and Service1.cs
Image(2)
3. Add IMath.cs and MathService.cs and add the code listed below
Image(3)
IMath.cs
01using System.Runtime.Serialization;
02using System.ServiceModel;
03 
04namespace WcfMathServLib
05{
06    [ServiceContract] //System.ServiceModel
07    public interface IMath
08    {
09        [OperationContract]
10        double Add(double i, double j);
11        [OperationContract]
12        double Sub(double i, double j);
13        [OperationContract]
14        Complex AddComplexNo(Complex i, Complex j);
15        [OperationContract]
16        Complex SubComplexNo(Complex i, Complex j);
17    }
18 
19    // Use a data contract
20    [DataContract] //using System.Runtime.Serialization
21    public class Complex
22    {
23        private int real;
24        private int imaginary;
25 
26        [DataMember]
27        public int Real { getset; }
28 
29        [DataMember]
30        public int Imaginary { getset; }
31    }
32}
MathService.cs
01namespace WcfMathServLib
02{
03    public class MathService : IMath
04    {
05 
06        public double Add(double i, double j)
07        {
08            return (i + j);
09        }
10 
11        public double Sub(double i, double j)
12        {
13            return (i - j);
14        }
15 
16        public Complex AddComplexNo(Complex i, Complex j)
17        {
18            Complex result = new Complex();
19            result.Real = i.Real + j.Real;
20            result.Imaginary = i.Imaginary + j.Imaginary;
21            return result;
22        }
23 
24        public Complex SubComplexNo(Complex i, Complex j)
25        {
26            Complex result = new Complex();
27            result.Real = i.Real - j.Real;
28            result.Imaginary = i.Imaginary - j.Imaginary;
29            return result;
30        }
31    }
32}
4.Modify the App.config file as shown
App.config
01<?xml version="1.0" encoding="utf-8" ?>
02<configuration>
03 
04  <system.web>
05    <compilation debug="true" />
06  </system.web>
07 
08  <system.serviceModel>
09    <services>
10      <service name="WcfMathServLib.MathService">
11 
12        <host>
13          <baseAddresses>
14            <add baseAddress ="http://localhost:8732/Design_Time_Addresses/WcfMathServLib/MathService/" />
15          </baseAddresses>
16        </host>
17 
18        <!-- Service Endpoints -->
19        <endpoint address ="" binding="wsHttpBinding" contract="WcfMathServLib.IMath">
20          <identity>
21            <dns value="localhost"/>
22          </identity>
23        </endpoint>
24 
25        <!-- Metadata Endpoints -->
26        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
27      </service>
28    </services>
29    <behaviors>
30 
31      <serviceBehaviors>
32        <behavior>
33           <serviceMetadata httpGetEnabled="True"/>
34          <serviceDebug includeExceptionDetailInFaults="False" />
35        </behavior>
36      </serviceBehaviors>
37    </behaviors>
38 
39  </system.serviceModel>
40 
41</configuration>

Result Using WCF Test Client

1. Run the WcfMathServLib project you will get the ‘WCF Test Client’
2. Select each method say ‘AddComplexNo’ Give the values in ‘Request’
3. Click on Invoke button
4. See the results in “Response”
Image(4)
Steps for creating ConsoleMathClient
1. Open Visual Studio 2010 and File->NewProject
2. select Visual C#->Windows in ‘Installed Templates’
3. select ‘Console Application’
4. Give Name as ConsoleMathClient
5. Click OK
image
2. Go to ‘Solution Explorer’ Right click on ConsoleMathClient -> Select ‘Add Service
Reference’ the below dialog will be displayed
1. Click on Discover button
2. Give namespace as ‘MathServiceReference’ and click OK
image
The service reference will be added now modify the program.cs as shown below.
Program.cs
01using System;
02using ConsoleMathClient.MathServiceReference;
03 
04namespace ConsoleMathClient
05{
06    class Program
07    {
08        static void Main(string[] args)
09        {
10            Console.WriteLine("Press <Enter> to run the client....");
11            Console.ReadLine();
12 
13            MathClient math = new MathClient();
14            Console.WriteLine("Add of 3 and 2 = {0}", math.Add(3, 2));
15            Console.WriteLine("Sub of 3 and 2 = {0}", math.Sub(3, 2));
16 
17            Complex no1 = new Complex();
18            no1.Real = 3;
19            no1.Imaginary = 3;
20 
21            Complex no2 = new Complex();
22            no2.Real = 2;
23            no2.Imaginary = 2;
24 
25            Complex result = new Complex();
26            result = math.AddComplexNo(no1, no2);
27            Console.WriteLine("Add of 3+3i and 2+2i = {0}+{1}i", result.Real, result.Imaginary);
28 
29            result = math.SubComplexNo(no1, no2);
30            Console.WriteLine("Sub of 3+3i and 2+2i = {0}+{1}i", result.Real, result.Imaginary);
31 
32            Console.ReadLine();
33        }
34    }
35}
Result
Compile and Run the project to see the Result
image

Friday, 25 January 2013

Alter schema name for whole database stored procedures using cursor


SELECT 'ALTER SCHEMA dbo TRANSFER ' + s.Name + '.' + p.Name FROM
sys.Procedures p INNER JOIN sys.Schemas s on p.schema_id = s.schema_id
where s.Name = 'ebiz1'

declare @ProcName varchar(500)
declare cur cursor
for SELECT 'ALTER SCHEMA dbo TRANSFER ' + s.Name + '.' + p.Name FROM sys.Procedures p INNER JOIN sys.Schemas s on p.schema_id = s.schema_id where s.Name = 'ebiz1'
open cur
fetch next from cur into @ProcName
while @@fetch_status = 0
begin
begin try
exec (@ProcName)
end try
begin catch
 select ERROR_MESSAGE() as ErrorMessage
end catch
 fetch next from cur into @ProcName
end
close cur
deallocate cur

Wednesday, 16 January 2013

Check string with delimiter and return as comma seperated string using SQL Server


Create Function dbo.CCMailToWithComma  --'test@test.com,example@gmail.com,test@yahoo.com'
(
 @MailSentTo varchar(max)
)
RETURNS VARCHAR(MAX)
BEGIN
    declare @list varchar(max)
    set @MailSentTo=dbo.Remove_Duplicate_Entry(@MailSentTo,',')
 
;with tmp
  (CorrMailSentToName,Data) as (
select
LEFT(@MailSentTo, CHARINDEX(',',@MailSentTo+',')-1)
,STUFF(@MailSentTo, 1, CHARINDEX(',',@MailSentTo+','), '')
union all
select
LEFT(Data, CHARINDEX(',',Data+',')-1)
,STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp
where CorrMailSentToName > ''
)
select
@list=coalesce(@list+',','')+a.CorrMailSentToName from tmp as a where a.CorrMailSentToName not in (SELECT CPT_email from CPT_UserMgmt)

if(@list is null or @list='')
set @list=''
else
set @list=SUBSTRING(@list,0,len(@list)-1)

    return @list
 end

Note : If Mail not found in that table then it returns
E.g - test@test.com and test@yahoo.com not found in table then

O/p:
-----
test@test.com,test@yahoo.com

---------------------------------------------------------------------------------------

Create  function dbo.UserNameWithComma --'Support@ebizgc.com,tst@gc.com,Support2@ebizgc.com,Support@ebizgc.com'
(
@MailSentTo varchar(max)
)
returns varchar(max)
as
begin
declare @list varchar(max)
    set @MailSentTo=dbo.Remove_Duplicate_Entry(@MailSentTo,',')
;with tmp
  (CorrMailSentToName,Data) as (
select
LEFT(@MailSentTo, CHARINDEX(',',@MailSentTo+',')-1)
,STUFF(@MailSentTo, 1, CHARINDEX(',',@MailSentTo+','), '')
union all
select
LEFT(Data, CHARINDEX(',',Data+',')-1)
,STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp
where CorrMailSentToName > ''
)

select
@list=coalesce(@list+',','')+b.CPT_FirstName+' '+b.CPT_LastName from tmp as a
inner join CPT_UserMgmt as b on b.CPT_email=a.CorrMailSentToName
where a.CorrMailSentToName is not null and len(a.CorrMailSentToName)>0
return @list
end

Remove Duplicate string with delimiter using SQL Server


Create Function dbo.Remove_Duplicate_Entry
(
      @Duplicate_String VARCHAR(MAX),
      @delimiter VARCHAR(2)
)
RETURNS VARCHAR(MAX)
BEGIN
     DECLARE @Xml XML
     DECLARE @Removed_Duplicate_String VARCHAR(Max)
     SET @Xml = cast(('<A>'+replace(@Duplicate_String,@delimiter,'</A><A>')+'</A>') AS XML)

     ;WITH CTE AS (SELECT A.value('.', 'varchar(max)') AS [Column]
      FROM @Xml.nodes('A') AS FN(A))

      SELECT @Removed_Duplicate_String =Stuff((SELECT '' + @delimiter + '' + [Column]  FROM CTE GROUP BY [column]
      FOR XML PATH('') ),1,1,'')
     
RETURN (@Removed_Duplicate_String)
END