Sunday 24 August 2014

creating a simple WCF secure service

This article discusses the simplest way to write, configure and consume Windows Communication Foundation (WCF) service, using Visual Studio 2010.

Problem Statement

Assume that
ZYZ Inc is one of the leading mobile menufacturing companies in India. Currently ABC Inc uses an XML based web service that provides the details of the various mobile models available for sale. The management of the ZYZ Inc wants their Web service to accommodate features such as reliable messaging, transactions, security and this web service should be accessible from any application of all platforms.

The developers of ZYZ Inc know that they can fullfill all the above requirements by developing the service in WCF.

Prerequisite: Create tblProduct in SqlServer for this Demo.

image1.gif

Solution

Task 1: Creating a WCF Service
To create a WCF service you need to perform the following tasks:

  1. Open Microsoft Visual Studio.
  2. Select "File" - "New" - "Website". A dialog box appears, as shown in the following figure.

    image2.gif
  3. Select the WCF Service template under the Visual Studio installed templates section.
  4. Click on the "OK" Button. The "App_Code/Service.cs" file appears, as shown in the following figure.

    image3.gif
  5. Add the following namespaces to the "App_Code/Service.cs" file:
    using System.Data;using System.Data.SqlClient;
     
  6. Remove the following code snippet from the Service class:
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);}
    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue +=
    "Suffix";
        }
        return composite;}
     
  7. Open "App_Code/Iservice.cs" and remove the following highlighted code from the interface:
    [ServiceContract]public interface IService{
        [OperationContract]
       
    string GetData(int value);
        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
       
    // TODO: Add your service operations here// Use a data contract as illustrated in the sample below to add composite types to service operations.[DataContract]public class CompositeType{
       
    bool boolValue = true;
       
    string stringValue = "Hello ";
        [DataMember]
       
    public bool BoolValue
        {
           
    get { return boolValue; }
           
    set { boolValue = value; }
        }
        [DataMember]
       
    public string StringValue
        {
           
    get { return stringValue; }
           
    set { stringValue = value; }
        }
    }
     
  8. Add the following namespace in the "App_Code/Iservice.cs" interface:
    using System.Data;
     
  9. Type the following code snippet for the "Iservice" interface as shown in the following figure.

    image4.gif
  10. Type the following code for the "Service.cs" file as shown in the following figure.

    image5.gif
  11. Verifying WCF Service.

    Press F5 to run your service; you will get a browser window as shown in the following figure.

    image6.gif
Task 2: Creating ASP.Net Client Application
  1. Open Visual Studio then click on "File" - "New" - "Web Site" - "ASP.Net website".
  2. Drag and drop a TextBox, Button and GrideView as shown in the following figure.

    image7.gif
  3. Switch to the Solution Explorer. Right-click on the root directory (the solution) and click on "Add Service Reference". Provide the WSDL file link in the Address TextBox, as shown in the following figure.

    image8.gif
  4. Click the "Ok" Button
  5. For the Click event of the Show Button write the following code:
    int Id = Convert.ToInt32(TextBox1.Text);
    ServiceReference1.
    ServiceClient proxy = new ServiceReference1.ServiceClient();
    GridView1.DataSource = proxy.QueryProduct(Id).Tables[0];
    GridView1.DataBind();
     
  6. Press F5 to run your ASP.Net application. Enter a product id in the TextBox and click on the Show Button. If everything goes well you will get the following output as shown in the following figure.

    imagenew9.gif

How to Create Windows Service in C# ?

I'm going to explain you , How will you can create simple windows service , Where You can do schedule activity.

Windows Services are applications that run in the background and perform various tasks. The applications do not have a user interface or produce any visual output. Windows Services are started automatically when computer is booted. They do not require a logged in user in order to execute and can run under the context of any user including the system. Windows Services are controlled through the Service Control Manager where they can be stopped, paused, and started as needed.


Step 1. Create Skeleton of the Service

To create a new Window Service, pick Windows Service option from your Visual C# Projects, give your service a name, and click OK.


Open visual studio --> Select File --> New -->Project--> select Windows Service
And give name as WinServiceSample (What ever your service name , Create with that name).



After give WinServiceSample name click ok button after create our project that should like this



In Solution explorer select Service1.cs file and change Service1.cs name to ScheduledService.cs because in this project I am using this name if you want to use another name for your service you should give your required name.

After change name of service open ScheduledService.cs in design view right click and select Properties now one window will open in that change Name value to ScheduledService and change ServiceName to ScheduledService. Check below properties window that should be like this


After change Name and ServiceName properties again open ScheduledService.cs in design view and right click on it to Add Installer files to our application.

The main purpose of using Windows Installer is an installation and configuration service provided with Windows. The installer service enables customers to provide better corporate deployment and provides a standard format for component management.

After click on Add installer a designer screen added to project with 2 controls: serviceProcessInstaller1 and ServiceInstaller1

Now right click on serviceProcessInstaller1 and select properties in that change Account to LocalSystem



After set those properties now right click on ServiceInstaller1 and change following StartType property to Automatic and give proper name for DisplayName property


After completion of setting all the properties now we need to write the code to run the windows services at scheduled intervals.

If you observe our project structure that contains Program.cs file that file contains Main() method otherwise write the Main() method like this in Program.cs file
 
 

/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ScheduledService()
};
ServiceBase.Run(ServicesToRun);
}
After completion of adding Main() method open ScheduledService.cs file and add following namespaces in codebehind of ScheduledService.cs file

using System.IO;
using System.Timers;
If you observe code behind file you will find two methods those are

protected override void OnStart(string[] args)
{
}

protected override void OnStop()
{
}
We will write entire code in these two methods to start and stop the windows service. Write the following code in code behind to run service in scheduled intervals
 
//Initialize the timer
Timer timer = new Timer();
public ScheduledService()
{
InitializeComponent();
}
//This method is used to raise event during start of service
protected override void OnStart(string[] args)
{
//add this line to text file during start of service
TraceService("start service");

//handle Elapsed event
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

//This statement is used to set interval to 1 minute (= 60,000 milliseconds)

timer.Interval = 90000;

//enabling the timer
timer.Enabled = true;
}
//This method is used to stop the service
protected override void OnStop()
{
timer.Enabled = false;
TraceService("stopping service");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TraceService("Another entry at "+DateTime.Now);
}
private void TraceService(string content)
{

//set up a filestream
FileStream fs = new FileStream(@"d:\ScheduledService.txt",FileMode.OpenOrCreate, FileAccess.Write);

//set up a streamwriter for adding text
StreamWriter sw = new StreamWriter(fs);

//find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End);

//add the text
sw.WriteLine(content);
//add the text to the underlying filestream

sw.Flush();
//close the writer
sw.Close();
 // Event Log 


this.EventLog = new System.Diagnostics.EventLog();
this.EventLog.Source = this.ServiceName;
this.EventLog.Log = "Application";
 
this.EventLog.WriteEntry("My Eventlog message.", EventLogEntryType.Information); 
 
}

If you observe above code in OnStart method I written event ElapsedEventHandler this event is used to run the windows service for every one minute

After completion code writing build the application and install windows service. To install windows service check this post here I explained clearly how to install windows service and how to start windows service

Now the service is installed. To start and stop the service, go to Control Panel --> Administrative Tools --> Services.  Right click the service and select Start. 

Now the service is started, and you will be able to see entries in the log file we defined in the code.

Now open the log file in your folder that Output of the file like this