Archive for November, 2008

Windows Communication Foundation (WCF)

Sunday, November 30th, 2008

Windows Communication Foundation (WCF) (code-named “Indigo”) is a set of .NET technologies for building and running connected systems. It is a new breed of communications infrastructure built around the Web services architecture. Windows Communication Foundation, or just WCF, is a programming framework used to build applications that inter-communicate. Here is one sample which demonstrates WCF.

First create a blank solution in Visual Studio .NET 2005. I’ll call it “WSFSample”.

Then add New Project to your solution, language C#, type of project Class Library.
Let’s call this project “ServiceLibrary”. When you do this, Visual Studio cretes new file in your project. By default it is named: Class1.cs. Let’s rename it to MathService.cs. If you renamed the file name, you can see that the class name was renamed too. Add a reference to System.ServiceModel. After that let’s put some code to our class MathService. This is how our class looks like when you put few lines of code there.

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace ServiceLibrary
{
    [ServiceContract]
    public class MathService
    {
        [OperationContract]
        public Int32 AddFunction(Int32 a, Int32 b)
        {
            return a + b;
        }

        [OperationContract]
        public Int32 SquareFunction(Int32 a)
        {
            return a * a;
        }
    }
}

Now we will create Service Hosts. Add new project to your solution. Right click on solution and then select: Solution -> Add New Web Site->WCF Service.
Select WCF service template. For language select C#. Take care where is location of your WCF service because by default it is in your Document and Settings folder. I prefer to hold all project files in the root of my solution file.
I’ll call my WCF service project: “WebServiceHost”.


If you take a look at your new project, you will find a file named “Service.svc”.




add this line to file:

<% @ServiceHost Language=VB Service="ServiceLibrary.MathService" %>

As you can see there is a file named “Service.cs” under App_Code folder. Because we will not use it, you can delete it. Now, please rebuid your application and set WCF service to be Startup Project. Before we test it we need to ad some end points to Web.config and we need to add refernce to the project “ServiceLibrary”. Add this lines to Web.config




  
    
      
        
          
        
      
    
    
      
        
      
    
  

  
    
  


and add Reference in your wcf service project to “ServiceLibrary” project and press “F5″ please. You must have something like this on your screen.



Now we can create some client to consume this web service. Once again we add new project to our solution. This time it will be Windows application, language C# off course. I’ll call it “WindowsClient”.We will add 3 text boxes and one button control to our windows form. As you can imagine 2 text boxes will be for integers “a” and “b” and third text box will be result. Also we need to add “Service Reference” (not web reference as we did with *.asmx) to our wcf service. To do this right click on Windows project we’ve just created and click on “Add Service Reference”.But before that we must know URL of our WCF. We can just start with F5 our application and copy paste address from address bar of Service.svc. In my case it is: http://localhost:1157/WebServiceHost/Service.svc and this address I’ll put for “Service Reference”. Now click to add Service Reference, after you enter Service URI: http://localhost:1157/WebServiceHost/Service.svc
, your service reference name is “localhost” by default. I’ll rename it to “WCFMathService”. If you want your application to be ready for test you must check your app.config file. But Visual Studio set up all for your. Just for remember, you must specify end points element in your App.config too. Here is how it looks like:



    
        
            
                
                    
                    

                        
                    
                
            
        
        
            
        
    

.
Also you must add “System.ServiceModel” reference into your Windows client application.

Here is the code of our form which will call WCF Service when we press button on the form.
Just before I show tou you my code to say how I called controls on form:
button is called: bntCallWebService

2 text boxes txtA and txtB

The third textbox is called” txtResult

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void bntCallWebService_Click(object sender, EventArgs e)
        {
            using( WCFMathService.MathServiceClient ws = new WCFMathService.MathServiceClient())
            {
                txtResult.Text = ws.AddFunction(Convert.ToInt32(txtA.Text), Convert.ToInt32(txtB.Text)).ToString();
            }
        }
    }
}


Before I finish I want to tell you to pay attention to this class: WCFMathService


And before we test this we must be carefull because our application will not work if WCF is not started. One way to do this is following: you must specify multiple startup projects: like this:



Just for case rebuild your solution and press “F5″.
Here is what I got!




heappy programming :)

Windows Workflow Foundation (WWF)

Sunday, November 30th, 2008

WWF is a tool for building workflow enabled applications on windows. To do this you will need namespace in Microsoft .NET Framework which is called System.Workflow.
WWF provides a flexible flow model for various types of workflow:

  • Sequential workflow in which one task is executed after another
  • State machine workflow in which external events drive the flow
  • Rule-driven workflow in which a set of rules in combination with the state of data drive the order of processing.
  • To use workflow in your .NET application you need extension for Visual Studio 2005.
    Visual Studio 2005 extensions for .NET Framework 3.0 (Windows Workflow Foundation)

    Also there is 12 hands on lab.
    Community site with samples and other tutorials

    And now an example:
    Open Visual Studio 2005 and select new project, C#, workflow project.

    here is how workflow designer looks like

    at the left, in toolbox there are activities. drag and drop activity to workflow designer.

    We will use Code Activity and If else activity.

    here is the very simple application which demonstrate how to use WWF.
    This small demo is for registering flyghts. As I said it is very simple.
    We have one Dictionary variable where we save information about cities
    and two string variable for departure and arrival.

    	public sealed partial class Workflow1: SequentialWorkflowActivity
    	{
            public Dictionary cities =
                    new Dictionary();
    
            public string FromCity;
            public string ToCity;
    
            public Workflow1()
    		{
    			InitializeComponent();
    
                // Add cities in cities collection
                cities.Add(1, "medina");
                cities.Add(2, "london");
                cities.Add(3, "houston");
                cities.Add(4, "karachi");
                cities.Add(5, "tokyo");
                cities.Add(6, "singapore");
                cities.Add(7, "istanbul");
                cities.Add(8, "seattle");
    		}
    	}
    

    as you can see, in the constructor of this class Workflow1, we add some initial values for cities.

    Now we must say to our application which is true and which is false condition?
    Click on IfElseBranchActivity1 in Workflow designer and view Property. There is Condition property which can be: Code Condition or Declarative Rule condition. We will use Declarative Rule Condition. Enter name, like: FlightExisits. After that we must specify some rule. here is how we do that: click next to the expression and enter this text:
    this.cities.ContainsValue(this.FromCity.ToLower()) == True && this.cities.ContainsValue(this.ToCity.ToLower()) == True

    The same is for IfElseBranchActivity2. We will use Declerative Rule Condition. Set name to “FlightNotExists” and Expression to “!this.cities.ContainsValue(this.FromCity.ToLower()) || !this.cities.ContainsValue(this.ToCity.ToLower())”

    Here is the code which playes at the begining of application work. It belongs to CodeActivity:

            private void codeActivity1_ExecuteCode(object sender, EventArgs e)
            {
                Console.WriteLine("Enter Passenger Name : ");
                string passengerName = Console.ReadLine();
    
                Console.WriteLine("Enter Departure City :");
                this.FromCity = Console.ReadLine();
                Console.WriteLine("Enter Destination City :");
                this.ToCity = Console.ReadLine();
    
            }
    

    and here is code for true condition:

            private void codeActivity2_ExecuteCode(object sender, EventArgs e)
            {
                Console.WriteLine("Flight Booking Confirmed!");
                Console.ReadKey();
            }
    

    and here is code for false condition:

            private void codeActivity3_ExecuteCode(object sender, EventArgs e)
            {
                Console.WriteLine("Sorry, No Such Flight Exists!");
                Console.ReadKey();
            }
    

    at the end, here is autogenerated code for Program.cs

    namespace FirstWFProject
    {
        class Program
        {
            static void Main(string[] args)
            {
                using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
                {
                    AutoResetEvent waitHandle = new AutoResetEvent(false);
                    workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) {waitHandle.Set();};
                    workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                    {
                        Console.WriteLine(e.Exception.Message);
                        waitHandle.Set();
                    };
    
                    WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(FirstWFProject.Workflow1));
                    instance.Start();
    
                    waitHandle.WaitOne();
                }
            }
        }
    }
    

    WP Theme & Icons by N.Design Studio
    Entries RSS Comments RSS Log in