Developing Async apps using WCF and MSMQ -- Part 1

by Hari Mukkapati 30. June 2009 17:38

Software Requirements

  • Visual Studio 2008  (Also works in 2005, but not tested for this tutorial.)
  • MSMQ Installed and Running.  To Implement Security MSMQ installation must be integrated to AD.
  • .NET 3.0 Framework or higher
  • IIS
  • Distributed Transaction Coordinator (DTC) Must be installed and running.

The Goal here is to setup an asynchronous communication between a client and server using WCF and MSMQ.  To do that I use a “WCFQ” solution which contains 3 projects.

The Goal here is to setup an asynchronous communication between a client and server using WCF and MSMQ.  To do that I use a “WCFQ” solution which contains 3 projects. 

  • WCFQ.Service – Hosts Queued WCF Service.
  • WCFQ.Contract – Contains the Data and Service contracts for the Queued WCF Service.
  • WCFQ.Client – A Console application to call WCFQ.Service

 

Step 1:  Open Visual Studio 2008 IDE and Create a “WCF Service Application”

 

image001 

 

 

Step 2: Add another “Class Library” Project and Delete “Class1.cs” from the project.

 

Step 3: Delete IService1.cs in WCFQ.Service and add IService1.cs to WCFQ.Contract and replace the code with below.  The trick here is when building WCF-MSMQ services is to ensure that all the operation contracts are defined with IsOneWay=true.

using System; 
using System.Runtime.Serialization; 
using System.ServiceModel; 

namespace WCFQ.Contract 
{ 
    [ServiceContract] 
    public interface IService1 
    { 
        [OperationContract(IsOneWay=true)] 
        void SendData(QData composite); 
    } 

    //An object for Data Contract 
    [DataContract] 
    public class QData 
    { 
        [DataMember] 
        public string Name { get; set; } 
    } 
}
 

Step 4: Add references of “System.ServiceModel” and “System.Runtime.Serialization” to WCFQ.Contract. This is where you define the contract.

Step 5: Reference WCFQ.Contract project in WCFQ.Service and change the Service1.svc.cs code should look like this.

using System; 
using System.Diagnostics; 
using WCFQ.Contract; 
namespace WCFQ.Service 
{ 
    public class Service1 : IService1 
    { 
        public void SendData(QData qdata) 
        { 
            //Do something with the data 
            Trace.WriteLine(String.Format("Name : {0}", qdata.Name)); 
        } 
    } 
}

Step 6: Now, The configuration comes into picture. Here is how the ServiceModel part of web.config should look like. We don’t need wsHttpBinding to get net MSMQ to be working.  That is default and I left it that way to make it easy to understand the WCF Service is working.

<SYSTEM.SERVICEMODEL>
    <BINDINGS>
        <NETMSMQBINDING>
            <BINDING name="WCFQNonTransactional" exactlyonce="false">
                <SECURITY mode="None" />
            </BINDING>
        </NETMSMQBINDING>
    </BINDINGS>
    <SERVICES>
        <SERVICE name="WCFQ.Service.Service1" behaviorconfiguration="WCFQ.Service.Service1Behavior">
            <ENDPOINT contract="WCFQ.Contract.IService1" binding="wsHttpBinding" address="http://localhost/WCFQService/Service1.svc">
                <IDENTITY>
                    <DNS value="localhost" />
                </IDENTITY>
            </ENDPOINT>
            <ENDPOINT contract="WCFQ.Contract.IService1" binding="netMsmqBinding" address="net.msmq://localhost/private/WCFQService/Service1.svc" bindingconfiguration="WCFQNonTransactional" />
        </SERVICE>
    </SERVICES>
    <BEHAVIORS>
        <SERVICEBEHAVIORS>
            <BEHAVIOR name="WCFQ.Service.Service1Behavior">
                <SERVICEMETADATA httpgetenabled="true" />
                <SERVICEDEBUG includeexceptiondetailinfaults="false" />
            </BEHAVIOR>
        </SERVICEBEHAVIORS>
    </BEHAVIORS>
</SYSTEM.SERVICEMODEL>

Step 7:  The WCF service to work with MSMQ there is one more rule. That is the queue name which must be same as the URI that is used to Access the WCF Service. So, if the URL is http://localhost/WCFQService/Service1.svc, then the Queue Name will be “WCFQService/Service1.svc”. This has to be created manually by going to “Computer Management/Services and Applications/Message Queuing/Private Queues”.  When creating the Queue, Do not check “Transactional”. Computer Management can be accessed from Right click on My Computer and click on Manage or “Start -> Run” and typing “Compmgmt.msc” and Hit enter.

 image002 

Step 8: After creating the queue, enable Journal by Right click and select properties on the queue. Check the Enabled checkbox inside Journal Area. This is just for tracking purpose that your messages reached MSMQ. Next go to security tab of the properties and Add user “Network Service” and give full control to the user. This is the user who writes and reads out messages from the queue.

 

image003 

 

image004 

Step 9: Configure the WCFQ.Service to Run in IIS by setting the project properties. Remove the DOT from the WCFQ.Service and Create virtual directory. [Note: Windows 7 or Windows 2008 server must create an application pool which runs with “Network service” User, instead of “ApplicationPoolIdentity” and assign the application pool create to the WCFQService from IIS, INetMgr]

 

 image005

 

Step 10:  In order to make the WCF to work with MSMQ we need to enable MSMQ WAS listener on the WCFQService application that is just created by running following command from command prompt from location C:\Windows\System32\inetsrv.

appcmd set app "Default web site/WCFQService" /enabledProtocols:net.msmq,http

 

 image006

 

This enables the net.msmq protocol on WCFQService application on IIS.

Step 11: Now, The WCFQService application is ready to roll. So, let’s get to the client. Add a Console Application to the project.  And add references for WCFQ.Contract project, System.ServiceModel.

Step 12: Without having to create a proxy and access the WCF service, Add a new class called “WCFQService1Client.cs”. The proxy class derives from the class ClientBase<T>. ClientBase<T> accepts a single generic type parameter identifying the service contract that this proxy encapsulates. The Channel property of ClientBase<T> is of the type of that type parameter. The generated subclass of ClientBase<T> simply delegates to Channel the method call.

using System; 
using System.ServiceModel; 
using WCFQ.Contract; 

namespace WCFQ.Client 
{ 
    internal class WCFQService1Client : ClientBase, IService1 
    { 
        public WCFQService1Client(string endpoint) : base(endpoint) 
        { 

        } 

        //IService1 Members 
        public void SendData(QData data) 
        { 
            Channel.SendData(data); 
        } 
    } 
}

Step 13: Now configure the Client app.config to access the WCF Service.

<?xml version="1.0" encoding="utf-8"?>
<CONFIGURATION>
    <SYSTEM.SERVICEMODEL>
        <BINDINGS>
            <NETMSMQBINDING>
                <BINDING name="WCFQNonTransactional" exactlyonce="false">
                    <SECURITY mode="None" />
                </BINDING>
            </NETMSMQBINDING>
            <WSHTTPBINDING>
                <BINDING name="WCFQwsHttp">
                    <SECURITY mode="None" />
                </BINDING>
            </WSHTTPBINDING>
        </BINDINGS>
        <CLIENT>
            <ENDPOINT name="WCFQNonTransactional" contract="WCFQ.Contract.IService1" binding="netMsmqBinding" address="net.msmq://localhost/private/WCFQService/Service1.svc" bindingconfiguration="WCFQNonTransactional" />
            <ENDPOINT name="WCFQwsHttp" contract="WCFQ.Contract.IService1" binding="wsHttpBinding" address="http://localhost/WCFQService/Service1.svc" bindingconfiguration="WCFQwsHttp" />
        </CLIENT>
    </SYSTEM.SERVICEMODEL>
</CONFIGURATION>

 

Step 13: To use the proxy, the client first needs to instantiate a proxy object and provide the constructor with endpoint information from the endpoint section name from the config file. The client can then use the proxy methods to call the service, and when the client is done, the client needs to close the proxy instance. The program.cs will look like this after implementing the code.

using System; 
using WCFQ.Contract; 

namespace WCFQ.Client 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            QData data = new QData(); 
            data.Message = "Hello World!";            

            //Send Message 
            using (WCFQService1Client proxy = new WCFQService1Client("WCFQNonTransactional")) 
            { 
                Console.WriteLine("Sending Message {0} ", data.Message); 
                proxy.SendData(data); 

                //Close the client. 
                proxy.Close(); 

            }//Dispose 
            
            Console.Read(); 
        } 
    } 
}

Step 14: Set WCFQ.Client as the startup project and run……. Here is what needs to be observed to make sure the service and client ran fine.

Command window of client will show

image007 

MSMQ Window will show the journal message count increased by 1.

image008


    Next time I will post on working with transactional messaging.

Click hear to Download source code here…

Tags: , , , ,

Windows Live Sync : Keep it all in sync!!!

by Hari Mukkapati 26. June 2009 04:45
 
Sync your files between computers so you always have the latest copy.

Download Live Sync Below :
For Windows :
Version: 14.0.8064.0206
Requires: Microsoft Windows XP SP2 or later, Microsoft Windows 2003 SP2 or later, Windows Server 2008 or Windows Vista (Windows XP Professional x64 Edition is not supported)
For Mac :
Version: 14.0.6067.1212
Requires: OSX 10.5 or later
Need More information for Sync :
More info can be found directly at :
       
 

Tags: , , , ,

Internet Tools | Tools

Problem SSIS Package Scheduling

by Hari Mukkapati 26. June 2009 04:45

 

While scheduling the SSIS package some of you already might have seen the following problem.

Unable to cast object of type 'Microsoft.SqlServer.Management.Smo.SimpleObjectKey' to type 'Microsoft.SqlServer.Management.Smo.Agent.JobObjectKey'. (Microsoft.SqlServer.Smo)

The reason for this problem is that you the SP2 patch is not applied properly. Why I said properly here is because that the SQL Server installed first and then installed SP2. Later you might have decided to install SSIS later in the game. SP2 is missing on the SSIS. This can happen any changes that you make to .Net Framework 2.0 (either uninstall or do some changes to it) to SQL server adding or removing features. So, Patch it up when you see the above problem or some thing like

Unable to cast object of type 'X' to type 'Y'.

Tags: , ,

SQL Server | SSIS | Database

Data Mining Concepts

by Hari Mukkapati 26. June 2009 04:26

Data mining is frequently described as "the process of extracting valid, authentic, and actionable information from large databases." In other words, data mining derives patterns and trends that exist in data. These patterns and trends can be collected together and defined as a mining model. Mining models can be applied to specific business scenarios, such as:

  • Forecasting sales.
  • Targeting mailings toward specific customers.
  • Determining which products are likely to be sold together.
  • Finding sequences in the order that customers add products to a shopping cart.

An important concept is that building a mining model is part of a larger process that includes everything from defining the basic problem that the model will solve, to deploying the model into a working environment. This process can be defined by using the following six basic steps:

Here is the link to the Microsoft web site for

Data mining concepts

Tags: , , ,

Time out issues in cube processing SSAS 2005 Options

by Hari Mukkapati 26. June 2009 04:25
 
Right click on Analysis Services in Management Studio
=> Properties.
=> Show Advanced (all) Properties
=> ExternalCommandTimeout 0
=> ExternalConnectionTimeout 0
 

Tags: , , ,

T-SQL Script for Grant(ing) permissions to all tables in a database to a user

by Hari Mukkapati 26. June 2009 04:22
set nocount on 
declare @object varchar(40) 
declare mycursor scroll cursor 
for 
   select name from sysobjects 
   where type = 'u' 
   order by name 
  
open mycursor 
fetch first from mycursor into @object 

while @@fetch_status <> -1 
begin 
  if @@fetch_status <> -2 
  begin 
     exec('grant SELECT, INSERT, UPDATE, DELETE on '+@object+' to [userid]') 
  end 
  fetch next from mycursor into @object 
end
 
close mycursor 
deallocate mycursor
 
set nocount off
Recently I was working on a database and Had to GRANT Select, Update, Delete, Insert permissions to one user on all  tables in one data base. So, Below script will do the job.
 

Tags: , , ,

Removing windows service from command line

by Hari Mukkapati 26. June 2009 04:20

Removing a windows service from command line using “SC” command line utility.

Here is the syntax and help.

DESCRIPTION:

     SC is a command line program used for communicating with the
     NT Service Controller and services.

USAGE:

sc <server> [command] [service name] <option1> <option2>...
The option <server> has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"
Commands:
query-----------Queries the status for a service, or
enumerates the status for types of services.
queryex---------Queries the extended status for a service, or
enumerates the status for types of services.
start-----------Starts a service.
pause-----------Sends a PAUSE control request to a service.
interrogate-----Sends an INTERROGATE control request to a service.
continue--------Sends a CONTINUE control request to a service.
stop------------Sends a STOP request to a service.
config----------Changes the configuration of a service (persistant).
description-----Changes the description of a service.
failure---------Changes the actions taken by a service upon failure.
qc--------------Queries the configuration information for a service.
qdescription----Queries the description for a service.
qfailure--------Queries the actions taken by a service upon failure.
delete----------Deletes a service (from the registry).
create----------Creates a service. (adds it to the registry).
control---------Sends a control to a service.
sdshow----------Displays a service's security descriptor.
sdset-----------Sets a service's security descriptor.
GetDisplayName--Gets the DisplayName for a service.
GetKeyName------Gets the ServiceKeyName for a service.
EnumDepend------Enumerates Service Dependencies.

The following commands don't require a service name:
sc <server> <command> <option>
boot------------(ok | bad) Indicates whether the last boot should
be saved as the last-known-good boot configuration
Lock------------Locks the Service Database
QueryLock-------Queries the LockStatus for the SCManager Database
EXAMPLE:
   
sc start MyService
The installed services can be found in the registry under
\\HKEY_LOCAL_MACHNINE\SYSTEM\CurrentControlSet\Services

Tags: ,

COM+ application starting and stopping

by Hari Mukkapati 26. June 2009 04:12

COM+ application starting and stopping can be done easily using the COM+ Admin dll.  It can be done using VB or in a script language like VBS (which you can run using WSH).  Here's example code:

On Error Resume Next 
    ' if VB add a reference to COM+ 1.0 Admin Type Library. 
    ' if VBS just declare this object without a type 
    Dim oCatalog As COMAdmin.COMAdminCatalog 
    Dim sName As String 
    Set oCatalog = CreateObject("COMAdmin.COMAdminCatalog") 
  
    sName = "the package name goes here"    
    oCatalog.ShutdownApplication sName 
    
    ' to start the app use this syntax 
    'oCatalog.StartApplication sName 
    
    If Err.Number = 0 Then 
        MsgBox sName & " has been shut down.", vbOKOnly + vbInformation 
    Else 
        Const cMsg = "Error 0x#ERR# trying to shut down #APP#. (#DESC#.)" 
        Dim sMsg 
        sMsg = Replace(cMsg, "#ERR#", Hex(Err.Number), 1, 1) 
        sMsg = Replace(sMsg, "#APP#", sName, 1, 1) 
        sMsg = Replace(sMsg, "#DESC#", Err.Description, 1, 1) 
        MsgBox sMsg, vbOKOnly + vbInformation 
        Err.Clear 
    End If 
    Set oCatalog = Nothing 
del.icio.us Tags: ,,

Tags: , ,

Mukkapati.com

About the author

Hari Mukkapati

Month List

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar