Multiple Service Contracts in WCF Service

Objective

In this article, I will show you, how we can have multiple contracts in WCF service.

Block Diagram

clip_image002

Above block diagram says

1. There are three contracts.

2. All contracts are being implemented in same service class.

3. Each contract is exposed on different end points.

To start with follow the below steps,

Step 1

Create a WCF Service Application.

Step 2

Already by default IService1 contract is being added. Add two more contracts. Right click on the project and select add new item and then choose Interface from Code tab.

For my purpose, I am adding two more contracts called IMyContract1 and IMyContract2. So now there are three service contracts in my service. They are

1. IService1

2. IMyContract1

3. IMyContract2

IMyContract1

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

namespace MultipleEndpoints

{

[ServiceContract]

public interface IMyContract1

{

[OperationContract ]

string GetMessagefromIMyContract1();

}

}

IService1

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

namespace MultipleEndpoints

{

[ServiceContract]

public interface IService1

{

[OperationContract]

string GetMessagefromIService1();

}

}

IMyContract2

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

namespace MultipleEndpoints

{

[ServiceContract]

public interface IMyContract2

{

[OperationContract]

string GetMessagefromIMyContract2();

}

}

Step 3

Implement the contracts in same service class Service1.svc. All the function is just returning a simple string.

Service1.svc.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

namespace MultipleEndpoints

{

public class Service1 : IService1, IMyContract1, IMyContract2

{

public string GetMessagefromIService1()

{

return “Calling Default Contract IService1”;

}

public string GetMessagefromIMyContract1()

{

return “Calling My Contract IMyContract1”;

}

public string GetMessagefromIMyContract2()

{

return “Calling My Contract IMyContract2”;

}

}

}


Step4

Now we need to configure the end points for the different contracts. Just modify System.ServiceModel node in configuration file (Web.Config) as below

clip_image003

If you see the above end points configuration, different contracts has been exposed on different endpoints. Address of the end points is given as relative to base address. And each end point contains a unique name also. Address is unique for each end point.

Web.Config

<?xml version=1.0?>

<configuration>

<system.web>

<compilation debug=true targetFramework=4.0 />

</system.web>

<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior name =Mg>

<serviceMetadata httpGetEnabled=true/>

<serviceDebug includeExceptionDetailInFaults=false/>

</behavior>

</serviceBehaviors>

</behaviors>

<services >

<service name =MultipleEndpoints.Service1

behaviorConfiguration =Mg>

<endpoint name=firstBinding

address =/firstContract

binding =basicHttpBinding

contract =MultipleEndpoints.IService1 />

<endpoint name=secondBinding

address =/secondContract

binding =basicHttpBinding

contract =MultipleEndpoints.IMyContract1/>

<endpoint name=thirdBinding

address =/thirdContract

binding =basicHttpBinding

contract =MultipleEndpoints.IMyContract2/>

<endpoint contract=IMetadataExchange

binding=mexHttpBinding

address=mex />

<host>

<baseAddresses >

<add baseAddress =http://localhost:8180/Service1.svc/>

</baseAddresses>

</host>

</service >

</services>

</system.serviceModel>

<system.webServer>

<modules runAllManagedModulesForAllRequests=true/>

</system.webServer>

</configuration>

Step 5

Press F5 to run the service. Once service is up and running, we are ready to consume the service in client.

Step 6

Create a Console application as client. Add the service reference of the service. Now you can see, there are three proxy classes have been generated by WCF. Each class is corresponding to each service contracts exposed by the service through the end points.

clip_image004

You can see three service contracts have been exposed to the clients.

clip_image006

Above block diagram says the all that, each contract is exposed on different end points. And WCF created corresponding class for each contracts.

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using ConsoleApplication1.ServiceReference1;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

Service1Client p = new Service1Client(“firstBinding”);

MyContract1Client q = new MyContract1Client(“secondBinding”);

MyContract2Client r = new MyContract2Client(“thirdBinding”);

Console.WriteLine(p.GetMessagefromIService1());

Console.WriteLine(q.GetMessagefromIMyContract1());

Console.WriteLine(r.GetMessagefromIMyContract2());

Console.Read();

}

}

}


When you run, you will get output as

clip_image008

Thanks for reading. I hope article was useful. Happy Coding.

Configuring Multiple End points for WCF Service

Objective

In this article, I will explain how we could configure multiple binding for WCF service.

To see the video tutorial of hosting WCF Service in Console Application Click Here

i1

While creating multiple endpoints for the service, make sure each end point is having unique address. If address is not unique, you will catch with run time error.

i3

Mathematically, we can say

i2

Scenario for Multiple End Points

1. Service wants to expose more than one type of binding.

2. Service wants to expose more than one contract on the same binding.

3. Service wants to expose same binding and contract on different addresses.

Multiple End Points could be configuring in Web.Config file.

i4

Sample Service with multiple End Points

Step 1

Create a WCF Service Application. Open Visual studio and create new project selecting WCF Service Application project template. In VS2008, you will get WCF Service Application project template inside WEB tab whereas in VS2010, you will get WCF Service Application project template inside WCF tab.

Step 2

Delete the default code getting created for you by WCF. Delete all the code from IService1 and Service1. If you are using VS2008, comment out whole System.ServiceModel from Web.Config file. And if you are using VS2010 then comment out Multiple Host Binding.

Step 3

Contract is as below

clip_image007

Service implementation is

clip_image009

Step 4

To see the video tutorial of hosting WCF Service in Console Application Click Here

Create a console application to host the service.

For this,

1. Right click and add new project to your solution of Console type.

2. Add Reference of System.ServiceModel.

3. Add project reference of WCF Service Application created in Step 1.

4. Make this Console application as your startup project. To make this right click on console application and select make as startup project.

5. Right click on the console application then select add new item and then add new Application Configuration File.

clip_image011

Step 5

Configure the multiple end points here.

1. Add as many end points as you want in service tag.

2. Make sure none of the end points is having same address. Else you will get run time error.

3. Advisable is to use relative address. So for that add base address using Host tag.

So configuration file with multiple end points can look like,

clip_image013

Explanation

1. There are two end points getting exposed.

2. Relative address is being used to expose the end points.

3. Two end points are having their respective names as firstBinding and secondBinding.

Press F5 to run the host (Console) application.

clip_image015

Keep open this console running window. Do not close this window.

Step 6

Create a Console client. To do, open visual studio and create a new console application. Add Service Reference. Copy the base address from app.config of host console application (created in Step 5) and paste as Service URL.

clip_image017

You can see in above code, we are creating proxy twice by passing end point names respectively. If you want, you can pass address of respective endpoint also along with name of the end point.

clip_image019

When you press F5, you will get below output.

clip_image021

For your Reference full source code is given below,

WCF Service Application

Contract (IService1.cs)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

namespace MultipleEndpoints

{

[ServiceContract]

public interface IService1

{

[OperationContract]

string GreetingMessage(string Name);

}

}

Service1.svc.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

namespace MultipleEndpoints

{

public class Service1 : IService1

{

public string GreetingMessage(string name)

{

return “You are Called From “ + name;

}

}

}

Hosting Console Application

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using MultipleEndpoints;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

ServiceHost host = new ServiceHost(typeof(Service1));

host.Open();

Console.WriteLine(“Service is up and running”);

Console.WriteLine(“To Close Service Press any Key “);

Console.ReadKey();

host.Close();

}

}

}

App.Config

<?xml version=1.0 encoding=utf-8 ?>

<configuration>

<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior name =Mg>

<serviceMetadata httpGetEnabled=true/>

<serviceDebug includeExceptionDetailInFaults=false/>

</behavior>

</serviceBehaviors>

</behaviors>

<services >

<service name =MultipleEndpoints.Service1

behaviorConfiguration =Mg>

<endpoint name=firstBinding

address =/MyFirstBindingAddress

binding =basicHttpBinding

contract =MultipleEndpoints.IService1 />

<endpoint name=secondBinding

address =/MySecondBindingAddress

binding =basicHttpBinding

contract =MultipleEndpoints.IService1/>

<endpoint contract=IMetadataExchange

binding=mexHttpBinding

address=mex />

<host>

<baseAddresses >

<add baseAddress =http://localhost:8181/Service1.svc/>

</baseAddresses>

</host>

</service >

</services>

</system.serviceModel>

</configuration>

Client Console application

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using ConsoleApplication2.ServiceReference1;

namespace ConsoleApplication2

{

class Program

{

static void Main(string[] args)

{

Service1Client proxy1 = null;

proxy1 = new Service1Client(“firstBinding”);

Console.WriteLine(proxy1.GreetingMessage(“First End Point”));

proxy1 = new Service1Client(“secondBinding”);

Console.WriteLine(proxy1.GreetingMessage(“Second End Point”));

Service1Client proxy = null;

proxy = new Service1Client(“firstBinding”,

http://localhost:8181/Service1.svc/MyFirstBindingAddress&#8221;);

Console.WriteLine(proxy.GreetingMessage(“First End Point calling with Address”));

proxy = new Service1Client(“secondBinding”,

http://localhost:8181/Service1.svc/MySecondBindingAddress&#8221;);

Console.WriteLine(proxy.GreetingMessage(“Second End Point Calling with Address”));

Console.ReadLine();

}

}

}

I hope, this article was useful. Thanks for reading. Happy Coding.

Hosting WCF service in Console Application

This video will explain , how to host a WCF Service in a Console Application

For your reference soure code is as below ,

IService1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

 

namespace MultipleEndpoints

{

 

    [ServiceContract]

    public interface IService1

    {

 

        [OperationContract]

        string GreetingMessage(string Name);

    }

 

 

}

 

 

 
Service1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

 

namespace MultipleEndpoints

{

 

    public class Service1 : IService1

    {

        public string GreetingMessage(string name)

        {

            return "Welcome to WCF " + name;

        }

 

    }

}

 

Hosting Console Application

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using MultipleEndpoints;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

 

            ServiceHost host = new ServiceHost(typeof(Service1));

            host.Open();

            Console.Write("Service is up and running");

            Console.ReadKey();

            host.Close();

 

        }

    }

}

 

 

App.Config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <system.serviceModel>

    <behaviors>

      <serviceBehaviors>

        <behavior name ="Mg">

          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

          <serviceMetadata httpGetEnabled="true"/>

          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->

          <serviceDebug includeExceptionDetailInFaults="false"/>

        </behavior>

      </serviceBehaviors>

    </behaviors>

    <!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />-->

    <services >

      <service name ="MultipleEndpoints.Service1" behaviorConfiguration ="Mg">

        <endpoint address ="/MyAddress" binding ="basicHttpBinding" contract ="MultipleEndpoints.IService1" />

        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />

        <host>

          <baseAddresses >

            <add baseAddress ="http://localhost:8181/Service1.svc"/>

          </baseAddresses>

        </host>

      </service >

    </services>

  </system.serviceModel>

</configuration>

 


Thanks for watching this video. I hope this was useful. Happy Coding

FAULT Contract in WCF with Learning Video

Video of the article is HERE 

Objective

This article will give basic introduction on

1. How to handle Exception at service side?

2. How to use Fault contract at Service side?

3. How to handle Service Exception at client side?

Video explaining this article is here

Few points about Exception at Service

1. Exception is technology specific.

2. Exception should not share beyond service boundary.

3. Since Exception is technology specific they cannot be propagated to client.

4. Exception are of types

Ø CLR Exception

Ø Windows32 Exception

Ø Runtime Exception at service

Ø C++ Exception

5. Exception are very much native to the technology in which service is made.

6. Exception must be converted from technology specific information to natural information that can be communicated to client.

clip_image002

SOAP Fault

clip_image003

FaultException<T>

1. Service should throw FaultException<T> instead of usual CLR exception.

2. FaultException<T> is specialization of Fault Exception.

3. Any client that programs against FaultException can handle exception thrown by FaultException<T>.

4. The type parameter T conveys the error detail.

5. T can be of any type like Exception, CLR Type or any type that can be serialized. 

6. T can be of type Data contract.  

7. T is a generic parameter conveys the error details.  

 

About Fault Contract

1. Any Exception service want to share beyond service boundary comes must be goes at the part of service contract.

2. Fault contract says what type of exception service can throw to client.

3. The type in Fault Contract must be the same as the T of FaultException<T>

4. Fault contract is the contact between service and client about what exception can be thrown from service to client.

5. Fault contract is attributing of a method in the service. So only attributed method can throw the type of exception specified in Fault Contract.

Working sample

1. Create a simple WCF service with only one method. This method will have one output and two input parameters.

clip_image004

2. Implement the service contract

clip_image006

3. Press F5 to host the service in cassini server. Copy the URL from here.

4. Create a console client and add the service reference of the service we created.

5. Handle the exception at client side

clip_image008

6. Press F5 to get the exception information at client side. On running , you will get the exception message as below

clip_image010

So, we are getting the proper error message at the client side.

For your reference, source code is as below

Service side

IService1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

 

namespace FaultHandling

{

 

    [ServiceContract]

    public interface IService1

    {

        [OperationContract]

        [FaultContract(typeof(DivideByZeroException))]

        double divide(int num1, int num2);

 

    }  

}

 

 

Service1.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

 

namespace FaultHandling

{

 

    public class Service1 : IService1

    {

        public double divide(int num1, int num2)

        {

            if (num2 == 0)

            {

 

 

                DivideByZeroException myException = new DivideByZeroException();

                throw new FaultException<DivideByZeroException>(myException, “NUMBER 2 is 0”);

            }

            return num1 % num2;

        }

 

    }

}

 

 

 

Client side

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using ConsoleApplication3.ServiceReference1;

using System.ServiceModel;

 

namespace ConsoleApplication3

{

    class Program

    {

        static void Main(string[] args)

        {

            Service1Client proxy = new Service1Client();

            try

            {

                double result = proxy.divide(30,0);

                Console.WriteLine(result);

            }

            catch (FaultException<DivideByZeroException> ex)

            {

                Console.WriteLine(ex.Message);

            }

            Console.ReadKey();

        }

    }

}

 

 

Thanks for reading. I hope this article was useful for you. Happy Coding.

Learning Video on Fault Contract in WCF

This video is giving basic explanation on How to work with Fault Contract.

For reference Soure code is as below ,

IService1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

 

namespace demoFaultService

{

 

    [ServiceContract]

    public interface IService1

    {

        [OperationContract ]

        [FaultContract(typeof(DivideByZeroException))]

        double Div (double number1, double number2);

 

    }

}

 

Service.svc.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

 

namespace demoFaultService

{

 

    public class Service1 : IService1

    {

        public double Div(double number1, double number2)

        {

            if(number2 ==0)

            {

            DivideByZeroException exception = new DivideByZeroException();

                throw new FaultException<DivideByZeroException>(exception,“Number 2 is Zero at Service Side”);

            }

 

            return number1 % number2;

        }

 

 

    }

}

 

Client code is as below

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using ConsoleApplication3.ServiceReference1;

 

namespace ConsoleApplication3

{

    class Program

    {

        static void Main(string[] args)

        {

            Service1Client proxy = new Service1Client();

            try

            {

                double result = proxy.Div(30, 0);

                Console.WriteLine(result);

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.Message);

            }

            Console.ReadKey();

        }

    }

}

 

Shut Down, Restart, Log Off and Forced Log off System using c#

Objective

In this article, I am going to show,

  1. How to Shut Down a machine
  2. How to Log Off a machine
  3. How to forced log off a machine
  4. How to restart a machine using c#

To perform our task, very first let us create a windows application project. On form drag and drop four buttons for four different operations. After design form will look like below

 

Navigate to code behind of form and add reference of System.Runtime.InteropServices

Add a static extern method to Form.cs

Log off the System

On click event of Log Off button, call ExitWindowsEX method with proper flag. For log off operation flag value is 0.

 

Forced Log off the System

On click event of Forced Log Off button, call ExitWindowsEX method with proper flag. For Forced log off operation flag value is 4.

Shut Down the System

On click event of Shut down button, call ExitWindowsEX method with proper flag. For shut down operation flag value is 1.


Restart the System

On click event of Restart button, call ExitWindowsEX method with proper flag. For Restart operation flag value is 2.

Now when you run the application all system operation should be performed.

For your reference full source code is given here

Form.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Runtime.InteropServices;

 

namespace SystmShutDownApp

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

 

        }

 

 

        [DllImport(“user32.dll”)]

        public static extern int ExitWindowsEx(int operationFlag, int operationReason);

 

        private void btnRestart_Click(object sender, EventArgs e)

        {

              ExitWindowsEx(2, 0);

        }

 

        private void btnLogOff_Click(object sender, EventArgs e)

        {

            ExitWindowsEx(0, 0);

        }

 

        private void btnForcedLogOff_Click(object sender, EventArgs e)

        {

           ExitWindowsEx(4, 0);

        }

 

        private void btnShutDown_Click(object sender, EventArgs e)

        {

            ExitWindowsEx(1, 0);

        }    

    }

}

 

Thanks for reading. I hope post was useful. Happy Coding.

Custom Binding Part #2: creating a Basic REST service using CUSTOM Binding

In this article, I am going to show you how we could create a basic WCF REST service using custom binding.

Part 1 of this article series could be read Here

Follow the steps below,

Step 1

Create a new WCF service application project. Delete all the default codes getting created by WCF.

Step 2

Create the contract,

a

1. There is only one operation contract.

2. Function is returning Message and taking input parameter also as Message type.

3. * To ReplyAction says not to add reply action to the message.

4. * To Action will add that route all incoming request to this method.

Step 3

Implementing the service.

B

1. Using HTTPRequestMessageProperty class, I am finding absolute path for requesting URL.

2. Then I am checking whether request type is GET or not. If type is GET, I am displaying the message body.

3. Then I am checking the query string, if query string is there I am displaying that.

4. Then, I am creating the message. I am giving the message version as none. And appending a string. This will be displayed in browser as string.

5. Using HttpResponseMessageProperty class I am creating the response message. Then I am adding the custom header.

6. Then I am returning the response.

Compile the WCF Service application.

Step 4

Right click on the solution and add new project of the type console application. Right click on console application project and make it as startup project. Add the reference of System.ServiceModel and System.ServiceModel.Channel reference to the console project.

Step 5

Creating custom binding for REST Service.

C

 

 

1. I am creating object of CustomBinding class.

2. Then adding the binding elements in correct order.

3. For the transport adding the HttpTransportElement. Because we need to create a REST service and that follow only Http protocol.

4. Creating the service host and adding the endpoints.

Step 6

Go ahead and run the Console project. You will be getting the below console window.

D

Now open the browser and open the URL which you added as address in endpoint in the code. In my case it is Http://localhost:8889/TestHttp

E

And now when you see the command prompt you can see the other messages.

F

For your reference complete source code is as below ,

IService1.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Runtime.Serialization;

    5 using System.ServiceModel;

    6 using System.ServiceModel.Web;

    7 using System.Text;

    8 using System.ServiceModel.Channels ;

    9 

   10 namespace MyService

   11 {  

   12     [ServiceContract]

   13     public interface IService1

   14     {

   15         [OperationContract(Action = “*”, ReplyAction = “*”)]

   16          Message  GetMessage(Message msg);

   17 

   18     }

   19 }

   20 

Service1.svc.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Runtime.Serialization;

    5 using System.ServiceModel;

    6 using System.ServiceModel.Web;

    7 using System.Text;

    8 using System.ServiceModel.Channels ;

    9 

   10 namespace MyService

   11 {

   12     // NOTE: You can use the “Rename” command on the “Refactor” menu to change the class name “Service1” in code, svc and config file together.

   13     public class Service1 : IService1

   14     {

   15         public  Message   GetMessage(Message msg)

   16         {

   17             HttpRequestMessageProperty httpProps;

   18             string propName;

   19             propName = HttpRequestMessageProperty.Name;

   20             httpProps = msg.Properties[propName] as HttpRequestMessageProperty;

   21             string uri;

   22             uri = msg.Headers.To.AbsolutePath;

   23             Console.WriteLine(“Request to {0}”, uri);

   24             if (httpProps.Method != “GET”)

   25             {

   26                 Console.WriteLine(“Incoming Message {0} with method of {1}”,

   27                     msg.GetReaderAtBodyContents().ReadOuterXml(),

   28                     httpProps.Method);

   29 

   30             }

   31             else

   32             {

   33                 Console.WriteLine(“GET Request – no message body “);

   34             }

   35             if (httpProps.QueryString != null)

   36             {

   37                 Console.WriteLine(“QueryString = {0} “, httpProps.QueryString);

   38             }

   39             Message respone = Message.CreateMessage(MessageVersion.None, “*”, “Simple Response String”);

   40             HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty();

   41             responseProp.Headers.Add(“CustomHeader”, “Value”);

   42             return respone;

   43 

   44         }

   45     }

   46 }

   47 

And in console application

Program.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using System.ServiceModel;

    6 using System.ServiceModel.Channels;

    7 using System.ServiceModel.Description;

    8 using MyService;

    9 

   10 

   11 namespace HostingApplication

   12 {

   13     class Program

   14     {

   15         static void Main(string[] args)

   16         {

   17             CustomBinding myBinding = new CustomBinding();

   18             TextMessageEncodingBindingElement msgEncoder = new TextMessageEncodingBindingElement();

   19             msgEncoder.MessageVersion = MessageVersion.None;

   20             myBinding.Elements.Add(msgEncoder);

   21             HttpTransportBindingElement bindingelemt = new HttpTransportBindingElement();

   22             myBinding.Elements.Add(bindingelemt);

   23             ServiceHost sh = new ServiceHost(typeof(Service1));

   24             ServiceEndpoint endpoint = null;

   25              endpoint = sh.AddServiceEndpoint(typeof(IService1),myBinding ,“Http://localhost:8889/TestHttp”);           

   26             sh.Open();

   27             Console.WriteLine(“REST Service is running”);

   28             Console.WriteLine(“Press a Key to close the service”);

   29             Console.ReadKey();

   30 

   31 

   32 

   33         }

   34     }

   35 }

   36 

 

I hope this was useful article. Thanks for reading. Happy coding

Inserting and Retrieving Image using LINQ to SQL from ASP.Net Application

Objective

In this article, I am going to show you

1. How to insert an image from ASP.Net application to SQL Server using LINQ to SQL.

2. How to retrieve image from SQL Server data base using LINQ to SQL and display to an Image control.

Block Diagram of solution

clip_image002

Description of table

For my purpose, I have created a table called ImageTable.

clip_image003

1. Id is primary key.

2. Name column will contain name of the image file.

3. FileSource column will contain binary of image. Type of this column is image.

Create ASP.Net Web Application

Open visual studio and from File menu select New Project and then from Web tab select new web application. Give meaningful name to your web application.

Create DBML file using LINQ to SQL class.

For detail description on how to use LINQ to SQL class read HERE

1. Right click on the project and select add new item.

2. From DATA tab select LINQ to SQL Class.

3. On design surface select server explorer.

4. In server explorer and add new connection.

5. Give database server name and select database.

6. Dragged the table on the design surface.

Once all the steps done, you will have a dbml file created.

Design the page

1. I have dragged one FileUpload control and a button for upload purpose.

2. One text box. In this text box user will enter Id of the image to be fetched.

3. One button to fetch the image from database.

4. One Image control to display image from database.

Default.aspx

clip_image005

Saving image in table

On click event of Button 1 Image upload will be done.

clip_image007

In this code

1. First checking whether FileUplad control contains file or not.

2. Saving the file name in a string variable.

3. Reading file content in Byte array.

4. Then converting Byte array in Binary Object.

5. Creating instance of data context class.

6. Creating instance of ImageTable class using object initializer. Passing Id as hard coded value. Name as file name and FileSource as binary object.

Retrieving Image from table

On click event of button2 Image will be fetched of a particular Id. Image Id will be given by user in text box.

clip_image009

In above code, I am calling a generic HTTP handler. As query string value from textbox1 is appended to the URL of HTTP handler. To add HTTP handler, right click on project and add new item. Then select generic handler from web tab.

clip_image011

In above code,

1. Reading query string in a variable.

2. Calling a function returning ShowEmpImage returning Stream.

3. In ShowEmpImage , creating object DataContext class .

4. Using LINQ fetching a particular raw from table of a particular ID.

5. Converting image column in memory stream. In this case FileSource column is containing image.

6. Converting stream into byte array.

7. Reading byte array in series of integer.

8. Using Output stream writing the integer sequence.

Running application

 

output1 Output2

 Output3

For your reference entire source code is given below ,

Default.aspx.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Web;

    5 using System.Web.UI;

    6 using System.Web.UI.WebControls;

    7 using System.Data.Linq;

    8 using System.IO;

    9 

   10 namespace uploadingImageusingLInqtoSQl

   11 {

   12     public partial class _Default : System.Web.UI.Page

   13     {

   14         protected void Page_Load(object sender, EventArgs e)

   15         {

   16 

   17         }

   18 

   19         protected void Button1_Click(object sender, EventArgs e)

   20         {

   21             if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)

   22             {

   23                 string fileName = FileUpload1.FileName;           

   24 

   25                 byte[] fileByte = FileUpload1.FileBytes;

   26                 Binary binaryObj = new Binary(fileByte);

   27                 DataClasses1DataContext context = new DataClasses1DataContext();

   28                 context.ImageTables.InsertOnSubmit(

   29                     new ImageTable { Id = “xyz”,

   30                         Name = fileName,

   31                         FileSource = binaryObj });

   32                 context.SubmitChanges();

   33 

   34 

   35             }

   36         }

   37 

   38         protected void Button2_Click(object sender, EventArgs e)

   39         {

   40 

   41 

   42             Image1.ImageUrl = “~/MyPhoto.ashx?Id=”+TextBox1.Text;

   43 

   44         }

   45 

   46 

   47     }

   48 }

   49 

 

MyPhoto.ashx.cs

 

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Web;

    5 using System.IO;

    6 using System.Web.UI;

    7 using System.Web.UI.WebControls;

    8 

    9 

   10 namespace uploadingImageusingLInqtoSQl

   11 {

   12     /// <summary>

   13     /// Summary description for MyPhoto

   14     /// </summary>

   15     public class MyPhoto : IHttpHandler

   16     {

   17 

   18         public void ProcessRequest(HttpContext context)

   19         {

   20 

   21             string id = context.Request.QueryString[“Id”];

   22             context.Response.ContentType = “image/jpeg”;

   23             Stream strm = ShowEmpImage(id);

   24             byte[] buffer = new byte[4096];

   25             int byteSeq = strm.Read(buffer, 0, 4096);

   26             while (byteSeq > 0)

   27             {

   28                 context.Response.OutputStream.Write(buffer, 0, byteSeq);

   29                 byteSeq = strm.Read(buffer, 0, 4096);

   30             }  

   31         }

   32 

   33         public Stream ShowEmpImage(string id)

   34         {

   35             DataClasses1DataContext context1 = new DataClasses1DataContext();

   36             var r = (from a in context1.ImageTables where a.Id == id select a).First();

   37             return new MemoryStream(r.FileSource.ToArray());         

   38 

   39         }

   40         public bool IsReusable

   41         {

   42             get

   43             {

   44                 return false;

   45             }

   46         }

   47     }

   48 }

 

Thanks for reading. I hope this post is useful. Happy Coding.

Simple Explanation for very beginners of Query String

Query String allows you to pass values between the asp.net pages.

Let us say, you are navigating to below URL

In above URL, you are navigating to a page called Add.aspx and Number1 and Number2 are query string to page Add.aspx.

To create Query String,

  1. Add a question mark (?) to URL.
  2. After Question mark, give variable name and value separated by equal to (=).
  3. If more than one parameter need to be passed then separate them by ampersand (&).

To read query String,

Say your URL is,

http://localhost:12165/Add.aspx?Number1=72&Number2=27

Then to read query string, on Add.aspx

You can read by passing exact variable name in index or,

You can read, by passing index value as above.

Now, I am going to show you a very basic sample,

  1. I will create a page with two text boxes and one link button.
  2. I will pass text boxes values as query string to other page on click event of link button.
  3. On the other page, I will read the query string value and will add them in display in a label.

I have created a new asp.net application. Then I dragged and dropped two textboxes and one link button on the page. On click event of link button, I am performing the below operation.

I am constructing the URL, as to navigate to Add.aspx page and then appending two query strings from textbox1 text and textbox2 text.

Now, add a page to project say Add.aspx . Drag and drop a label on the page. On the page load event perform the below operation.

 \

So, when you run the application you will get the output as below,

For your reference, the whole source code is given below,

Default.aspx.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Web;

    5 using System.Web.UI;

    6 using System.Web.UI.WebControls;

    7 

    8 namespace queryparameterexample

    9 {

   10     public partial class _Default : System.Web.UI.Page

   11     {

   12         protected void Page_Load(object sender, EventArgs e)

   13         {

   14 

   15         }

   16 

   17 

   18         protected void LinkButton1_Click(object sender, EventArgs e)

   19         {

   20             string urltoNaviget = “~/Add.aspx?Number1=” +

   21                                      TextBox1.Text +

   22                                      “&Number2=” +

   23                                      TextBox2.Text;

   24 

   25             LinkButton1.PostBackUrl = urltoNaviget;

   26         }

   27     }

   28 }

   29 

Add.aspx.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Web;

    5 using System.Web.UI;

    6 using System.Web.UI.WebControls;

    7 

    8 namespace queryparameterexample

    9 {

   10     public partial class WebForm1 : System.Web.UI.Page

   11     {

   12         protected void Page_Load(object sender, EventArgs e)

   13         {

   14 

   15             string number1 = Request.QueryString[0];

   16             string number2 = Request.QueryString[1];

   17 

   18             // The other way to Read the values

   19             //string number1 = Request.QueryString[“Number1”];

   20             //string number2 = Request.QueryString[“Number2”];

   21 

   22             int result = Convert.ToInt32(number1) + Convert.ToInt32(number2);

   23             Label2.Text = result.ToString();

   24 

   25         }

   26     }

   27 }


 

I hope this post is useful. Thanks for reading. Happy Coding.

7 queries on LINQ to SQL class

 In this article, I am going to show you how we can perform various operations using LINQ to SQL.

Database description

Let us say, I have created a database called ILPTrainee. This table got only one table with below structure

EmpId is primary key here.

For our explanation, I have put few records in the table. So table with records is as below

 

Using LINQ to SQL Class

  1. Create a new project of type class library.
  2. Right click on the project and add new item and select LINQ to SQL Class from Data tab.
  3. Select Server Explorer. Then Server Explorer will get open. Click on Data connection and Add new connection.
  4. In Server name give name of your database server and from drop down select the database.
  5. Once you are done with above steps, you can see a dbml file got generated in solution explorer.

    Follow the diagrams below, in order left to right and top to down.

     

    LINQ to SQL class is an ORM which creates a class representing your table from the database. It will create a datacontext class. We will apply query against generated data context class.

    TraineeModels class is representation of TraineeModel table.

    Now querying

    To perform query add a new class in the same class library project. Make this class as static. Add various static methods that will be performing different types of query.

    Query 1 # retrieving all the records from table

    Explanation

    1. I created instance of Data Context class.
    2. I applied simple LINQ query to retrieve all the records from the table TraineeModels in data context.

    Query 2 # retrieving selected records from table

    Explanation

    1. I created instance of Data Context class.
    2. I applied simple LINQ query to retrieve all the records from the table TraineeModels in data context.
    3. I applied where clause to filter the data.

    Query 3 # inserting a single record

    Explanation

    1. I created instance of Data Context class.
    2. Input parameter to this method is object of TraineeModel class.
    3. I am using InsertOnSubmit method on the datacontext class to insert one record.
    4. Then finally, I am calling the submitchanges to commit the database on datacontext.

    Query 4 #Updating a Record

    Explanation

    1. I created instance of Data Context class.
    2. Input parameter to this method is object of TraineeModel class.
    3. I am retrieving the object to be modified using where clause.
    4. After modification, calling the submitchanges on data context.

Query 5 #Deleting a Record


 

Explanation

  1. I created instance of Data Context class.
  2. Input parameter to this method is empid as string to be deleted.
  3. I am retrieving the object to be deleted using where clause.
  4. After deletion, calling the submitchanges on data context.

Query 6# Adding List of Records

Explanation

  1. I created instance of Data Context class.
  2. Input parameter to this method is List of TraineeModels to be inserted.
  3. I am inserting the records using InsertAllOnSubmit method on data context class.
  4. After insertion, calling the submitchanges on data context.

Query 7# Deleting List of Records

Explanation

  1. I created instance of Data Context class.
  2. Input parameter to this method is List of TraineeModels to be deletd.
  3. I am deleting the records using deleteAllOnSubmit method on data context class.
  4. After insertion, calling the submitchanges on data context.

Up to this step, I have written all possible LINQ query to be used for CRUD operation. Now to use this query just call the methods with class name.

For your reference, whole code is given below.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 

    6 namespace DataOperationsLibrary

    7 {

    8     public static  class CRUDRepository

    9     {

   10         public static List<TraineeModel> GetTrainees()

   11         {

   12            DataClasses1DataContext context = new DataClasses1DataContext();

   13 

   14            var result = from r in context.TraineeModels select r;

   15            return result.ToList();

   16 

   17         }

   18 

   19         public TraineeModel GetSelectedTrainee(string EmpId)

   20         {

   21             DataClasses1DataContext context = new DataClasses1DataContext();

   22 

   23             TraineeModel traineeResult = (from r in context.TraineeModels where r.EmpId == EmpId

   24                                           select r).First();

   25 

   26             return traineeResult;

   27         }

   28 

   29 

   30         public static bool AddTrainee(TraineeModel  trainee)

   31         {

   32             try

   33             {

   34                 DataClasses1DataContext context = new DataClasses1DataContext();

   35                 context.TraineeModels.InsertOnSubmit(trainee);

   36                 context.SubmitChanges();

   37                 return true;

   38             }

   39             catch

   40             {

   41                 return false;

   42             }

   43         }

   44         public static bool DeleteTrainee(string empID)

   45         {

   46             try

   47             {

   48                 DataClasses1DataContext context = new DataClasses1DataContext();

   49                 TraineeModel  obj = (from r in context.TraineeModels

   50                                           where r.EmpId.Contains(empID)

   51                                           select r).First();

   52                 if (obj != null)

   53                 {

   54                     context.TraineeModels .DeleteOnSubmit(obj);

   55                     context.SubmitChanges();

   56                     return true;

   57                 }

   58                 else

   59                 {

   60                     return false;

   61                 }

   62 

   63             }

   64             catch

   65             {

   66                 return false;

   67             }

   68         }

   69         public static bool UpdateTrainee(TraineeModel  trainee)

   70         {

   71             try

   72             {

   73                 DataClasses1DataContext context = new DataClasses1DataContext();

   74                 TraineeModel  res = (from r in context.TraineeModels

   75                                           where r.EmpId.Contains(trainee.EmpId)

   76                                           select r

   77                                           ).First();

   78 

   79 

   80                 res.EmpName = trainee.EmpName;

   81                 res.Expertise = trainee.Expertise;

   82                 res.Native = trainee.Native;

   83 

   84                 context.SubmitChanges();

   85                 return true;

   86             }

   87             catch

   88             {

   89                 return false;

   90             }

   91 

   92 

   93         }

   94         public static bool AddTrainees(List<TraineeModel> lstTrainee)

   95         {

   96             try

   97             {

   98                 DataClasses1DataContext context = new DataClasses1DataContext();

   99                 context.TraineeModels.InsertAllOnSubmit(lstTrainee);

  100                 context.SubmitChanges();

  101                 return true;

  102             }

  103             catch

  104             {

  105                 return false;

  106             }

  107         }

  108 

  109         public static bool DeleteTrainees(List<TraineeModel> lstTrainee)

  110         {

  111             try

  112             {

  113                 DataClasses1DataContext context = new DataClasses1DataContext();

  114                 context.TraineeModels.DeleteAllOnSubmit(lstTrainee);

  115                 context.SubmitChanges();

  116                 return true;

  117             }

  118             catch

  119             {

  120                 return false;

  121             }

  122         }

  123     }

  124 }

  125 

I hope, this post was useful. Thanks for reading. Happy Coding.