Tuesday, June 14, 2011

Hosting a WCF Service in a Managed Application

WCF enables you to host your service through any managed application. This means you can use a Console application, a Windows service, a Windows Forms application, or even an application built with Windows Presentation Foundation.

Hosting a WCF Service by Using a Console Application

The Console application must specifically create and open an instance of the ServiceHost object. The ServiceHost then remains open and available until it is no longer needed.

Eg:
• Create a New Project from the File menu and select WcfServiceLibrary.
Create and Implement service.
Build the project.
• Create ConsoleApplication named ConsoleServiceHost. From the project menu select Add Reference option and select the WcfServiceLibrary1.dll. Click ok.
Write the following code in the Main function.


ServiceHost host = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
host.Open();
Console.WriteLine("Service Started...");
Console.WriteLine("\nPress any key to stop...");
Console.ReadLine();
host.Close();

Add an Application Configuration file to the project. And write the following configuration settings in the app.config.
<configuration>
<system.serviceModel>
<services>
<service name="WcfServiceLibrary1.Service1" behaviorConfiguration="WcfServiceLibrary1.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/" />
</baseAddresses>
</host>
<endpoint address ="" binding="wsHttpBinding" contract="WcfServiceLibrary1.IService1">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfServiceLibrary1.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>

• Create a new console application. Copy the address from the app.config of ConsoleServiceHost application. Add service reference. Write the following code in the main function.
Console.WriteLine("Press ENTER when the service has started");
Console.Read();

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();

Console.WriteLine(client.GetData(33));
client.Close();
Console.WriteLine("Press any key to exit");
Console.ReadLine();
Console.ReadLine();

Monday, June 13, 2011

Hosting a WCF Service on a Web Server

Hosting a Service on an IIS Web Server
Hosting a service on an IIS Web server is very similar to hosting a traditional Web service. Services exposed this way will be highly available and scalable, but they will require the installation and configuration of an IIS Web server.

To register WCF in IIS Run the following command.

C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation>ServiceModelReg.exe -i.

You can host a WCF Service in two different ways.

1. Create WCF service in HTTP mode.
When creating a WCF Service in HTTP Mode it automatically hosted in IIS webserver. To create a service in HTTP Mode, your system must have IIS get installed.




2. Manually host the service in IIS like websites.
You can also do hosting a service by creating a virtual directory in IIS and paste you service files into your virtual directory.

Publishing Metadata Through Endpoints

WCF enables you to publish service metadata, using the HTTP-GET protocol. Clients can access the metadata using an HTTP-GET request with a ?wsdl query string appended. You do this by specifying a service behavior either programmatically or through a configuration file. The behavior is then referenced when specifying the service.

You also need to create a metadata exchange endpoint. This special endpoint can append mex to the HTTP address the service uses. The endpoint should use the IMetadataExchange interface as the contract and mexHttpBinding as the binding.

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="http://localhost:50187/WCFService1/" binding="wsHttpBinding" contract="IService"></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Tuesday, June 7, 2011

Advanced TextBox for Asp.Net ( TextBox with built in Validation )

Advanced TextBox Control for Asp.Net (Asp.Net Custom Server Control)
Hello friends, we all have been using Asp.Net validation controls with TextBox controls. By default, we have to configure several properties to do a validation using any validation controls. Here I'm introducing a new Custom Server Control which is derived from TextBox control. This control have some additional properties under the Advanced tab on the properties window.
The given below example shows how to create (or setup) an AdvancedTextBox control with builtin logic for validations. AdvancedTextBox control uses the TextBox and validation controls built with Asp.Net .
To develop this control, create a Asp.Net Server Control Project and write the following code.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AdvancedTextBox
{
public enum TextType
{
String,
Int,
Double,
Date,
Email,
Url
}

[DefaultProperty("Text")]
[ToolboxData("<{0}:AdvancedTextBox runat=server></{0}:AdvancedTextBox>")]
public class AdvancedTextBox : TextBox
{
private TextType _textType = TextType.String;
private bool _isRequired = false;
List<Control> _controls = new List<Control>();

[Category("Advanced")]
[Description("Text type for the TextBox")]
public TextType TextType
{
set
{
_textType = value;
}
get
{
return _textType;
}
}

[Category("Advanced")]
[Description("Mandatory field or not")]
public bool IsRequired
{
set { _isRequired = value; }
get { return _isRequired; }
}

[Category("Advanced")]
[Description("Minimum range value")]
public string MinimumValue
{
set;
get;
}

[Category("Advanced")]
[Description("Maximum range value")]
public string MaximumValue
{
set;
get;
}
[Category("Advanced")]
[Description("Error Message to be displayed when not entering value.")]
public string RequiredErrorMessage
{
set;
get;
}
[Category("Advanced")]
[Description("Error message to be displayed when type mismatch or range violation.")]
public string TypeOrRangeErrorMessage
{
set;
get;
}

[Category("Advanced")]
[Description("Sets the Text property of associated validation controls")]
public string ValidatorText
{
set;
get;
}

protected override void OnInit(EventArgs e)
{
GenerateControls();
base.OnInit(e);
}

protected void GenerateControls()
{
if (_isRequired)
{
RequiredFieldValidator req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ForeColor = System.Drawing.Color.Red;
req.ValidationGroup = this.ValidationGroup;
req.ErrorMessage = this.RequiredErrorMessage;
req.Text = this.ValidatorText;
_controls.Add(req);
this.Controls.Add(req);
}
if (this.MinimumValue != null this.MaximumValue != null)
{
RangeValidator rag = new RangeValidator();
rag.ControlToValidate = this.ID;
rag.ForeColor = System.Drawing.Color.Red;
rag.ValidationGroup = this.ValidationGroup;
rag.ErrorMessage = this.TypeOrRangeErrorMessage;
rag.Text = this.ValidatorText;
switch (_textType)
{
case TextType.Int:
rag.Type = ValidationDataType.Integer;
break;
case TextType.Double:
rag.Type = ValidationDataType.Double;
break;
case TextType.Date:
rag.Type = ValidationDataType.Date;
break;
default: rag.Type = ValidationDataType.String;
break;
}

rag.MinimumValue = this.MinimumValue;
rag.MaximumValue = this.MaximumValue;
_controls.Add(rag);
this.Controls.Add(rag);
}
else
{
switch (_textType)
{
case TextType.String:

break;
case TextType.Int:
CompareValidator cv = new CompareValidator();
cv.ControlToValidate = this.ID;
cv.ValidationGroup = this.ValidationGroup;
cv.ForeColor = System.Drawing.Color.Red;
cv.ErrorMessage = this.TypeOrRangeErrorMessage;
cv.Type = ValidationDataType.Integer;
cv.Text = this.ValidatorText;
cv.Operator = ValidationCompareOperator.DataTypeCheck;
_controls.Add(cv);
this.Controls.Add(cv);
break;
case TextType.Double:
cv = new CompareValidator();
cv.ControlToValidate = this.ID;
cv.ValidationGroup = this.ValidationGroup;
cv.ForeColor = System.Drawing.Color.Red;
cv.ErrorMessage = this.TypeOrRangeErrorMessage;
cv.Type = ValidationDataType.Double;
cv.Text = this.ValidatorText;
cv.Operator = ValidationCompareOperator.DataTypeCheck;
_controls.Add(cv);
this.Controls.Add(cv);
break;
case TextType.Date:
cv = new CompareValidator();
cv.ControlToValidate = this.ID;
cv.ValidationGroup = this.ValidationGroup;
cv.ForeColor = System.Drawing.Color.Red;
cv.ErrorMessage = this.TypeOrRangeErrorMessage;
cv.Type = ValidationDataType.Date;
cv.Text = this.ValidatorText;
cv.Operator = ValidationCompareOperator.DataTypeCheck;
_controls.Add(cv);
this.Controls.Add(cv);
break;
case TextType.Email:
RegularExpressionValidator reg = new RegularExpressionValidator();
reg.ControlToValidate = this.ID;
reg.ForeColor = System.Drawing.Color.Red;
reg.ValidationGroup = this.ValidationGroup;
reg.ErrorMessage = this.TypeOrRangeErrorMessage;
reg.Text = this.ValidatorText;
reg.ValidationExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
_controls.Add(reg);
this.Controls.Add(reg);
break;
case TextType.Url:
reg = new RegularExpressionValidator();
reg.ControlToValidate = this.ID;
reg.ForeColor = System.Drawing.Color.Red;
reg.ValidationGroup = this.ValidationGroup;
reg.ErrorMessage = this.TypeOrRangeErrorMessage;
reg.Text = this.ValidatorText;
reg.ValidationExpression = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&amp;=]*)?";
_controls.Add(reg);
this.Controls.Add(reg);
break;
default:
break;
};
}

}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
for (int i = 0; i < _controls.Count; i++)
{
_controls[i].RenderControl(writer);
}
}
}
}



When using this AdvancedTextBox control you can see the "Advanced" tab on the properties window.







  • IsRequired : when you set this property to true, then AdvancedTextBox come up with RequiredFieldValidator control.

  • MaximumValue and MinimumValue: when you set this property AdvancedTextBox come up with a RangeValidatior Control.

  • RequiredErrorMessage: Error message to be set on the Required field validation control.

  • TextType: When you set this property, Advanced TextBox come up with a CompareValidator control to ensure the data type.

  • TypeOrRangeErrorMessage: Error message to be set on either compare validator control or range validator control.

  • ValidatorText: This will be for setting the Text property of the validation controls that are come up with AdvancedTextBox control.

This control will help developers to develop GUI fastly and efficiently without specifying or declaring any validation controls to validate a TextBox.
Hope all of you are doing great programming with AdvancedTextBox Control. Feel free to ask questions and doubts. :-)

Friday, June 3, 2011

Singleton Design Pattern in .Net (C#)

Singleton Design Pattern
This pattern ensures that only a single instance of a given object can exist. It prevent developers from creating multiple instances of class. It is very simple patter to implement it in our applications. Go through the following example, it will give you the exact idea behind the Singleton Design Pattern.

    //sealed class cannot be inherited.
//thus we can prevent creating objects
//through its subclasses.
public sealed class MyDataContext
{
private static readonly MyDataContext _context = new MyDataContext();

//by defining a private constructor
//we cannot create an object from outside the class.
private MyDataContext()
{
}

public static MyDataContext Create()
{
return _context;
}


//Other operations.
}


Here in this example we can create an instance of MyDataContext class only by calling the Create method. We have ensure singleton by



  • declaring class as sealed

  • defining a private constructor to prevent outside object initialization

Hope all of you are now clear with Singleton Design Pattern. In my opinion this pattern is most used in Desktop Applications. It is possible to implement this in Asp.Net, I will post an article on that soon.

Factory Method Design Pattern in .Net (C#)

Factory Method Pattern
Like Abstract Factory Pattern, Factory Method Pattern is also a part of Creational patterns. This pattern is also to create concrete product objects. There are many ways are available to implement Factory Method Pattern in .Net. Here I will demostrate a typical structure of Factory Method Pattern.
Factory Method Pattern Structure


  1. Creator: An interface to create product objects. which contains either factor method declarations or factory methods itself. (In .Net an Abstract class or Interface is used to create Creator).

  2. Concrete Creator: It implements the factory methods declared within the Creator. (It will be class declaration)

  3. Product: Declares an interface to define products. (It will be either an Abstract class or an Interface)

  4. Concrete Product: It implements the Product to define a concrete object. (it will be class).

Have a look on the following example. Here in this example I have created all the above mentioned items.


1. Creating Product. In the example I have used an Interface named "IFruit" to create a Product.


Note: Here in our example I have used Interface instead of base classe, you can use abstract classes because abstract classes offer versioning benefits over pure interfaces.


    public interface IFruit
{
string GetDescription();
}

2. Creating concrete products. In our example I have created two concrete products named "Apple" and "Orange".

    public class Apple : IFruit
{
public string GetDescription()
{
return "I'm an Apple....!";
}
}

public class Orange : IFruit
{
public string GetDescription()
{
return "I'm an Orange....!";
}
}



3. Creating Creator: In our example I have created a creator named "IFruitFactory".

    public interface IFruitFactory
{
IFruit CreateApple();
IFruit CreateOrange();
}
4. Creating Concrete Creator: We have a concrete creator named "FruitFactory" is in our example.
    public class FruitFactory : IFruitFactory
{
public IFruit CreateApple()
{
return new Apple();
}

public IFruit CreateOrange()
{
return new Orange();
}
}
Next we can consume our sample application
            IFruitFactory fruitFactory = new FruitFactory();
IFruit fruit;

fruit = fruitFactory.CreateApple();
Console.WriteLine(fruit.GetDescription());

fruit = fruitFactory.CreateOrange();
Console.WriteLine(fruit.GetDescription());



Hope all of you are clear with Factory Method pattern. Above I mentioned only the typical way of defining Factory Method Pattern; there are several other ways to implement the same. Try it yourself. :-)