Monday 3 November 2014

A wait...yet to be over...

Hi all,
As of now I'm in China and behind The Great Firewall, I was unable to post something new. But now onward I will try to manage this blog to cater you all with new recipes...
Well very soon I'm coming with hot'n'spicy DDoS attacks and Mitigation. I have just completed my research on this topic before coming to Shanghai...

So...hope to have something new very soon...

Thursday 30 May 2013

TAPI : A gateway to VOiP in .net

As I have promised earlier, here I'm going to present the VOiP enhancements in .net framework. To implement Voice and Video services you need to incorporate TAPI dll in your application. TAPI is Telephony Application Programming Interface and in this post I am quoting TAPI v3.0. Here is a C# program which will exemplify the procedure which needs to be followed while doing TAPI programming using TAPI 3.0. The program shows you how you can use the TAPI 3.0 functions to create a TAPI application of your own. Microsoft provides more than 100 functions as part of the TAPI library. TAPI 2.1 was more difficult to use as it was a set of API functions but TAPI 3.0 which comes as part of Windows 2000 has ActiveX controls that make the TAPI application creation much easier. The TAPI SDK that can be downloaded from the Microsoft site. Learning to use different TAPI functions require lot of time investment but once you create some applications using these TAPI functions, it becomes easier for you to use the TAPI functions more efficiently.

First of all develop a basic design with all necessary stuffs for our application.




Adding a Reference
The first thing you need to start working on TAPI 3.0 API is to add the references to your project. To do that first create a new project or open an existing project, then right click on the solution file in Solution Explorer. This will open "Add Reference" dialog box as below:



Then loacte the tapi3.dll by clicking on "Browse" and select the tapi3.dll file from your windows\system32 or windows\system directory and click OK. Then press OK in the preceeding dialog box.

Add Code To Your Program
Next you need to do is create the TAPI objects to initialize the TAPI 3.0 TSP (TAPI Service Providers - For documentation refer to MSDN). The code below is a declaration of the TAPI object and addresses the interfaces that will hold the addresses which are responsible for call handling, and basic call control interface which will hold the reference to the object that will be responsible for handling basic operations of the call.

private TAPIClass tapiObj;
private ITAddress[] ia=new TAPI3Lib.ITAddress[10];
private ITBasicCallControl bcc;

The code below is meant for initializing a TAPI object to use it with our application. The main functions are:
  • Initialize() will initialize TAPI.
  • EnumerateAddresses() will give the list of available TSPs.


void initializetapi3()
{
    try
    {
        tapiObj = new TAPIClass();
        tapiObj.Initialize();
        IEnumAddress ea=tapiObj.EnumerateAddresses();
        ITAddress ln;
        uint arg3=0;
        lines=0;
    
        cn=new callnotification();
        cn.addtolist=new callnotification.listshow(this.status);
        tapiObj.ITTAPIEventNotification_Event_Event+= new 
           TAPI3Lib.ITTAPIEventNotification_EventEventHandler(cn.Event);
        tapiObj.EventFilter=(int)(TAPI_EVENT.TE_CALLNOTIFICATION|
            TAPI_EVENT.TE_DIGITEVENT|
            TAPI_EVENT.TE_PHONEEVENT|
            TAPI_EVENT.TE_CALLSTATE|
            TAPI_EVENT.TE_GENERATEEVENT|
            TAPI_EVENT.TE_GATHERDIGITS|
            TAPI_EVENT.TE_REQUEST);
    
        for(int i=0;i<10;i++)
        {
            ea.Next(1,out ln,ref arg3);
            ia[i]=ln;
            if(ln!=null)
            {
                comboBox1.Items.Add(ia[i].AddressName);
                lines++;
            }
            else
                break;
        }
    }
    catch(Exception e)
    {
        MessageBox.Show(e.ToString());
    }
}

The code below is responsible for registering incoming calls so that these calls can be handled by the application. For that you need to select the line on which you want to receive calls and press the "Register" button.

try
{
    registertoken[line]=tapiObj.RegisterCallNotifications(ia[line],
                 true,true,TapiConstants.TAPIMEDIATYPE_AUDIO,2);    
    MessageBox.Show("Registration token : "+ 
                 registertoken[line], 
                 "Registration Succeed for line "+line);
}
catch(Exception ein)
{
    MessageBox.Show("Failed to register on line "+line,"Registration for calls");
}

The class given below is to be added depending upon your TAPI event handling requirements. This is specially designed according to the requirements of the application.

class callnotification:TAPI3Lib.ITTAPIEventNotification
{
    public delegate void listshow(string str);
    public listshow addtolist;
    
    public void Event(TAPI3Lib.TAPI_EVENT te,object eobj)
    {
        switch(te)
        {
            case TAPI3Lib.TAPI_EVENT.TE_CALLNOTIFICATION:
                addtolist("call notification event has occured");
                break;
            case TAPI3Lib.TAPI_EVENT.TE_DIGITEVENT:
                TAPI3Lib.ITDigitDetectionEvent dd = 
                   (TAPI3Lib.ITDigitDetectionEvent)eobj;
                addtolist("Dialed digit"+dd.ToString());
                break;
            case TAPI3Lib.TAPI_EVENT.TE_GENERATEEVENT:
                TAPI3Lib.ITDigitGenerationEvent dg = 
                     (TAPI3Lib.ITDigitGenerationEvent)eobj;
                MessageBox.Show("Digit dialed...!");
                addtolist("Dialed digit"+dg.ToString());
                break;
            case TAPI3Lib.TAPI_EVENT.TE_PHONEEVENT:
                addtolist("A phone event occured!");
                break;
            case TAPI3Lib.TAPI_EVENT.TE_GATHERDIGITS:
                addtolist("Gather digit event!");
                break;
            case TAPI3Lib.TAPI_EVENT.TE_CALLSTATE:
                TAPI3Lib.ITCallStateEvent a= 
                     (TAPI3Lib.ITCallStateEvent)eobj;
                TAPI3Lib.ITCallInfo b=a.Call;
            switch(b.CallState)
            {
                case TAPI3Lib.CALL_STATE.CS_INPROGRESS:
                    addtolist("Dialing...");
                    break;
                case TAPI3Lib.CALL_STATE.CS_CONNECTED:
                    addtolist("Connected");
                    break;
                case TAPI3Lib.CALL_STATE.CS_DISCONNECTED:
                    addtolist("Disconnected");
                    break;
                case TAPI3Lib.CALL_STATE.CS_OFFERING:
                    addtolist("Here's a call for you!");
                    break;
                case TAPI3Lib.CALL_STATE.CS_IDLE:
                    addtolist("Call is made!");
                    break;
            }
            break;
        }
    }
}

How to handle IP calls or "Technically" H.323 calls?
To do IP calls or H.323 calls, I have given a checkbox named IP call enabled. Enter the IP address of the destination and press the Call button. Otherwise it will not succeed in calling to the remote destination. To receive H.323 calls or IP calls, you need to first register on the line on which you want to receive IP calls and check the above mentioned checkbox.

Transferring a call
To transfer a call, first there should be one active call existing. Then you can specify the address to which the call is to be transferred to, as shown in the figure:




Here IP of the machine has been given since the call was an IP call. To provide this functionality, there is a function in IBasicCallControl named BlindTransfer(String TransferAddress).

My next post would be about developing a complete PHONE DIALER by using this API. So keep checking for updates or subscribe for RSS feeds.

Hope to have feedback from all the readers. :)...enjoy coding...

Wednesday 27 March 2013

A basic WCF Service

The Windows Communication Foundation (WCF) service enables to manage the interoperability of the distributed applications and also supports the service oriented architecture. In this post I will illustrate the various steps required for creating, implementing and hosting of WCF. And also learn about creating the WCF client, its configuration and consuming the WCF service in an application. Let's understand the steps involved in Creating and Running a WCF service.

The Microsoft Visual Studio also contains pre-built template for creating the WCF service that can be created and implemented by following few wizard steps. Here we will use a C# class to create the WCF service, then will create a client application to consume the methods exposed by the WCF service. Following are the steps that we will cover to create a working WCF service:

  1. Defining Service Contract in WCF: the first step to create a WCF service contract using a C# interface that will outline the functionality offered by the service.
  2. Implementing Service Contract in WCF: the second step to implement the methods described in the interface created in the previous step.
  3. Hosting and Running a Basic WCF Service: the third step to host the service inside the application by providing an endpoint in C# code.
  4. Creating a WCF Client: the fourth step to retrieve the service metadata using Service Model Metadata Utility Tool provided by WCF. It enables to create a WCF client in relation to the underlying WCF service.
  5. Configuring a WCF Client: the fifth step to configure the WCF client by specifying the endpoint of the WCF service to access it.
  6. Using a WCF Client: the last step to invoke the functionality exposed by the WCF service and consuming it in the WCF client application.

Defining Service Contract in WCF

In this first step we will start with defining the Service contract in WCF. The WCF service contract involves the code for defining an outline of the service by creating a user defined interface. The interface includes all the methods and functionality that the underlying WCF service will expose to its corresponding client application.
The methods defined in the interfaces created for WCF service outlines its expected functionality. When an interface is created it must have the ServiceContractAttribute applied to it. The ServiceContractAttribute indicates that the interface or class is defined as a service contract in application. Each method defined inside the interfaces must have the OperationContractAttribute applied to it. The OperationCtractAtttribute indicates that the method is defined as a part of service contract in the application.

Creating WCF Service Contract with an Interface

1. Open the Microsoft Visual C# 2010 Express and select a new Console Application template from under the File menu -> New Project option.
2. In the Name box enter WCFService as application name and press ok to create an empty console application.
3. After creating the console application, it will show the Program.cs file by default containing the following Main method code:
namespace WCFService
{
    class Program
    {
        static void Main(string[] args)
        {


        }

    }
}
4. Next add a new interface to the application by right-clicking on the project in solution explorer and choosing New Item under the Add menu option. Specify IArea as interface name.
5. Add a reference to System.ServiceModel.dll by right-clicking the project in solution explorer and choosing Add Reference option.
6. In the Add Reference dialog box choose the System.ServiceModel and click ok to add its reference in to the application.
7. Include the System.ServiceModel namespace at the top of the IArea interface that we created earlier:
using System.ServiceModel;
8. Define the service contract and methods for the IArea interface as shown in the following code:
namespace WCFService
{
    [ServiceContract(Namespace = "http://WCFService")]
    public interface IArea
    {
        [OperationContract]
        double AreaOfRectangle(double length, double width);


        [OperationContract]

        double AreaOfCircle(double radius);
    }
}

Implementing Service Contract in WCF

1. Create a new class with name AreaService by right-clicking on the project in the solution explorer by choosing New Item from the Add menu.
2. Next implement the IArea interface to the class:
public class AreaService : IArea
3. Implement each method defined in the IArea interace within the AreaService class:
namespace WCFService
{
    public class AreaService : IArea
    {
        public double AreaOfRectangle(double length, double width)
        {
            double area = length * width;
            Console.WriteLine("length: {0}; width: {1}", length, width);
            Console.WriteLine("Area: {0}", area);
            return area;
        }


        public double AreaOfCircle(double radius)

        {
            double area = Math.PI * radius;
            Console.WriteLine("radius: {0}", radius);
            Console.WriteLine("Area: {0}", area);
            return area;
        }
    }
}
Now we are finished with creation of service contract and its implementation steps.

Hosting and Running a Basic WCF Service

The code for hosting and running a WCF service enables to run the service that can be consumed by the WCF client application. This third step involves a sequence of programming commands which enable to run a basic Windows Communication Foundation service. It consists of the following steps to self-host and run a service:
1. creating a base address for the service.
2. creating an instance for self-hosting the service.
3. enabling the metadata behavior
4. opening the service host
Self-Hosting and Running a WCF Service
1. Specify a base address for the WCF service using Uri class instance. The following Uri will open the port number 5000 to expose the service instance:
Uri serviceBaseAddress = new Uri("http://localhost:5000/WCFService/Sample");
2. Next create the ServiceHost instance for self-hosting the WCF service over the specified base address:
ServiceHost selfServiceHost = new ServiceHost(typeof(AreaService), serviceBaseAddress);
3. Then add a service endpoint that enables to expose the service:
selfServiceHost.AddServiceEndpoint(typeof(IArea), new WSDualHttpBinding(), "AreaService");
4. To enable the metadata information exchange functionality of a WCF service, you must import the System.ServiceModel.Description namespace at the top of the program.cs file:
using System.ServiceModel.Description;
5. You can use the following C# code inside the Main method of program.cs file to run the basic WCF service.
static void Main(string[] args)
{
    // creating base address for self-hosting the WCF service
    Uri serviceBaseAddress = new Uri("http://localhost:5000/WCFService/Sample");


    // creating an instance for self-hosting

    ServiceHost selfServiceHost = new ServiceHost(typeof(AreaService), serviceBaseAddress);


    try

    {
        // adding a service endpoint
        selfServiceHost.AddServiceEndpoint(typeof(IArea), new WSDualHttpBinding(), "AreaService");


        // enabling metadata behavior of service

        ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();
        serviceMetadataBehavior.HttpGetEnabled = true;
        selfServiceHost.Description.Behaviors.Add(serviceMetadataBehavior);


        // starting the WCF service instance

        selfServiceHost.Open();
        Console.WriteLine("The service is running now.");
        Console.WriteLine("Press any key to stop the service...");
        Console.WriteLine();
        Console.ReadLine();
        // stopping the WCF service instance
        selfServiceHost.Close();
    }
    catch(CommunicationException ex)
    {
        // abort the service in case any error occurs
        Console.WriteLine("An exception occurred: {0}", ex.Message);
        selfServiceHost.Abort();
    }
}
6. Press F5 to compile and run the service and try to browse the base address URL in the Internet Explorer. If it shows the web service information without any error, it means you have created a service successfully.

Creating a WCF Client

The fourth step involves creating the Windows Communication Foundation (WCF) client. It can be created using a Service Model Metadata Utility Tool (svcutil.exe) that can be found inside the Visual Studio SDK. This utility tool enables to extract the metadata associated to the WCF service and auto-generates a managed code for WCF service proxy in the specified programming language. It also generates a configuration file containing the information about WsDualHttpBinding and service endpoints which enable the client to communicate with the WCF Service.

Steps to Create a WCF Client

1. Add a new Console Application into the same WCFService solution by selecting its template from under the File menu -> New Project option.
2. In the Name box enter WCFService_Client as application name and press ok to create an empty console application.
3. After creating the console application, it will show the Program.cs file by default containing the following Main method code:
namespace WCFService_Client
{
    class Program
    {
        static void Main(string[] args)
        {


        }

    }
}
4. Add a reference to System.ServiceModel.dll by right-clicking the project in solution explorer and choosing Add Reference option. 
5. Now before proceeding further we need to create a proxy class using Service Model Utility Tool. Locate the tool inside the Microsoft SDK under the following path:
For x64 windows:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin
For x86 windows:
C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bin
First run the WCFService application to self-host and run the created WCF service then open the command prompt and change directory to the above specified path and run the following command to generate the managed source code in C#:
svcutil.exe /language:cs /out:wcfServiceProxy.cs /config:app.config http://localhost:5000/WCFService/Sample
After executing the above comment it will generate two output files inside the located tool path in the command prompt where the svcutil.exe exists. It will generate wcfServiceProxy.cs and app.config file there. The Service Model Metadata Utility Tool will generate the following code in wcfServiceProxy.cs file:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.4952
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------



[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]

[System.ServiceModel.ServiceContractAttribute(Namespace="http://WCFService", ConfigurationName="IArea")]
public interface IArea
{
    
    [System.ServiceModel.OperationContractAttribute(Action="http://WCFService/IArea/AreaOfRectangle", ReplyAction="http://WCFService/IArea/AreaOfRectangleResponse")]
    double AreaOfRectangle(double length, double width);
    
    [System.ServiceModel.OperationContractAttribute(Action="http://WCFService/IArea/AreaOfCircle", ReplyAction="http://WCFService/IArea/AreaOfCircleResponse")]
    double AreaOfCircle(double radius);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface IAreaChannel : IArea, System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class AreaClient : System.ServiceModel.ClientBase<IArea>, IArea
{
    
    public AreaClient()
    {
    }
    
    public AreaClient(string endpointConfigurationName) : 
            base(endpointConfigurationName)
    {
    }
    
    public AreaClient(string endpointConfigurationName, string remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public AreaClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(endpointConfigurationName, remoteAddress)
    {
    }
    
    public AreaClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(binding, remoteAddress)
    {
    }
    
    public double AreaOfRectangle(double length, double width)
    {
        return base.Channel.AreaOfRectangle(length, width);
    }
    
    public double AreaOfCircle(double radius)
    {
        return base.Channel.AreaOfCircle(radius);
    }
}

Configuring a WCF Client

The WCF service can be consumed in a WCF Client application only if its endpoint configured properly. In the previous tutorial: Creating a WCF Client we used the Service Model Metadata Utility Tool (svcutil.exe) to generate a proxy class and a configuration file. The configuration step for WCF client consists of specifying the endpoints to enable the client application to access the WCF service. An endpoint configuration contains the base address, binding such as WsDualHttpBinding, and service contract.
Steps to Configure a WCF Client
1. For adding the auto-generated proxy class i.e. wcfServiceProxy.cs that we created in the previous tutorial, right click on the project in the solution explorer and click the Existing Item option from the Add menu. Then browse and select the wcfServiceProxy.cs class file from the Add Existing Item dialog box. Click the Add button to include the managed source code class file into the WCFService_Client application.
2. Repeat the above step to add the existing app.config file, generated using svcutil.exe tool, into the client application. The app.config file includes the endpoint required for accessing the WCF service. Following is the app.config file code auto-generated by Service Model Metadata Utility tool:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsDualHttpBinding>
                <binding name="WSDualHttpBinding_IArea" 
                         closeTimeout="00:01:00"
                         openTimeout="00:01:00" 
                         receiveTimeout="00:10:00" 
                         sendTimeout="00:01:00"
                         bypassProxyOnLocal="false" 
                         transactionFlow="false" 
                         hostNameComparisonMode="StrongWildcard"
                         maxBufferPoolSize="524288" 
                         maxReceivedMessageSize="65536"
                         messageEncoding="Text" 
                         textEncoding="utf-8" 
                         useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" 
                                  maxStringContentLength="8192" 
                                  maxArrayLength="16384"
                                  maxBytesPerRead="4096" 
                                  maxNameTableCharCount="16384" />
                  
                    <reliableSession ordered="true" 
                                     inactivityTimeout="00:10:00" />
                    <security mode="Message">
                        <message clientCredentialType="Windows" 
                                 negotiateServiceCredential="true"
                                 algorithmSuite="Default" />
                    </security>
                </binding>
            </wsDualHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:5000/WCFService/Sample/AreaService"
                      binding="wsDualHttpBinding" 
                      bindingConfiguration="WSDualHttpBinding_IArea"
                      contract="IArea" 
                      name="WSDualHttpBinding_IArea">
                <identity>
                    <userPrincipalName value="Rayat-PC\Rayat" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>
Now the WCF client application is ready to access the WCF service.

Using a WCF Client

Now our client application is ready to access the WCF client and consume the service contracts. The Windows Communication Foundation (WCF) proxy class included inside the client application it enables to initialize the client instance that further allows consuming the service contracts exposed by the WCF service.
The code required for using a WCF client must be placed inside the Main() method of program.cs class file of the client application.
C# Code to Use WCF Client
1. It is an optional step to specify the endpoint programmatically, but if required anywhere then you can use the following code to specify the endpoint address using C# code:
// specify the same endpoint address that we got in the generated app.config file
EndpointAddress endPointAddress = new EndpointAddress("http://localhost:5000/WCFService/Sample/AreaService");
2. For providing the endpoint address explicitly, you can use the following code to initialize an instance of WCF client:
// initialize an instance of WCF client
AreaClient areaclient = new AreaClient(new WSDualHttpBinding(), endPointAddress);
  
3. You can call the client operations by the following way:
double length = 85.5;
double width = 35.5;


Console.WriteLine(areaclient.AreaOfRectangle(length, width));

4. Alternatively you can also use the following code to access and use a WCF Client that requires no endpoint specification explicitly:
static void Main(string[] args)
{
    // initialize an instance of WCF client
    AreaClient areaclient = new AreaClient();


    double length = 85.5;

    double width = 35.5;


    Console.WriteLine(areaclient.AreaOfRectangle(length, width));

}
For running the WCF client, ensure that the WCF service instance is already running. Otherwise run the WCF service instance and then run the WCF client instance to execute the specified client operation.
You can get further information from my article hosted at Scribd