Authorization Filter – Reusable/Common components for ASP.NET MVC 3.0

 

Suppose we want to apply an authorization to every action except the action that lets the user login than Decorate [Authorize] attribute to all methods except login one.

Code

There are some risks if we follow above approach.

1. Programmer might miss to decorate one or more method (Security risk)

2. Maintainability issue. Require to prepare tracker.

To solve above problem, now ASP.NET MVC 3 introduces global filters. For this we have to create class which derived from Authorize class (LogonAuthorize – which I have created ) and register into Global.asax.

Once we register custom Authorize class into Global.asax, it introduce another problem. We can’t call the logon and registration methods too because we have set globally that before calling any action method, user must be login into application.

To solve above problem, we have to write attribute (AllowAnonymous – which I have created) and inform to the application that don’t expect login if any action method is decorated with AllowAnonymous.

I have made class library for LogonAuthorize and AllowAnonymous. So any consumer should give the reference of dll and add below code in respected global.asax (In pinkcolour).

public class MvcApplication : System.Web.HttpApplication

{

public static void RegisterGlobalFilters(GlobalFilterCollection filters)

{

filters.Add(new HandleErrorAttribute());

filters.Add(new LogonAuthorize());

}

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id}", // URL with parameters

new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

);

}

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);

RegisterRoutes(RouteTable.Routes);

}

}

Now for action method, decorate AllowAnonymous , if we want to give Anonymous access.

[AllowAnonymous]

public ActionResult Register()

{

return View();

}

So now when we run the application, we can call Register action before login.

Even after implementing custom filter, we can decorate action method with [Authorize] and used all the features.

[Authorize(Users = "ABCXYZ")]

public ActionResult About()

{

return View();

}

 

This blog is for information purpose only. Please contact for any conflict.

Windows Azure

What is Azure platform?

The Windows Azure platform is an internet-scale cloud computing services platform hosted in Microsoft data centers. The Windows Azure platform, which provides a range of functionality to build applications that span from consumer Web to enterprise scenarios, includes a cloud services operating system and a set of developer services. Windows Azure, Microsoft SQL Azure and AppFabric are the key components of the Windows Azure platform.

 

What is Windows Azure?

Windows Azure provides developers with on-demand compute and storage to host, scale and manage Web applications on the Internet through Microsoft data centers.

 

What is Microsoft Sql Azure?

Microsoft SQL Azure delivers on Microsoft’s SQL Server® Data Platform vision of extending the Data Platform capabilities in cloud as web-based services. SQL Azure enables a rich set of services for relational database, reporting; and analytics and data synchronization with mobile users, remote offices and business partners

What is AppFabric Service bus and Access Control?

The Service Bus enables loosely-coupled connectivity between services and applications across firewall or network boundaries, using a variety of communication patterns. The Access Control Service provides federated, claims-based access control for REST web services. Developers can use these services to build distributed or composite applications and services.

Compute Instance

Windows Azure compute instances come in four unique sizes to enable complex applications and workloads.

Compute Instance Size

CPU

Memory

Instance Storage

I/O Performance

Small

1.6 GHz

1.75 GB

225 GB

Moderate

Medium

2 x 1.6 GHz

3.5 GB

490 GB

High

Large

4 x 1.6 GHz

7 GB

1,000 GB

High

Extra large

8 x 1.6 GHz

14 GB

2,040 GB

High

 

Each Windows Azure compute instance represents a virtual server

 

Pricing for Azure

Monthly usage exceeding the amount included in the Base Units purchased will be charged at the standard rates:

Windows Azure

·         Compute

§  Small instance (default): $0.12 per hour

§  Medium instance: $0.24 per hour

§  Large instance: $0.48 per hour

§  Extra large instance: $0.96 per hour

·         Storage

§  $0.15 per GB stored per month

§  $0.01 per 10,000 storage transactions

·         Content Delivery Network (CDN) (Content Delivery Network (CDN) – Windows Azure CDN data transfer charges are based on the data center location from where the traffic was served, not based on the end user’s location)

§  $0.15 per GB for data transfers from European and North American locations*

§  $0.20 per GB for data transfers from other locations*

§  $0.01 per 10,000 transactions*

SQL Azure

·         Web Edition

§  $9.99 per database up to 1GB per month

§  $49.95 per database up to 5GB per month**

·         Business Edition

§  $99.99 per database up to 10GB per month**

§  $199.98 per database up to 20GB per month**

§  $299.97 per database up to 30GB per month**

§  $399.96 per database up to 40GB per month**

§  $499.95 per database up to 50GB per month**

AppFabric

·         Access Control (provides the ability to create rules and claims for authentication and authorization)

§  $1.99 per 100,000 transactions

·         Service Bus (Expose apps and services)

§  $3.99 per connection on a “pay-as-you-go” basis

§  Pack of 5 connections $9.95

§  Pack of 25 connections $49.75

§  Pack of 100 connections $199.00

§  Pack of 500 connections $995.00

Data Transfers

·         North America and Europe regions

§  $0.10 per GB in

§  $0.15 per GB out

·         Asia Pacific Region

§  $0.30 per GB in

§  $0.45 per GB out

·         Inbound data transfers during off-peak times through October 31, 2010 are at no charge. Prices revert to our normal inbound data transfer rates after October 31, 2010.

 

 

Measuring Windows Azure Consumption

·         Compute time, measured in service hours: Windows Azure compute hours are charged only for when your application is deployed. When developing and testing your application, developers will want to remove the compute instances that are not being used to minimize compute hour billing. Partial compute hours are billed as full hours.

·         Storage, measured in GB: Storage is metered in units of average daily amount of data stored (in GB) over a monthly period. For example, if a user uploaded 30GB of data and stored it on Windows Azure for a day, her monthly billed storage would be 1 GB. If the same user uploaded 30GB of data and stored it on Windows Azure for an entire billing period, her monthly billed storage would be 30GB. Storage is also metered in terms of storage transactions used to add, update, read and delete storage data. These are billed at a rate of $0.01 for 10,000 (10k) transaction requests

·         Data transfers measured in GB (transmissions to and from the Windows Azure datacenter): Data transfers are charged based on the total amount of data going in and out of the Azure services via the internet in a given 30-day period. Data transfers within a sub region are free.

·         Transactions, measured as application requests.

 

Calculate connection count for service bus

A “connection” is established whether the service binds to the AppFabric Service Bus, and also when a client(s) bind to the cloud endpoint.  So if I have a development application and press F5 in Visual Studio, when my service and client bind to the cloud that counts as 2 “connections.”

Pay for the maximum number of Connections that were in simultaneous use on any given day during the billing period.

For example, a given client application may open and close a single Connection many times during a day; this is especially likely if an HTTP binding is used. To the target system, this might appear to be separate, discrete Connections, however to the customer this is a single intermittent Connection. Charging based on simultaneous Connection usage ensures that a customer would not be billed multiple times for a single intermittent Connection

 

 

References

http://en.wikipedia.org/wiki/Cloud_computing

http://www.microsoft.com/windowsazure/pricing/

http://seroter.wordpress.com/2010/04/14/how-do-you-figure-out-the-cost-of-using-the-azure-appfabric-service-bus/

http://www.microsoft.com/windowsazure/faq/

Simple example for how to host or deploy the Web Site.

Now with the help of WebDeploymentSetup provided by Microsoft, web deployment is very easy.

You can download it from following path.

http://www.microsoft.com/downloads/details.aspx?familyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&displaylang=en

Install the WebDeploymentSetup.msi. Now follow the following steps.

  1. First Create one Web Site. (Not a Web Application)
  2. Right click on Web Site. You will get “Add Web Deployment Project” tab, click on it.
    image
  3. Click on “Add Web Deployment Project”, it will create one more project in solution.
    image image

4.  Now build the WebSite2_deploy project.

5. Now Click on solution and select the WEB Deployment Project.

image

6. You will get following screen.

image

7. Right click on “Web Application Folder” and click on “Add” and Select “Prolect Output” tab.

image

8. Once we click on “Project Output”. Following window prompt. Select our WebSite2_deploy project (Which we have created using WebDeploymentSetup.msi)

9. Now build the project and check that in folder. Now .msi file will be there. Click on .msi file.

10 Now it will ask for the Virtual directory , in IIS.  If you have server, you can even create the site and give the Virtual directory. In client computer, allow only to create virtual directory.

image

11 Select the appropriate virtual directory and finish the installation.

12. Now if you check in IIS, you will get the “websetup1_man_deploy” virtual directory.

 

This is the easiest way to host web site into IIS using .msi…..  

Useful Commands for Remote Server

Sometimes you have urgency to access the server but server’s logging capacity is over. It means once any existing session log off, new user can enter.

1. To know how many session’s are active in the remote server.
  c:/> qwinsta /server:<<Server Name / IP address>>

Once you know the session, kill the session or logoff the remote computer.

using following command, we can kill the session

c:/> rwinsta {sessionname | sessionid} /SERVER:servername

using following command, we can logoff the remote machine.

C:\>logoff /server:<<ServerName>> 1 /v
Logging off session ID 1

2. Forcefully logging into the remote computer
   c:/> mstsc -v:<<ServerName>> /F –console

3.  Check for a list of running sessions by typing the following only on the server. we can call this Query where the Terminal services are available ;
  c:/> QUERY USER /SERVER:servername

4. This will list all current session on that server. Record the session ID for the session you want to kill.  Then
  c:/> RESET SESSION sessionID /SERVER:servername

For more reference read the following blog. http://ts.veranoest.net/ts_faq_administration.htm

SSRS : First simple example : How to use Sql Server Reporting Service and How to display report into Windows Application

Create the Report

1. Create new Project of Business Intelligence Projects –> Report Server Project

image

2. After that, click on Solution Explore, right click on “Shared Data Source” and create Data Source for the report.

image

3. Once Data Source is created, Again right click and Add the report. This is first time so I can explain using Wizard.

4. During the wizard, give the query so it will create “Data Set” for the report.

5. After finishing the wizard, now we can see the report on screen, click on “Preview”. if table has data , it will display.

 

image

Now this is the way to create simple report. The challenge is to set the “Reporting Server” and host the report to the server and run the report on the Windows / Web application.

Now I’ll explain how to set the “Reporting Services”

Configure the Reporting Server

1. Open All Programs –> Microsoft SQL 2008 –> Configuration Tool –> Reporting Service Confige  Manager

you will get following screen

image

2. Above is the Configuration tool to set the “Reporting Services”

If we click on “Web Service URL” tab, we will get the WEB url to access our server.

Now we have set the server. Now we will deploy our report to the server.

Deploy Report into the Reporting Server 

1. Go back to our solution which we have created.

2. Right Click to solution and click on Property. We have to set “TargetServerURL” property to our server. (URL of our reporting server)

2. Right click on solution and click on Deploy tab.

image

3. check on URL, now we will get one report hosted.

Now we have finished the hosting of report into the server.

Only one part is remaining and that is to display report into the WEB/WINDOWS application.

Display report into the WEB/WINDOWS application

1. Create the Windows Application and dreg MicrosoftReportViewer form the tool box.

2. Right click on the MicrosoftReportViewer and select the Property.

3. We have to set 2 property to get the report which is hosted in our “Reporting Server”.

ReportPath :- Path of the report into the report server

ReportServerURL : The URL of our “reporting Server”

image

Run the windows application, it will connect the server which we mention in “ReportServerURL “ property and execute the report which we mention in “ReportPath “ property.

image

I hope , this article may useful for the new person who wants to start SSRS.

Tips for SQL

How to find the lock table in sql 2008?

Select  
    object_name(P.object_id) as TableName, 
    resource_type, resource_description
from
    sys.dm_tran_locks L
    join sys.partitions P on L.resource_associated_entity_id = p.hobt_id

 

Other way to get the lock object

select * from sys.objects where name =’<<Table Name >>’

–You will get object id for table(2081546599

sp_lock  — it gives number of records, find out the exact number  ex. 2081546599 from the records and kill them following way

kill 53

kill 71

How to use the Link server using query?

 

Linq to XML

Generally I don’t like to do XML programming due to all the XPath and etc….

But now due to LINQ to XML , it is very easy and interesting…

 

Suppose you have following XML. Now we can create xml using XElement (System.Xml.Linq;)object. Following is the code to create the XML..

This is the simplest from just for understanding ..

Code Snippet
  1. XElement con = new XElement(“Contracts”,
  2.                                     new XElement(“Contact”, new XAttribute(“IsPermmenet”, “True”),
  3.                                         new XElement(“Office”, new XElement(“Add1″, “Simanhar”), new XElement(“City”, “Ahd”)),new XElement(“Home”,new XElement(“Add1″,“ssss”),new XElement(“City”,“AHD”))),
  4.                                     new XElement(“Contact”, new XAttribute(“IsPermmenet”, “false”),
  5.                                         new XElement(“Office”, new XElement(“Add1″, “JayNagar”), new XElement(“City”, “BNG”)),new XElement(“Home”,new XElement(“Add1″,“pppp”),new XElement(“City”,“BNG”))));

 

<Contracts>
  <Contact IsPermanent="True">
    <Office>
      <Add1>Simanhar</Add1>
      <City>Ahd</City>
    </Office>
    <Home>
      <Add1>ssss</Add1>
      <City>AHD</City>
    </Home>
  </Contact>
  <Contact IsPermanent="false">
    <Office>
      <Add1>JayNagar</Add1>
      <City>BNG</City>
    </Office>
    <Home>
      <Add1>pppp</Add1>
      <City>BNG</City>
    </Home>
  </Contact>
</Contracts>

Now we can write the LINQ for above xml.

Code Snippet
  1. XElement con = new XElement(“Contracts”,
  2.                                     new XElement(“Contact”, new XAttribute(“IsPermmenet”, “True”),
  3.                                         new XElement(“Office”, new XElement(“Add1″, “Simanhar”), new XElement(“City”, “Ahd”)),new XElement(“Home”,new XElement(“Add1″,“ssss”),new XElement(“City”,“AHD”))),
  4.                                     new XElement(“Contact”, new XAttribute(“IsPermmenet”, “false”),
  5.                                         new XElement(“Office”, new XElement(“Add1″, “JayNagar”), new XElement(“City”, “BNG”)),new XElement(“Home”,new XElement(“Add1″,“pppp”),new XElement(“City”,“BNG”))));
  6.             Console.WriteLine(con.ToString());
  7.             var cons = con.DescendantsAndSelf(“Contact”);
  8.             var con_one = from c in cons
  9.                           where c.Element(“Office”).Element(“City”).Value == “Ahd”
  10.                           let address1 = c.Element(“Office”).Element(“Add1″)
  11.                           let city = c.Element(“Office”).Element(“City”)
  12.                           select new
  13.                           {
  14.                               AddressForOffice = address1.Value.ToUpper(),
  15.                               CityForOffice = city.Value.ToUpper()
  16.                               
  17.                           };
  18.             Console.WriteLine(con_one.ToString());

If you observed above code, after creating the xml, I have used DescendentaAndSelf method of XElement to create the List of Contact. LINQ will work with collection only so I have to convert XElement into List<XElement>.

 

I have used ‘let’ keyword in between the query. ‘let’ keyword will create the local variable and store the information for the query.

If you observed, I have taken the variable address1 and city and store the value of element which office’s city is “Ahd”.

I have used both the variable when query is creating the output using select new command.

select new
                          {
                              AddressForOffice = address1.Value.ToUpper(),
                              CityForOffice = city.Value.ToUpper()
                          };

So this way we can store the value in between of linq query and after that we can apply some function (here ToUPPER()) and create the new object.

MessageInspector – WCF

Actually I got one assignment from current job that when client call the service, I want to add some object that I can use at service side.

 

So basically, I want to try to display the SOAP message sent to the service host. In order to do this, you might want to pay attention to 3 things:

· System.ServiceModel.Configuration.BehaviorExtensionElement

· System.ServiceModel.Description.IEndpointBehavior

· System.ServiceModel.Dispatcher.IClientMessageInspector

 

You can fine code here : http://cid-39f476822b8257be.skydrive.live.com/self.aspx/.Public/WCF^_Demo/MitWCFDay1.zip

Here is the service…

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceModel;
  6. using MitWCFDay2;
  7. namespace MitWCFDay1
  8. {
  9.     [ServiceContract]
  10.     [MyMessageInspector]
  11.     public interface ICalcMath
  12.     {
  13.         [OperationContract]
  14.         int AddNumber(int i, int j);
  15.     }
  16.     public class CalcMath : ICalcMath
  17.     {
  18.         #region ICalcMath Members
  19.         public int AddNumber(int i, int j)
  20.         {
  21.             return i + j;
  22.         }
  23.         #endregion
  24.     }
  25. }

If you observe carefully then one  MyMessageInspector attribute is define to service. I’ll explain that later.

 

Now We have to create MyMessageInspector class  and code is following…

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceModel.Channels;
  6. using System.ServiceModel;
  7. using System.ServiceModel.Description;
  8. using System.ServiceModel.Dispatcher;
  9. using System.ServiceModel.Configuration;
  10. namespace MitWCFDay1
  11. {
  12.     class MyMessageInspector : Attribute, IClientMessageInspector, System.ServiceModel.Description.IEndpointBehavior
  13.     {
  14.         #region IClientMessageInspector Members
  15.         public void AfterReceiveReply(ref Message reply, object correlationState)
  16.         {   // Ignore
  17.         }
  18.         public object BeforeSendRequest(ref Message request, IClientChannel channel)
  19.         {
  20.             Console.WriteLine(request.ToString());
  21.            
  22.             return null;
  23.         }
  24.         #endregion
  25.          #region IEndpointBehavior Members
  26.         public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
  27.         { // Ignore
  28.         }
  29.         public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  30.         {
  31.             clientRuntime.MessageInspectors.Add(new MyMessageInspector());
  32.         }
  33.         public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
  34.         { // Ignore
  35.         }
  36.         public void Validate(ServiceEndpoint endpoint)
  37.         { // Ignore
  38.         }
  39.         #endregion
  40.     }
  41.     
  42.     
  43.     public class CustomBehaviorSection : BehaviorExtensionElement
  44.     {
  45.         public override Type BehaviorType
  46.         {
  47.             get { return typeof(MyMessageInspector); }
  48.         }
  49.         protected override object CreateBehavior()
  50.         {
  51.             return new MyMessageInspector();
  52.         }
  53.         
  54.         
  55.     }
  56.     public class Information
  57.     {
  58.         public static Information CurrentInformation { get; set; }
  59.         public string ComputerName { get; set; }
  60.         public string UserName { get; set; }
  61.         public Information(string computerName,string userName)
  62.         {
  63.             if (CurrentInformation == null)
  64.             {
  65.                 this.ComputerName = computerName;
  66.                 this.UserName = userName;
  67.                 CurrentInformation = this;
  68.             }
  69.             else
  70.                 CurrentInformation = this;
  71.             
  72.         }
  73.     }
  74. }

Here MessageInspector class is responsible to set whatever client want to set.  There is other class call CustomBehaviorSection and it is derived from BehaviorExtensionElement. We have to give this BehaviorExtensionElement into app.config file.

Code Snippet
  1. <?xml version=1.0 encoding=utf-8 ?>
  2. <configuration>
  3.   
  4.   <system.serviceModel>
  5.     <services>
  6.       <service name=MitWCFDay1.CalcMath behaviorConfiguration=ForAuthorazation>
  7.         <endpoint address=net.tcp://localhost:56/MyMathService binding=netTcpBinding contract=MitWCFDay1.ICalcMath bindingConfiguration=ForSecurity name=Binding1 />
  8.         <endpoint address=http://localhost:560/MyMathService binding=basicHttpBinding contract=MitWCFDay1.ICalcMath name=Binding2“  />
  9.         <host>
  10.           <baseAddresses>
  11.             <add baseAddress=net.tcp://localhost:56/MyMathService/>
  12.           </baseAddresses>
  13.         </host>
  14.         
  15.       </service>
  16.       
  17.       
  18.     </services>
  19.     <client>
  20.       <endpoint address=net.tcp://localhost:56/MyMathService binding=netTcpBinding contract=MitWCFDay1.ICalcMath name=Binding1 behaviorConfiguration =aa />
  21.       <endpoint address=http://localhost:560/MyMathService binding=basicHttpBinding contract=MitWCFDay1.ICalcMath name=Binding2 behaviorConfiguration=aa />
  22.     </client>
  23.     <behaviors>
  24.       
  25.       <serviceBehaviors>
  26.         <behavior  name=ForAuthorazation>
  27.           <serviceAuthorization serviceAuthorizationManagerType=MitWCFDay1.CalcAutoMng,MitWCFDay1 />
  28.         
  29.         </behavior>
  30.       </serviceBehaviors>
  31.       <endpointBehaviors >
  32.         <behavior name=aa>
  33.           <CustomBehaviorSection />
  34.         </behavior>
  35.       </endpointBehaviors>
  36.     </behaviors>
  37.     <extensions>
  38.       <behaviorExtensions>
  39.         <add name=CustomBehaviorSection type=MitWCFDay1.CustomBehaviorSection, MitWCFDay1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null“  />
  40.       </behaviorExtensions>
  41.     </extensions>
  42.     
  43.     
  44.     
  45.     <bindings>
  46.       <netTcpBinding>
  47.         <binding name=ForSecurity>
  48.           <security mode=Transport>
  49.             
  50.             <transport clientCredentialType=Windows/>
  51.             
  52.           </security>
  53.         </binding>
  54.         
  55.       </netTcpBinding>
  56.       
  57.     </bindings>
  58.     
  59.     
  60.   </system.serviceModel>
  61. </configuration>

First we have created behaviorExtensions and after we have define that into endpointBehaviors.

now if you put break point on MessageInspector , before calling the service it will call the methods of MessageInspector  class.

Don’t forget to add the attribute on service.. other wise throw the error…

How to host service as a Windows Services

We can host services three ways…

1. Self Host

2. IIS

3. Window Service

 

This article is for Hosing service as a Windows Services.

I have following services..

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceModel;
  6. namespace CalcService
  7. {
  8.    [ServiceContract]
  9.     public interface ICalc
  10.     {
  11.        [OperationContract]
  12.        int GetSum(int i, int j);
  13.     }
  14.    public class CalcServices : ICalc
  15.    {
  16.        #region ICalc Members
  17.        public int GetSum(int i, int j)
  18.        {
  19.            return i + j;
  20.        }
  21.        #endregion
  22.    }
  23. }

 

Following is the App.config.

 

Code Snippet
  1. <?xml version=1.0 encoding=utf-8 ?>
  2. <configuration>
  3.   <system.serviceModel>
  4.     <services>
  5.       <service name=CalcService.CalcServices>
  6.         <endpoint address=“” binding=basicHttpBinding contract=CalcService.ICalc/>
  7.         <host>
  8.           <baseAddresses>
  9.             <add baseAddress=http://localhost:1234/CalcServices/>
  10.           </baseAddresses>
  11.         </host>
  12.         
  13.         
  14.       </service>
  15.       
  16.     </services>
  17.     
  18.     
  19.     
  20.   </system.serviceModel>  
  21. </configuration>

Now Add two files in the solution.

1. Windows Service and

2. Installer Class

Write down following code into Service1 (Windows Service class) class..

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.ServiceProcess;
  8. using System.Text;
  9. using System.ServiceModel;
  10. namespace CalcService
  11. {
  12.     partial class Service1 : ServiceBase
  13.     {
  14.         public Service1()
  15.         {
  16.             InitializeComponent();
  17.         }
  18.         ServiceHost sn;
  19.         protected override void OnStart(string[] args)
  20.         {
  21.             sn = new ServiceHost(typeof(CalcService.CalcServices), new Uri[] { });
  22.             sn.Open();
  23.         }
  24.         protected override void OnStop()
  25.         {
  26.             sn.Close();
  27.         }
  28.     }
  29. }

Write down following code into Installer1

Code Snippet
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Configuration.Install;
  6. using System.Linq;
  7. using System.ServiceProcess;
  8. namespace CalcService
  9. {
  10.     [RunInstaller(true)]
  11.     public partial class Installer1 : Installer
  12.     {
  13.         public Installer1()
  14.         {
  15.             InitializeComponent();
  16.             ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
  17.             ServiceInstaller serviceInstaller = new ServiceInstaller();
  18.             processInstaller.Account = ServiceAccount.LocalSystem;
  19.             serviceInstaller.DisplayName = “Service1″;
  20.             serviceInstaller.Description = “CalcService.”;
  21.             serviceInstaller.ServiceName = “Service1″;
  22.             serviceInstaller.StartType = ServiceStartMode.Manual;
  23.             Installers.Add(processInstaller);
  24.             Installers.Add(serviceInstaller);
  25.         }
  26.     }
  27. }

Now we have written both the service and Installer. Now we have to write code for start up means some ware I’ve to call ..

I’ve written in main program

 

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceProcess;
  6. namespace CalcService
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             ServiceBase[] ServicesToRun;
  13.             ServicesToRun = new ServiceBase[] { new Service1() };
  14.             ServiceBase.Run(ServicesToRun);
  15.         }
  16.     }
  17. }

 

Now we have done everything. Final step is after compiling the solution, we have to install through command prompt.

 

c:> Installutil –i c:…..DebugCaleService.exe

 

Now if you check in service.msi, you can get the service.

Hope this is useful …:)

WCF – FactoryChannel

We can call service by using two way

1. Create a proxy in client place

2. Create ChannelFactory and directly call the service (without Proxy)

 

I’m going to discuss both in this article.

For both the approach , we require the service… Following is the service code.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.ServiceModel;
  6. namespace WcfPlay1
  7. {
  8.     [ServiceContract]
  9.     public interface ICalcService
  10.     {
  11.         [OperationContract]
  12.         int Add(int i, int j);
  13.     }
  14.     public class CalcService : ICalcService
  15.     {
  16.         #region ICalcService Members
  17.         public int Add(int i, int j)
  18.         {
  19.             return i + j;
  20.         }
  21.         #endregion
  22.     }
  23. }

 

Now we have to host the service. Following is the Config file

Code Snippet
  1. <?xml version=1.0 encoding=utf-8 ?>
  2. <configuration>
  3.   <system.serviceModel>
  4.     <services>
  5.       <service name=WcfPlay1.CalcService behaviorConfiguration=svcBehavior>
  6.         <endpoint address=“” binding=netTcpBinding contract=WcfPlay1.ICalcService bindingConfiguration=MyBinding></endpoint>
  7.         <host>
  8.           <baseAddresses>
  9.             <add baseAddress=net.tcp://localhost:100/CalcService/>
  10.           </baseAddresses>
  11.         </host>
  12.       
  13.       
  14.       </service>
  15.       
  16.     </services>
  17.     <behaviors>
  18.       <serviceBehaviors>
  19.         <behavior name=svcBehavior>
  20.           <serviceAuthorization serviceAuthorizationManagerType=WcfPlay1.CalcServiceAuthMgr,WcfPlay1 />
  21.         </behavior>
  22.       </serviceBehaviors>
  23.     </behaviors>
  24.     <client>
  25.       <endpoint address=net.tcp://localhost:100/CalcService binding=netTcpBinding contract=WcfPlay1.ICalcService bindingConfiguration=MyBinding />
  26.     </client>
  27.     <bindings>
  28.       <netTcpBinding>
  29.         <binding name=MyBinding>
  30.           <security mode=Transport>
  31.             <transport clientCredentialType=Windows />
  32.           </security>
  33.         </binding>
  34.       </netTcpBinding>
  35.     </bindings>
  36.   </system.serviceModel>
  37. </configuration>

 

following is the hosing code… you can write in any function like Button click etc…

I’ve written in console application, so if i run the application, my services are up.

Code Snippet
  1. ServiceHost host = new ServiceHost(typeof(CalcService), new Uri[] { });
  2.             host.Open();
  3.             Console.WriteLine(“Hosted”);

 

Now we have everything. Now we can call this service.

Now I’m create proxy call to call my service. Following is the code to create proxy class. After we create proxy class, user can create the object of that and call the actual services.

Code Snippet
  1. class CalcServiceClient : ClientBase<ICalcService>, ICalcService
  2.     {
  3.         #region ICalcService Members
  4.      
  5.         public int Add(int i, int j)
  6.         {
  7.             return base.Channel.Add(i, j);
  8.         }
  9.         #endregion
  10.     }

Now proxy is ready. We can call the service following way…

 

Code Snippet
  1. CalcServiceClient client = new CalcServiceClient();
  2.             int res = 0;
  3.             try
  4.             {
  5.                 res = client.Add(10, 5);
  6.             }
  7.             catch (Exception ex)
  8.             {
  9.                 Console.WriteLine(ex.ToString());
  10.             }
  11.             Console.WriteLine(res.ToString());
  12.             Console.ReadLine();

Now I’m going to call my service directly means not creating the proxy class..

Following is the code….

 

Code Snippet
  1. private static void CallServiceChannelFactory()
  2.         {
  3.             NetTcpBinding netTcpBinding = new NetTcpBinding();
  4.             EndpointAddress address = new EndpointAddress(“net.tcp://localhost:100/CalcService”);
  5.             ChannelFactory<ICalcService> myChannelFactory = new ChannelFactory<ICalcService>(netTcpBinding, address);
  6.             ICalcService WcfClient = myChannelFactory.CreateChannel();
  7.             int j = WcfClient.Add(10, 40);
  8.             Console.WriteLine(“For Channel”);
  9.             Console.WriteLine(j.ToString());
  10.         }

Now i think you are clear how to access the services…

Follow

Get every new post delivered to your Inbox.