Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts



In this article, we will see how to create a simple WCF application and calling that in Windows services.

First we will create a WCF application called WCFExample.




 
Rename the default Contract .cs file as IPwdService.cs, and add one service contract, See the below one.

IPwdService.cs


using System;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace WCFExample
{
    // NOTE: If you change the interface name "IPwdService" here, you must also update the reference to "IPwdService" in Web.config.
    [ServiceContract]
    public interface IPwdService
    {
        [OperationContract]
        bool SetPwd(string sPassword);
        [OperationContract]
        bool PwdStatus();
    }
}


Then rename the .svc file as PwdService.svc and map the Serivice and CodeBehind property in SeviceHost directive like below,

<%@ ServiceHost Language="C#" Debug="true" Service="WCFExample.PwdService" CodeBehind="PwdService.svc.cs" %>

In code behind, we inherit the contract interface in a class and do the implementation like below,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace WCFExample
{
// NOTE: If you change the class name "PwdService" here, you must also update the reference to "PwdService" in Web.config and in the associated .svc file.
public class PwdService : IPwdService
{
private static string sPwd = "";

public bool PwdStatus()
{
if (sPwd != "")
    return true;
else
    return false;
}

public bool SetPwd(string sPassword)
{
SLAManager.HOVSDBManager objSLA = new SLAManager.HOVSDBManager();
try
{
    bool bReturn = false;
    DataTable dtStatus = new DataTable();
    objSLA.CreateParameters(1);
    objSLA.AddParameters(0, "@MasterKey", sPassword);
    dtStatus = objSLA.ExecuteDataTable(CommandType.StoredProcedure, "Usp_ValidatePassCode");
    if (dtStatus != null)
        if (dtStatus.Rows.Count == 1)
            if (dtStatus.Rows[0][0].ToString() == "Valid")
            {
                sPwd = sPassword;
                bReturn = true;
            }
    return bReturn;
}
catch
{
    return false;
}
finally
{
    if (objSLA != null)
    {
        objSLA = null;
    }
}
}

public static string GetPwdWS()
{
return sPwd;
}
}
}
Here we have setting a password and return based on our need. We take a build and it will create “WCFExample.dll.”

We also need to consider the Web.Config. It is having endpoint to call this WCF in different places like http, tcp and ntp. Here i have host in local server.

<system.serviceModel>
<services>
<service behaviorConfiguration="WCFExample.PwdServiceBehavior"
  name="WCFExample.PwdService">
  <endpoint address="" binding="wsHttpBinding" contract="WCFExample.IPwdService">
    <identity>
      <dns value="localhost" />
    </identity>
  </endpoint>
  <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
  <behavior name="WCFExample.PwdServiceBehavior">
    <!-- 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>
</system.serviceModel>



Now, We add the new Windows Service project to our Solution for make a use of WCF.
It have two files Service1.cs and Program.cs by default.



Now we review the program.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace WindowsServiceExample
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
                             {
                                       new WindowsTestService()
                             };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

At execution the Main() called and the WindowsTestService class and run it as a service with a priod of time intervals.

Then right click the WindowsService file(default service1.cs) and add installer.It will add the two differenct control as separate file(give a name as ProjectInstaller.cs). The code like below

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;


namespace WindowsServiceExample
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

        private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
        {
            //To start Service once installation is complete
            new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName).Start();
        }
    }
}

Here, we add the service to run after installing a service in your system/server.

Rename the Service1.cs as WindowsTestService.cs and do your needs. In this example I will connect to DB get the password and run it a Stored procedure and to do some Job.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Configuration;
using WCFExample;
using System.Security.Principal;

namespace WindowsServiceExample
{
public partial class WindowsTestService : ServiceBase
{
Timer objtimer = new Timer(1 * 5 * 60 * 1000);
private static string sPassword = "";
internal static ServiceHost HostWCF = null;
SLAManager.HOVSDBManager objSLA;

public WindowsTestService()
{
InitializeComponent();
}

//Each time interval start it will executed.
protected override void OnStart(string[] args)
{
try
{
    objtimer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    objtimer.Enabled = true;

    if (HostWCF != null)
    {
        HostWCF.Close();
    }
    //Create a URI to serve as the base address
    Uri httpUrl = new Uri("http://10.20.57.250:8090/WCFExample");

    WSHttpBinding wsbind = new WSHttpBinding();
    wsbind.UseDefaultWebProxy = false;

    //Create ServiceHost
    HostWCF = new ServiceHost(typeof(WCFExample.PwdService), httpUrl);
    //Add a service endpoint
    HostWCF.AddServiceEndpoint(typeof(WCFExample.IPwdService), wsbind, "PwdService");
    //Enable metadata exchange
    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
    smb.HttpGetEnabled = true;
    HostWCF.Description.Behaviors.Add(smb);
    //Start the Service
    HostWCF.Open();
    
    //Start Log
    objSLA = new SLAManager.HOVSDBManager();
    objSLA.CreateParameters(3);
    objSLA.AddParameters(0, "@Status", "X");
    objSLA.AddParameters(1, "@Host", System.Net.Dns.GetHostName());
    objSLA.AddParameters(2, "@User", Environment.UserDomainName);
    objSLA.ExecuteNonQuery(CommandType.StoredProcedure, "usp_TestJobExecutionFromWindowsService");
}
catch (Exception ex)
{
    objSLA = new SLAManager.HOVSDBManager();
    objSLA.CreateParameters(3);
    objSLA.AddParameters(0, "@Status", "F");
    objSLA.AddParameters(1, "@Host", System.Net.Dns.GetHostName());
    objSLA.AddParameters(2, "@Info", ex.Message);
    objSLA.ExecuteNonQuery(CommandType.StoredProcedure, "usp_TestJobExecutionFromWindowsService");
}
finally
{
    objSLA = null;
}
}


//On Elapsed time do other operation
protected void OnElapsedTime(object sender, ElapsedEventArgs e)
{
try
{
    if (HostWCF != null)
    {
        if (sPassword == "")
        {
            //Get Password from WCF
            sPassword = PwdService.GetPwdWS();
        }
        //If still pwd is null then send mail
        if (sPassword == "")
        {
            objSLA = new SLAManager.HOVSDBManager();
            objSLA.CreateParameters(2);
            objSLA.AddParameters(0, "@Status", "P");
            objSLA.AddParameters(1, "@Host", System.Net.Dns.GetHostName());
            objSLA.ExecuteNonQuery(CommandType.StoredProcedure, "usp_TestJobExecutionFromWindowsService");
            // objSLA = null;
        }
        else
        {
            objSLA = new SLAManager.HOVSDBManager();
            objSLA.CreateParameters(1);
            objSLA.AddParameters(0, "@MasterKey", sPassword);
            objSLA.ExecuteNonQuery(CommandType.StoredProcedure, "Usp_AnotherJobRun");
        }
    }
}
catch (Exception ex)
{
    objSLA = new SLAManager.HOVSDBManager();
    objSLA.CreateParameters(3);
    objSLA.AddParameters(0, "@Status", "F");
    objSLA.AddParameters(1, "@Host", System.Net.Dns.GetHostName());
    objSLA.AddParameters(2, "@Info", ex.Message);
    objSLA.ExecuteNonQuery(CommandType.StoredProcedure, "usp_TestJobExecutionFromWindowsService");
}
finally
{
    objSLA = null;
}
}

protected override void OnStop()
{
try
{
    if (HostWCF != null)
    {
        HostWCF.Close();
        HostWCF = null;
    }

    //Stop Log
    objSLA = new SLAManager.HOVSDBManager();
    objSLA.CreateParameters(3);
    objSLA.AddParameters(0, "@Status", "E");
    objSLA.AddParameters(1, "@Host", System.Net.Dns.GetHostName());
    objSLA.AddParameters(2, "@User", Environment.UserDomainName);
    objSLA.ExecuteNonQuery(CommandType.StoredProcedure, "usp_TestJobExecutionFromWindowsService");
}
catch (Exception ex)
{
    objSLA = new SLAManager.HOVSDBManager();
    objSLA.CreateParameters(3);
    objSLA.AddParameters(0, "@Status", "F");
    objSLA.AddParameters(1, "@Host", System.Net.Dns.GetHostName());
    objSLA.AddParameters(2, "@Info", ex.Message);
    objSLA.ExecuteNonQuery(CommandType.StoredProcedure, "usp_TestJobExecutionFromWindowsService");
}
finally
{
    objSLA = null;
}
}
}
}


This is one way to host a WCF. Service installment Operations please visit