Wednesday 21 November 2018

WCF Service as Windows Service

Host a WCF Service in a Managed Windows Service

This topic outlines the basic steps required to create a Windows Communication Foundation (WCF) service that is hosted by a Windows Service. The scenario is enabled by the managed Windows service hosting option that is a long-running WCF service hosted outside of Internet Information Services (IIS) in a secure environment that is not message activated. 

The service code includes a service implementation of the service contract, a Windows Service class, and an installer class. The service implementation class, CalculatorService, is a WCF service. The CalculatorWindowsService is a Windows service. To qualify as a Windows service, the class inherits from ServiceBase and implements the OnStartand OnStop methods. In OnStart, a ServiceHost is created for the CalculatorService type and opened. In OnStop, the service is stopped and disposed. The host is also responsible for providing a base address to the service host, which has been configured in application settings. The installer class, which inherits from Installer, allows the program to be installed as a Windows service by the Installutil.exe tool.

Construct the service and provide the hosting code
  1. Create a new Visual Studio Console app project called WcfAsWindows.
  2. Rename Program.cs to Service.cs.
  3. Change the namespace to Microsoft.ServiceModel.Samples.
  4. Add references to the following assemblies:
    • System.ServiceModel.dll
    • System.ServiceProcess.dll
    • System.Configuration.Install.dll
Add the following using statements to Service.cs.

using System.ComponentModel; using System.ServiceModel; using System.ServiceProcess; using System.Configuration; using System.Configuration.Install;

Define the ICalculator service contract as shown in the following code.

// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
    [OperationContract]
    double Add(double n1double n2);
    [OperationContract]
    double Subtract(double n1double n2);
    [OperationContract]
    double Multiply(double n1double n2);
    [OperationContract]
    double Divide(double n1double n2);
}

Implement the service contract in a class called CalculatorService as shown in the following code.

// Implement the ICalculator service contract in a service class.
public class CalculatorService : ICalculator
{
    // Implement the ICalculator methods.
    public double Add(double n1double n2)
    {
        double result = n1 + n2;
        return result;
    }

    public double Subtract(double n1double n2)
    {
        double result = n1 - n2;
        return result;
    }

    public double Multiply(double n1double n2)
    {
        double result = n1 * n2;
        return result;
    }

    public double Divide(double n1double n2)
    {
        double result = n1 / n2;
        return result;
    }
}

Create a new class called CalculatorWindowsService that inherits from the ServiceBase class. Add a local variable called serviceHost to reference the ServiceHost instance. Define the Main method that calls 

ServiceBase.Run(new CalculatorWindowsService)

public class CalculatorWindowsService : ServiceBase
{
    public ServiceHost serviceHost = null;
    public CalculatorWindowsService()
    {
        // Name the Windows Service
        ServiceName = "WCFWindowsServiceSample";
    }

    public static void Main()
    {
        ServiceBase.Run(new CalculatorWindowsService());
    }
 }

Override the OnStart(String[]) method by creating and opening a new ServiceHost instance as shown in the following code.

// Start the Windows service.
protected override void OnStart(string[] args)
{
    if (serviceHost != null)
    {
        serviceHost.Close();
    }

    // Create a ServiceHost for the CalculatorService type and 
    // provide the base address.
    serviceHost = new ServiceHost(typeof(CalculatorService));

    // Open the ServiceHostBase to create listeners and start 
    // listening for messages.
    serviceHost.Open();
}

Override the OnStop method closing the ServiceHost as shown in the following code.

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

Create a new class called ProjectInstaller that inherits from Installer and that is marked with the RunInstallerAttribute set to true. This allows the Windows service to be installed by the Installutil.exe tool.

// Provide the ProjectInstaller class which allows 
// the service to be installed by the Installutil.exe tool
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
    private ServiceProcessInstaller process;
    private ServiceInstaller service;

    public ProjectInstaller()
    {
        process = new ServiceProcessInstaller();
        process.Account = ServiceAccount.LocalSystem;
        service = new ServiceInstaller();
        service.ServiceName = "WCFWindowsServiceSample";
        Installers.Add(process);
        Installers.Add(service);
    }
}

Remove the Service class that was generated when you created the project.

Add an application configuration file to the project. Replace the contents of the file with the following configuration XML.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>    <services>
      <!-- This section is optional with the new configuration model
           introduced in .NET Framework 4. -->
      <service name="Microsoft.ServiceModel.Samples.CalculatorService"
               behaviorConfiguration="CalculatorServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
          </baseAddresses>
        </host>
        <!-- this endpoint is exposed at the base address provided by hosthttp://localhost:8000/ServiceModelSamples/service  -->
        <endpoint address=""
                  binding="wsHttpBinding"
                  contract="Microsoft.ServiceModel.Samples.ICalculator" />
        <!-- the mex endpoint is exposed at http://localhost:8000/ServiceModelSamples/service/mex -->
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="CalculatorServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Right click the App.config file in the Solution Explorer and select Properties. Under Copy to Output Directoryselect Copy if Newer.

This example explicitly specifies endpoints in the configuration file. If you do not add any endpoints to the service, the runtime adds default endpoints for you. In this example, because the service has a ServiceMetadataBehavior set to true, your service also has publishing metadata enabled. For more information about default endpoints, bindings, and behaviors, see Simplified Configuration and Simplified Configuration for WCF Services.

Install and run the service

Build the solution to create the WcfAsWindows.exe executable.

Open Developer Command Prompt (Administration mode) for Visual Studio and navigate to the project directory. Type installutil bin\WcfAsWindows.exe at the command prompt to install the Windows service.



Type services.msc at the command prompt to access the Service Control Manager (SCM). The Windows service should appear in Services as "WCFWindowsServiceSample". The WCF service can only respond to clients if the Windows service is running. To start the service, right-click it in the SCM and select "Start", or type net start WCFWindowsServiceSample at the command prompt.


If you make changes to the service, you must first stop it and uninstall it. 
To uninstall the Windows service type installutil /u bin\service.exe at the command prompt.

Download the complete project click here



Continue Reading →

Monday 19 November 2018

Custom Routes for MVC Application

When you request any page into MVC Application, it will go through the Routing Architecture. Your Routing system will decide your URL pattern. The default routing algorithm is like {controller}/ {action}/ {id} patterns. But it can be possible to change that pattern using Custom Routes.

Default Route
You can configure Route into the Global.aspx's Application Start Event. When you are creating an MVC application, it will already define Default route. Default route can be configured using the following code:

     routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });


Custom Routes
It is possible to develop an MVC application without creating a Custom Route. But sometimes, there is a situation to change the pattern of URL in which it makes sense to create Custom Routes.

Examples of Valid Route Patterns in ASP.NET MVC

Route PatternURL Example
mysite/{username}/{action}~/mysite/jatten/login
public/blog/{controller}-{action}/{postId}~/public/blog/posts-show/123
{country}-{lang}/{controller}/{action}/{id}~/us-en/products/show/123
products/buy/{productId}-{productName}~/products/but/2145-widgets

Suppose I have a BlogController like below.

public class BlogController : Controller
    {
        public string Archive(DateTime? entryDate)
        {
            return "You wants Blog Entry on Date:=" + entryDate.ToString();
        }

        public string All()
        {
            return "All function";
        }

        public string getData(string name, int empId)
        {
            return "name: " + name + " id= " + empId;
        }
     }

1- Imagine that you want to route a request look like: /Archive/12-25-2010.

          routes.MapRoute(
                            "myBlogRoute1",
                            "{Archive}/{entrydate}",

                            new { Controller = "Blog", action = "Archive", });

2- Imagine that you want to route a request look like: /MyBlogs/All/12 or /MyBlogs/All/

            // MyBlogs/All/12  
            // MyBlogs/All/
            routes.MapRoute(
                   name: "myBlogRoute2",
                   url: "MyBlogs/{action}/{id}",
                   defaults: new
                   {
                       controller = "Blog",
                       action = "All",
                       id = UrlParameter.Optional
                   }

                 );

3- Imagine that you want to route a request look like: /MyBlogs/Suraj/Post/101

            // MyBlogs/suraj/Post/101
            routes.MapRoute(
                name: "myBlogRoute3",
                url: "MyBlogs/{name}/Post/{postId}",
                defaults: new
                {
                    controller = "Blog",
                    action = "getData",
                }

            );

https://www.tutorialsteacher.com/
Continue Reading →

Thursday 15 November 2018

Exception Handling in Web API

Exception Handling in ASP.NET Web API
There are many ways to handle the exception.
  1. HttpResponseException
  2. Exception Filters
  3. HttpError
HttpResponseException: This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor.

public Product GetProduct(int id) {
    Product item = repository.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return item;
}

Exception Filters: You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response. Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface.
The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.

public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute 
    {
        public override void OnException(HttpActionExecutedContext context)
        {
          if (context.Exception is NotImplementedException)
          {
            context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
          }
        }
    }

Register Exception Filters

There are many ways to register exception filter but the developers generally follow three approaches to register filter.
  1. Decorate Action with exception filter.
  2. Decorate Controller with exception filter.
  3. Filter Register globally.
To apply the filter to a specific action, add the filter as an attribute to the action:

public class ProductsController : ApiController
{
    [NotImplExceptionFilter]
    public Contact GetContact(int id)
    {
        throw new NotImplementedException("This method is not implemented");
    }
}


To apply the filter to all of the actions on a controller, add the filter as an attribute to the controller class:

[NotImplExceptionFilter]
public class ProductsController : ApiController
{
    // ...
}

To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration.Configuration.Filters collection. Exeption filters in this collection apply to any Web API controller action.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute());

        // Other configuration code...
    }
}

HttpError: CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client.

public HttpResponseMessage GetProduct(int id) {
    Product item = repository.Get(id);
    if (item == null)
    {
        var message = string.Format("Product with id = {0} not found"id);
        return Request.CreateErrorResponse(HttpStatusCode.NotFoundmessage);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OKitem);
    }
}
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives