Monday, December 31, 2012

Simple Exif Viewer using C++ and Exiv2

Exif or Exchangeable image file format is a variation of JPEG, used by almost all digital cameras to record extra interchange information to image files as they are taken. Camera settings and scene information are recorded by the camera into the image file. Examples of stored information are shutter speed, date and time a photo was taken, focal length, exposure compensation, metering pattern and if a flash was used.

I have build a simple Exif Viewer using Exiv2 and C++ (I have wrote about Exiv2 in a previous post). Since Exiv2 supports command line, from my application I am invoking the Exiv2 commands through the command line and getting the output back to my application. The one of the nicest things in Exiv2 is, it has the capability to read set of commands from a text file and execute those commands on the command line.
image
Simple Exif Viewer
You can download the source and expand the application using various features Exiv2 supports.

Happy Coding.

Regards,
Jaliya

Saturday, December 22, 2012

Building and Installing Exiv2 on Visual Studio 2010

Exiv2 is a C++ library and a command line utility to manage image metadata. It provides fast and easy read and write access to the Exif (Exchangeable image file format), IPTC and XMP metadata of images in various formats. Exiv2 is available as free software and with a commercial license, and is used in many projects.

I have spent more than 2 hours to build this library on Visual Studio 2010. So I think it's better if I wrote the steps that I have followed to build the libraries.

Exiv2 has two main dependencies. One is expat and the other is zlib. The important thing here is finding the suitable versions of these two dependencies. To successfully compile Exiv2 we need following versions of expat and zlib.
Steps:
  • First create a folder in any place you like. I have created a folder named “gnu” in “C:\” drive.
  • Put all three folders which you got from extracting and put them inside the folder “gnu”.
image
My Folder : "C:\gnu"
image
C:\gnu\exiv2
image
C:\gnu\expat-2.0.1
image
C:\gnu\zlib-1.2.3
  • Open the “expat.dsw” inside the folder “expat-2.0.1”. Visual Studio 2010 will convert everything to latest project files and say "Yes" to everything.
  • Go to Batch Build and select the following and Build. Please note that if you try to build the whole solution you will get many errors. So you should only build the following.
    • expat-Debug
    • expat-Release
    • expat_static-Debug
    • expat_static-Release
image
Batch Build
image
Batch Build Selection
image
Build
  • Open the “zlib.dsw” inside the folder “zlib-1.2.3\projects\visualc6”. Again Visual Studio 2010 will convert everything to latest project files and say "Yes" to everything.
  • Go to Batch Build and select the following and Build. Please note that if you try to build the whole solution you will get many errors. So you should only build the following.
    • zlib-DLL Debug
    • zlib-DLL Release
    • zlib-LIB Debug
    • zlib-LIB Release
image
Batch Build Selection
image
Build
  • Now open the “exiv2.sln” inside the folder “exiv2\msvc”. Again Visual Studio 2010 will convert everything to latest project files and say "Yes" to everything. when Visual Studio has completed converting, select the project “exiv2lib”. Right click on it and select properties.
image
exiv2lib
image
exiv2lib Properties
image
exiv2lib Properties -> General
  • Only for this project, target name should changed as follows.
    • Debug           - exiv2sd
    • DebugDLL    - exiv2d
    • Release         - exiv2s
    • ReleaseDLL  - exiv2
image
Debug -> exiv2sd
image
DebugDLL -> exiv2d
image
Release -> exiv2s
image
ReleaseDLL -> exiv2
  • Now you can build the project without any errors.
image
Build
I have uploaded all the needed files to my skydrive and you can download it from there.


Happy Coding.

Regards,
Jaliya

Tuesday, December 18, 2012

ASP.NET Web Site in Windows 8 Metro Style

Have you ever wanted to create an ASP.NET web site in Windows 8 Metro Style? But you might already know that, to get started writing Metro style apps you need Windows 8 and Visual Studio 2012.

If you want to create Metro style using Visual Studio 2010, you will have to use third party libraries. I  have came across such a solution which is Metro UI CSS. Metro UI CSS a set of styles to create a site with an interface similar to Windows 8 Metro UI. This set of styles was developed as a self-contained solution. I have already tested it out and it’s really amazing.

image
Sample Metro Style Web App
I have created a sample web application, you can download and see for yourself the beauty of these css files.



Happy Coding.

Regards,
Jaliya

Friday, December 7, 2012

Presentation : Windows Communication Foundation (Part 2)

Continued my previous session at iOM World about Windows Communication Foundation (WCF) and today we spent some time learning how to create WCF services and how to configure the endpoints with different bindings etc.



I have uploaded the slide deck and demo source code to my SkyDrive. Do check it out.
     Download

Happy Coding.

Regards,
Jaliya

Wednesday, December 5, 2012

Forms Authentication with MS Access Database

I recently had a requirement to provide Forms Authentication to a web application which has a Microsoft Access database. If you are thinking that Forms authentication only supports with Microsoft SQL Server databases, No it’s not. ASP.NET supports variety of custom Membership and Roles providers including,
  • SQL Database Support for ASP.NET Membership, Roles and Personalization
  • Access Database Support for ASP.NET Membership, Roles and Personalization
  • MySQL Support for ASP.NET Membership and Roles
  • SQLLite3 Support for ASP.NET Membership and Roles
  • Oracle Support for ASP.NET Membership, Roles and Personalization
Today I am going to show you how to configure Forms Authentication with Microsoft Access. If you have used Forms Authentication with Microsoft SQL Server, you know that we run following command to create “aspnetdb” database in the SQL Server first.

image
Create aspnetdb in SQL Server
But since here we are using MS Access database, we should have some kind of a access database similar to “aspnetdb”. So for that Microsft has provided us a MS Access .mdb file and some set of classes to implement Forms Authentication with the provided MS Access database file. So let’s see how this works. (I am hoping to upload a sample project to SkyDrive, so you can get all the database files and class files.)

First I will create a new web application and I will add a new class library to the solution.

image
Solution Explorer : Add Class Library Project
In the class library I will add a folder called “AccessProviders” and I will add the Microsoft provided class files to that folder. Then I am building “MyAccessProvides” class library and to compile I need to add following references to the class library project.
  • System.Web
  • System.Web.ApplicationServices
  • System.configuration
image
Solution Explorer : AccessProviders
Now I am moving to my Web Application project and in that project I am adding a reference to my class library project. Then to the “App_Data” folder, I am adding the MS Access .mdb file.

image
Add Project Reference
image
Solution Explorer : App_Data Folder
Then I am modifying the web.config file as follows.

I am adding new a connection string which will point to the Access .mdb file.
<connectionStrings>
  <add name="AccessFileName" connectionString="~/App_Data/ASPNetDB.mdb" providerName="System.Data.OleDb"/>
</connectionStrings>

Then I am further modifying the web.config file as follows.
<membership defaultProvider="AccessMembershipProvider" >
    <providers>
    <clear/>
    <add name="AccessMembershipProvider"
        type="MyAccessProviders.AccessProviders.AccessMembershipProvider,MyAccessProviders"
        connectionStringName="AccessFileName" requiresQuestionAndAnswer="false"/>
    </providers>
</membership>

<profile enabled="true" defaultProvider="AccessProfileProvider">
    <providers>
    <add name="AccessProfileProvider" type="MyAccessProviders.AccessProviders.AccessProfileProvider,MyAccessProviders"
        connectionStringName="AccessFileName" />
    </providers>
    <properties>
    </properties>
</profile>

<roleManager enabled="true" defaultProvider="AccessRoleProvider">
    <providers>
    <clear/>
    <add name="AccessRoleProvider"
        type="MyAccessProviders.AccessProviders.AccessRoleProvider,MyAccessProviders"
        connectionStringName="AccessFileName" />
    </providers>
</roleManager>


Now that’s it. A can create a new account and I can see it in the “ASPNetDB.mdb”.

image
Create New Account
image
Logged In
image
User created in the database
I have uploaded a sample of all the class files and the database to SkyDrive. Do check it out and hope this helps.
     Download the Sample

Happy Coding.

Regards,
Jaliya

Tuesday, December 4, 2012

SharePoint 2010 : How to Create a Custom List Definition and a Instance

I will start by creating an Empty SharePoint project and I am going to deploy it as a Farm solution.
Untitled1
Empty SharePoint Project
Untitled2
Trust Level - Farm Solution
Then I am adding a SharePoint Mapped Folder to Images and I am adding a image to use as Feature Image Url.
Untitled3
SharePoint "Images" Mapped Folder
Untitled4
SharePoint "Images" Mapped Folder created
Then I am right clicking on my Project and add a new item which is a “List Definition”.
image
Add List Definition
Now I am setting the Display name of my list definition and setting up the list type as a “Custom List”.
Untitled5
List Display Name & Type

A Feature will be created in addition to my list definition. I am double clicking on the feature and in the properties I am setting up the Image Url.
Untitled6
Feature Image Url

Now I am modifying the Schema.xml file in the list definition. I am adding fields which should be included in my list.

Schema.xml
<Fields>
        <Field Name="EmpId" DisplayName="Employee Id" Type="Text"></Field>
        <Field Name="EmpName" DisplayName="Employee Name" Type="Text"></Field>
</Fields>


Since I have created an instance of my list, I am going to put some default values. I am modifying the Elements.xml of the instance.

Elements.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListInstance Title="MySharePointProject - MyListInstance"
                OnQuickLaunch="TRUE"
                TemplateType="10000"
                Url="Lists/MySharePointProject-MyListInstance"
                Description="My List Instance">
      <Data>
          <Rows>
              <Row>
                  <Field Name="EmpId">1</Field>
                  <Field Name="EmpName">Jaliya Udagedara</Field>
              </Row>

              <Row>
                  <Field Name="EmpId">2</Field>
                  <Field Name="EmpName">John Doe</Field>
              </Row>

              <Row>
                  <Field Name="EmpId">3</Field>
                  <Field Name="EmpName">Jane Doe</Field>
              </Row>
          </Rows>
      </Data>
  </ListInstance>
</Elements>


Now I am deploying the solution and once it is activated, I can see my List definition is available.
Untitled12
Create New List

And I can see a quick launch item is created.
Untitled7
Created List Instance

I am getting the default view of the list instance. But as you can see the two fields I have added is not displaying here. So I am again modifying the Schema.xml file in the list definition as follows. I am deploying the solution again and now the fields are displaying.

Schema.xml
<View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
    <Toolbar Type="Standard" />
    <XslLink Default="TRUE">main.xsl</XslLink>
    <RowLimit Paged="TRUE">30</RowLimit>
    <ViewFields>
      <FieldRef Name="Attachments"></FieldRef>
      <FieldRef Name="LinkTitle"></FieldRef> <!--if you don’t want to see title, comment this line-->
      <FieldRef Name="EmpId"></FieldRef>
      <FieldRef Name="EmpName"></FieldRef>
    </ViewFields>
    <Query>
      <OrderBy>
        <FieldRef Name="ID"></FieldRef>
      </OrderBy>
    </Query>
    <ParameterBindings>
      <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
      <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
    </ParameterBindings>
</View>


Untitled9
Created List Instance
Now when I click on Add new item, only Title field is displayed and not my created fields.
Untitled8
Created List Instance
For that, I am commenting the following part in the Schema.xml file in the list definition as follows.

Schema.xml
<!--<ContentTypes>
      <ContentTypeRef ID="0x01">
        <Folder TargetName="Item" />
      </ContentTypeRef>
      <ContentTypeRef ID="0x0120" />
    </ContentTypes>-->


Now I can see the fully completed output.
Untitled11
Created List Instance
Happy Coding.

Regards,
Jaliya

Tuesday, November 20, 2012

SharePoint : Sandboxed Solutions vs. Farm Solutions

We are almost close to end of this year and in this year I have only wrote 6 posts in SharePoint. I have not touched any SharePoint projects for like last 10 months and now I feel like I don’t know SharePoint at all. So it’s time to start learning SharePoint again, otherwise in couple of months I will ended up being a total stranger to SharePoint.

Today I am going to write about Sandbox solutions and Farm solutions. When you are creating any SharePoint solution using Visual Studio, you are prompted to select the Trust Level of the solution which is either a Sandboxed solution or a farm solution.
Untitled
Select the Trust Level
Which is either you can deploy the solution directly into the Server farm or into a sandbox. So what really is this deploying to sandbox or deploying to server farm? We are about to find it out.

Sandboxed Solution


Before learning what is a Sandboxed solution, we should learn what is a Sandbox. A sandbox is a testing environment that enables programs to access only certain resources, and that keeps problems/issues that occur in the sandbox from affecting the rest of the server environment. Basically what it does is sandbox isolates untested code from the working environment.

So when we are deploying a solution as a sandboxed solution, the solution  cannot access content outside the site collection they are deployed in. The sandboxed solution will not be able to use certain computer and network resources. Since the sandboxed solution is scoped to the site collection, we don’t really need a farm administrator to deploy the solution. A site collection administrator can do the deployment.

Sandboxed solutions are hosted in the SharePoint user code solution worker process (SPUCWorkerProcess.exe). Because sandboxed solutions do not run in the IIS worker process, neither the IIS application pool nor the IIS server must restart.

Mainly we can’t create following as a sandboxed solution.
  • Application pages.
  • Visual web parts.
  • Code-based workflows.
The following is a list of the most common things a solution running inside a sandbox cannot do,
  • Connect to resources that are not located on the local farm.
  • Access a database.
  • Call unmanaged code.
  • Write to disk.
  • Access resources in a different site collection.
  • Change the threading model.

Farm Solution


The Features in farm solutions can have scope as wide as the site collection, web application, or the whole SharePoint farm. Since Farm solutions can be scoped to Farm level, we need a Farm Administrator to deploy the solution and the assemblies in the solution always run with full trust.

Unlike sandboxed solutions, Farm solutions are are hosted in the IIS worker process (W3WP.exe) and the code in the farm solutions can affect the whole farm. When you try to retract or deploy a farm solution, the whole application pool will be recycled.

Farm solutions should be used for customizations of SharePoint administrative functions, such as custom timer jobs, custom Windows PowerShell cmdlets, and extensions of Central Administration.

For more information,
     What Can Be Implemented in Sandboxed Solutions in SharePoint 2010
     Sandboxed Solutions

Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, November 14, 2012

Introduction to Transactions in WCF

Couple of months back I have blogged about SQL Server Transactions. Last few days I have spent some quality time with the book Professional WCF 4: Windows Communication Foundation with .NET 4 and today I am going to write about what I learnt about Transactions in WCF. Since most of the things in this post will be theoretical things, you might feel bored. But I am sure, you will find some pretty interesting things here.

A transaction is a set of operations, in which if single operation fails, the entire set of operations are set to fail, as one atomic operation. Transactions are the best way to maintain consistency in a system. Let’s take a look at the following scenario where the system is transferring from state A to state B, as a result of series of operations.

1
States of a Transaction

In here State A and B are two consistent states. Before the transaction, the system is on State A and after completing the transaction the systems’ state changes into B.

When considering the above scenario, there can be three transaction types. Committed, Aborted and In-Doubt transaction. If the transaction manages to successfully transfer the system from State A to State B, then it is a Committed Transaction. If the transaction did not manage to transfer the system from State A to State B, and returned to State A, then it is an Aborted Transaction. Finally If the transaction failed to either commit or abort, then it is an In-Doubt transaction.

WCF services can work directly against any transactional resource. WCF also provides a programming model (as on offered by ADO.NET) to manage the transaction explicitly.

Mainly transactions have these four properties which are abbreviated as ACID.
  • Atomic
    • Atomic means that all the work in the transaction is treated as a single unit. That is either all statements in the unit must execute, or no statement in the unit must execute.
  • Consistent
    • Consistent means that a completed or roll backed transaction leaves the system in a consistent internal state. A transaction will convert the system from a known starting state to a known ending state. If the transaction commits, the database will be at the known ending state. If the transaction fails, the system will be at the known starting state.
  • Isolated
    • Isolation means that the transaction sees the system in a consistent state. If two transactions try to update the same resource, one will go first and then the other will follow. Transactions are committed independently from each other and they are transparent to each other.
  • Durability
    • Durability means that the results of the transaction are permanently stored in the system and ensures that the result or effect of a committed transaction persists in case of a system failure.

WCF Transactions

Distributed Transactions
A distributed transaction contains two or more independent services or even just a single service with two or more transactional resources. Let’s take the following design. We have an infrastructure where a client communicates with multiple services and these services interact with each other and with multiple resources.
2
Distributed Transaction

In here, we are facing two questions determining,
  1. Who will start the transaction and how others are going to know about the initiator? If everyone started transactions there will be many transactions.
  2. Who will instruct the transaction to either to commit or rollback?
In this kind of distributed transaction if you try to write the logic for transaction management, you will not be able to concentrate on your systems' logic. So you will need to rely on something. Now comes the Two-Phase Commit Protocol and the Transaction Manager to the picture. A transaction manager is a third party and will manage the transaction of the clients and services for you. Transaction manager takes the decision either to commit or rollback based on a transaction management protocol which is the two-Phase Commit protocol.
Transaction protocols used in Bindings
WCF chooses transaction management protocol based on the execution scope of the participating parties in the transaction. Please note that since I am using the term protocol here, this has nothing to do with two-Phase Commit protocol. These are used in bindings as the values for transactionProtocol.
  1. The Lightweight protocol
    • This protocol is used to manage transactions in a local context only, inside the same application domain.
    • The lightweight protocol is used only inside a service.
    • Never between services.
    • No binding supports the lightweight protocol.
  2. The OleTx protocol
    • This protocol is used to propagate transactions across application domain, process, and machine boundaries, and to manage the two-phase commit protocol.
    • Windows-Specific / Only in Windows environment.
    • Cannot be used across firewalls or to interoperate with Non-Windows parties.
    • TCP and IPC (Inter Process Communication) bindings uses OleTx protocol as the default and will switch to the WSAT protocol if required.
  3. The WS-Atomic Transaction (WSAT) protocol
    • Same as OleTx protocol.
    • Can be used across firewalls.
    • Non Windows-Specific.
    • The WS bindings are designed for use across the Internet, when multiple transaction managers are involved, using the WSAT protocol. (In an Internet scenario where only a single transaction manager is involved, these bindings will default to the OleTx protocol.)
Transaction Manager
WCF can work with three different transaction managers which are Lightweight Transaction Manager (LTM), the Kernel Transaction Manager (KTM), and the Distributed Transaction Coordinator (DTC). .NET will assign the appropriate transaction manager based on the platform used, what the application does, the services it calls, and the resources it consumes. Since the transaction manager is assigned automatically, the code is decoupled from the transaction management and from the transaction protocol used.
  1. Lightweight Transaction Manager (LTM)
    • Can only manage local transaction (inside a single application domain).
    • Can only manage a transaction inside a single service, and only when the service does not flow the transaction to other services.
    • Uses the lightweight transaction protocol to manage the two-phase commit protocol.
    • Most performing transaction manager.
  2. Kernel Transaction Manager (KTM)
    • Can be used to manage transactional kernel resource managers (KRMs) on Windows Vista, Windows Server 2008, and Windows 7 or later-specifically, the transactional files system (TxF) and the transactional registry (TxR).
    • Uses the lightweight transaction protocol.
  3. Distributed Transaction Coordinator (DTC)
    • Can manage transactions across any execution boundary, from the most local (a transaction within the same application domain) scope to the most remote (a transaction that crosses process, machine, or site boundaries).
    • Use either the OleTx or the WSAT protocol.
    • The DTC is the transaction manager used when transactions flow across the service boundary.
    • The DTC is a system service available by default on every machine running WCF, and WCF (and .NET) is tightly integrated with the DTC.
Two-Phase Commit Protocol
As the name means, this protocol has two phases.
  1. Commit Request / Voting
    • In this phase transaction manager requests the votes from all the participants to start a transaction.
    • Every participant replies with either Commit or Abort.
    • Once a vote has been made, it cannot be reversed.
  2. Commit / Complete
    • If every participant vote is for commit, then transaction is instructed to commit.
    • If single participant has voted to abort, then the transaction is instructed to abort and rollback.
Transaction Propagation
WCF can propagate transactions across the service boundary. Because of this, a one or more services can participate in a client’s transaction. In here client can be either a WCF or any other application. Both the binding and the operation contract take the decision on whether to or not to propagate on the client’s transaction. Only the TCP, IPC, and WS bindings have the ability to propagate client’s transactions.

Now comes the practical things, so I will stop now. Hope you all got a good understanding about these and will see these in action in a coming post.

Happy Coding.

Regards,
Jaliya

Friday, November 9, 2012

Presentation : Windows Communication Foundation (Part 1)

Conducted a session at iOM World about Windows Communication Foundation (WCF). Thought to introduce web services first, so this session was mainly targeted on Web Services though the heading was on WCF.




Happy Coding.

Regards,
Jaliya

Sunday, October 28, 2012

WCF Endpoints and Bindings Explained

My last post was about netTcpBinding in WCF and I thought it's better if I write a more detailed post about endpoints and bindings in WCF.

Windows Communication Foundation gives us the ability to transmit messages using different transport protocols such as HTTP, TCP, and MSMQ (Microsoft Message Queuing) etc. As you already know all communication with a WCF service occurs through the endpoints of the service.

There can be more than one endpoint for a service (Multiple Endpoints) and these endpoints provide client's the access to functionality offered by a WCF service. These endpoints has many properties and there are three main attributes which are commonly known as ABC’s or Where, How and What of a service. The ABCs make up an endpoint in WCF and these endpoints need to be set for both the service and the client.
  1. Address : The address uniquely identifies the endpoint and tells where the service is located.
  2. Binding : The binding specifies how to communicate with the endpoint. This includes the transport protocol, encoding to use for the messages and the necessary security requirements.
  3. Contract : The contract outlines what functionality the endpoint exposes to the client.
Today I will be focusing on the Address and the Binding attributes, because these two are very important.

For demonstration purposes I have created a WCF Service Application which is “WCFBindingApp” and I am using the IIS and not the Visual Studio Development server to host my service. Because we can’t use TCP bindings for services which are hosted in Visual Studio Development Server.

IService1

using System.ServiceModel;

namespace WcfBindingApp
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string MyMethod(string s);
    }
}

Service1.svc.cs

namespace WcfBindingApp
{
    public class Service1 : IService1
    {
        public string MyMethod(string s)
        {
            return string.Format("Message From Client: {0}", s);
        }
    }
}

Address of a Endpoint

When we define endpoints for a service, there are numerous options for specifying the address. You can either use the IP address or the host name along with the port number. If no port number is mentioned the default port for the protocol is used. There are two techniques we can use to specify the address.

   1.   Specify the absolute address for each endpoint

<services>        
    <service name="WcfBindingApp.Service1">        
        <endpoint address="http://localhost/WcfBindingApp/Service.svc" binding="basicHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>
    </service>
</services>

    2.   Specify a base address and then specify relative address for each endpoint

<services>
    <service name="WcfBindingApp.Service1">
        <endpoint address="" binding="basicHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>
        <endpoint address="secure" binding="wsHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>
        <endpoint address="tcp" binding="netTcpBinding" contract="WcfBindingApp.IService1" ></endpoint>

        <host>
            <baseAddresses>
                <add baseAddress="http://localhost/WcfBindingApp/Service.svc" />
            </baseAddresses>
        </host>
    </service>
</services>

since I am using the IIS here, I can write it even in this way without mentioning the base address (the base address will be determined by the IIS virtual directory). This will also work.

<services> 
    <!-- base address determined by IIS virtual directory -->        
    <service name="WcfBindingApp.Service1">
        <endpoint address="" binding="basicHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>
        <endpoint address="secure" binding="wsHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>
        <endpoint address="tcp" binding="netTcpBinding" contract="WcfBindingApp.IService1" ></endpoint>
    </service>
</services>

There are couple of things you should know when you define the address.

 1. If the address is empty, you can omit the address attribute. This means the endpoint will be exposed via the base address.

<endpoint address="" binding="basicHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>

is same as,

<endpoint binding="basicHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>

2. As I said before, when hosting in IIS, you don’t have to mention the base address. The base HTTP address is determined by the IIS virtual directory and WCF  ignores any base addresses we may specify.

3. When hosting in IIS, if you do specify an absolute address for a particular endpoint, it must start with the base address corresponding to the virtual directory.

4. When exposing multiple endpoints with same contract and with different bindings, each endpoint address must be unique.

5. If multiple endpoints share the same binding with different contracts, you can use the same address across those endpoints.

6. You can have multiple base addresses for each service, but only one for each protocol.

Bindings of a Endpoint

The bindings is the key element of the WCF architecture. There are variety types of bindings available to use when defining endpoints.

Built-In Bindings

Within the Windows Communication Foundation programming model, bindings are represented by the “System.ServiceModel.Channels.Binding” class. All binding classes must derive from this base class. Following image shows all the binding classes which are available with WCF.

image
Binding class which are available out of the box
In here I will only list the features of most used ones.
  • basicHttpBinding
    • Designed for scenarios where interoperability is of utmost importance.
    • HTTP for the transport and text for the message encoding.
    • Message version is SOAP 1.1.
    • Capable of using transport or message security, but both are disabled by default.
  • wsHttpBinding
    • Designed for interoperability while incorporating with richer Web services protocols for security, reliable messaging, and transaction.
    • Message version is SOAP 1.2.
    • This is default binding in WCF.
  • wsDualHttpBinding
    • Supports all the feature of wsHttpBinding.
    • Used for Duplex service contracts.
    • Supports bidirectional communication.
  • netTCPBinding
    • Unlike the ws* specific bindings, the various "Net" bindings were not designed for interoperability. This explains why the binding names are prefixed with "Net"
    • Assumes you have the Microsoft .NET Framework 3.0 installed on both sides.
    • NetTcpBinding uses TCP for the transport, binary for the message encoding, and SOAP 1.2 for the message version.
    • Enables transport security by default and can support transactions if enabled.
  • netPeerTCPBinding
    • Provides a secure binding for peer-to-peer network applications.
  • netNamedPipeBinding
    • Provides a secure and reliable binding that is optimized for on-machine communication.
    • Can be only used over a single WCF computer.
  • netMSMQBinding
    • Represents a queued binding that is suitable for cross-machine communication.
  • CustomBinding
Transport Protocols

Not like XML web services, WCF supports any protocol to communicate with the clients.
  • Http : This is the chosen protocol for communicating over the web and gives the ability to integrate the service with open standards exposing services to clients on many plaforms.
  • TCP : Fast binary format protocol. A great performance in WCF-WCF communication.
  • Named pipes : Fast communication between the client and the server which runs on the same machine. Works only in WCF-WCF.
  • MSMQ : Microsoft Message Queue allows queuing of messages and very useful in disconnected communications between the client the server. Used when client wants to enqueue a message that a service can consume later.
  • Custom Protocols : Can define own protocols.
Now let’s move in to see how binding is specified in the configuration file. The basic way is as follows.

<services>
    <service name="WcfBindingApp.Service1">
        <endpoint address="" binding="basicHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>
        <endpoint address="secure" binding="wsHttpBinding" contract="WcfBindingApp.IService1"></endpoint>
        <endpoint address="tcp" binding="netTcpBinding" contract="WcfBindingApp.IService1" ></endpoint>

        <host>
            <baseAddresses>
                <add baseAddress="http://localhost/WcfBindingApp/Service.svc" />
            </baseAddresses>
        </host>
    </service>
</services>

Here I have specified three bindings. And default settings are applied to each bindings. Now let’s say you want to change the wsHttpBinding defaults and apply new settings. You can easily do it this way.

<services>
    <service name="WcfBindingApp.Service1">
        <endpoint address="" binding="basicHttpBinding" contract="WcfBindingApp.IService1" ></endpoint>
        <endpoint address="secure" binding="wsHttpBinding" bindingConfiguration="mybinding" contract="WcfBindingApp.IService1"></endpoint>
        <endpoint address="tcp" binding="netTcpBinding" contract="WcfBindingApp.IService1" ></endpoint>

        <host>
            <baseAddresses>
                <add baseAddress="http://localhost/WcfBindingApp/Service.svc" />
            </baseAddresses>
        </host>
    </service>
</services>

<bindings>
    <wsHttpBinding>
        <binding name="mybinding"></binding> <!--you can change the default settings here-->
    </wsHttpBinding>
</bindings>

I am changing the wsHttpBinding settings and giving it a name. And in my endpoint I am giving it as endpoints binding congfiguration.

Now I have a client console application which will communicate with service using different bindings.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (svcTest.Service1Client client = new svcTest.Service1Client("BasicHttpBinding_IService1"))
                {
                    Console.WriteLine(client.MyMethod("basicHttpBinding"));
                }
                using (svcTest.Service1Client client = new svcTest.Service1Client("WSHttpBinding_IService1"))
                {
                    Console.WriteLine(client.MyMethod("wsHttpBinding"));
                }
                using (svcTest.Service1Client client = new svcTest.Service1Client("nettcpbinding_iservice1"))
                {
                    Console.WriteLine(client.MyMethod("netTcpBinding"));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:{0}", ex);
            }
            Console.ReadLine();
        }
    }
}

And when I run this I will get the output as follows.
Output
Hope you all got a good understanding about endpoints and different bindings I have explained. Appreciating your feedback.

Happy Coding.

Regards,
Jaliya