Opening a Jquery UI Modal Dialog shows a scroll bar on parent page

Howdy my dear readers, I hope you must be doing great!
Yes, I’m back here to write a new blog post after so long time. Sorry for not sharing anything with you since so long. But got busy with lot of bits and pieces. But it’s good to be busy, the busier you are the more you have to share!

So, keep visiting – going to share more with you in upcoming days! [Free advice: You can subscribe to this blog via EMAIL SUBSCRIPTION box given in right side – which means that whenever any new post gets posted here, you will get an email!]

Challenge:

I got a chance to use Jquery UI‘s Modal dialog in my application. Now, whenever we used to open a dialog and when we open it, it was showing scroll-bar on parent page.

Solution:

After doing a bit research and finally thought to use following solution, which worked for us:
http://forum.jquery.com/topic/opening-a-modal-dialog-shows-a-horizontal-scroll-bar [Main logic lies in open and close event!]
Basically, above solution sets body’s overflow to hidden in open event and auto in close event. Which works fine for all browsers except IE7.  What’s the solution? Why?
Solution is you need to set overflow hidden of html element as well along with body.
Why so?
Excerpt from http://stackoverflow.com/questions/4443006/body-overflow-hidden-problem-in-internet-explorer-7

Applying overflow-x:hidden or overflow-y:hidden; to the body element of the document will not work. The overflow-x:hidden or overflow-y:hidden must be applied to the html element, not body element.

Happy Coding! 🙂

Is it necessary to recycle worker process periodically?

Challenge:

By default IIS recycles your application pool after 1740 minutes (29 hours) which is default setting.  (Good to know that there are few other reasons due to which your application pool gets recycled automatically — What are they? read my earlier blog post) and this link is also good to read — http://lab.technet.microsoft.com/en-us/magazine/cc161040

Periodic recycling of your application pools is recommended. It helps to clean up memory fragmentation, memory leaks, abandoned threads and other clutter. Keep in mind that when an application pool recycles, session state information stored in-process is lost for that pool, but other pools are not affected. ASP.NET, however, does allow you to store your session state outside the worker process, so that session information is not lost during a recycle.
Notice that Recycle worker processes (in minutes) is set to 1740 minutes (29 hours) by default. This will cause an automatic recycling to occur every day, five hours later than the previous day. You may want to consider changing this to recycle at a specific time of day when your server load is the smallest. In a Web farm, you can stagger the settings.

http://lab.technet.microsoft.com/en-us/magazine/cc161040.fig02(en-us).gif
Okay, so it gets restart after 29 hours. If you have web farm then you can’t rely on this default setting. Because your server might get recycled during peak hour! (at the time when you expect your servers to server more and more number of requests!). So, to deal with this situation you can use schedule recycle for your application. Using which you can scheule your application pool to recycle during out of office hours.
We were also following scheduled recycling approach (We scheduled our application to recycle every day during OOH hours). But our application heavily relies on our caching layer which stores full data in memory.  Now, when we schedule our application to get recycled during office hours. Obviously, it will flush full cache and after recycle first request for each resource will be bit slow. (It might not be noticeable to an end users. But you can see that effect via your monitoring systems).
Then, question came to our mind that “Do we really need to recycle application pool daily?” Is it a same question you have? Then this post is for you!

Solution:

We did bit research and found few nice things and concluded few things, which sharing here with you:
http://sdn.sitecore.net/forum/showpost.aspx?PostID=19209

While I can see the advantages of restarting periodically, I actually think that the primary value of autorestart is to mask memory leaks and other defects in both ASP.NET and the solution. So if the quality of the code is high or the load is low, I think it’s probably not necessary to restart, but I would monitor the machine a little more closely for some time after making the change.

Nice article by Microsoft which helps you to Determining When to Use Worker Process Recycling– http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/3adc0117-3c7b-4bb9-a4a9-1d0592b84c9c.mspx?mfr=true
Basically, you should do recycle app pool, if your application is handling lot of issues, facing performance issues, having memory leak issues that could not be handled, and need sometime to fix it.
Okay, so if your application is not having memory leaks issues. You can disable application pool recycling! But how to find out whether your application has memory leak issues or not?
I also had same question and already wrote an article on it — http://kiranpatils.wordpress.com/2012/06/05/basics-of-memory-leak/
If this post helped you, then say thanks to Kate Butenko!
Happy Coding! 🙂
 

Why we use lookup tables in SQL

Challenge:


Few days back, we had a good discussion on lookup tables. Why we need them in our Database schema? Can’t we directly store simple status related text in parent table itself? why we add one extra table? why we need to do joins and fetch records out of it? If you also have such “whys” in your mind. Then this post is for you only!

Solution:

Basically, I was clear that we should use it? But the main thing is why? Did a quick search and found so many good links, but this stackoverflow discussion link [http://stackoverflow.com/questions/4824024/how-important-are-lookup-tables] sounds really perfect —  few points from discussion:

  • if you have “Open” and “Closed” repeated in data tables, that is a simple Normalisation error. If you change those values you may have to update millions of rows, which is very limited design. Such values are commonly normalised into a Reference or Lookup table. It also saves space. The value “Open”, “Closed” etc is no longer duplicated.
  • the second point is ease of change, if “Closed” were changed to “Expired”, again, one row needs to be changed, and that is reflected in the entire database; whereas in the unnormalised files, millions of rows need to be changed.
  • Enum is only for the Non-SQLS. In SQL the Enum is a Lookup table.
  • Since PKs are stable, particularly in Lookup tables, you can safely code:  WHERE status_id = ‘O’
  • And the users would choose the value from a drop-down that displayed “Open”, “Closed”, etc., not {0,1,2,4,5,6}, not {M, F, U}. Both in the apps, and in the report tool. Without a lookup table, you can’t do that.
  • The next point relates to the meaningfulness of the key. If the Key is meaningless to the user, fine, use an INT or TINYINT or whatever is suitable; number them incrementally; allow “gaps”. But if the Key is meaningful to the user, do not use a meaningless number, do use the meaningful key. “M” and “F” for Male and Female, etc.
  • Now some people will get in to tangents re the permanence of PKs. That is a separate point. Yes, of course, always use a stable value for a PK. “M” and “F” are unlikely to change; if you have used {0,1,2,4,5,6}, well don’t change it, why would you want to. Those values were supposed to be meaningless, only meaningful Key need to be changed.

And the final one, I liked most and modified a bit:

  • I always preferred the lookup table as opposed to constants because why duplicate a varchar(20) in every row when you can use a 1 byte tinyint id. Very true — For example if you have 2,00,000 records and if your column size is varchar(20) and let’s say we have 8 bytes data for each row. So, they goes around 1.5 MB. Now, if we have lookup table and store ID as int, which consumes 4 bytes then your size will be half (0.76 MB). And obviously, if after entering 2,00,000 records. If someone comes and ask you that we need to change value of some “X” to “Y” then you no need to update 2,00,000 records. Just update one record and you are done!

Happy Lookup! 🙂

Basics of Memory leak

Challenge:

Before couple of weeks, we wanted to check whether our application has memory leaks issue or not? And while doing that we found few articles, understood something, and learnt something which I would like to share with you.

Solution:

Best links to read:
http://www.codeproject.com/Articles/42721/Best-Practices-No-5-Detecting-NET-application-memo
http://blogs.msdn.com/b/tess/archive/2005/11/25/496899.aspx
Basically, to detect Memory leak you should check following things:
You should check if Private Bytes/Bytes in all heaps/Virtual bytes increase at the same rate. If you don’t see growing of private bytes, so it means no any memory leak is happening!
Expert comments from Ekaterina — Genius person on this earth who helped us to understand this issue (God bless Ekaterina and Tess!):
Generation 0:
This counter displays the number of times the generation 0 objects (youngest; most recently allocated) are garbage collected (Gen 0 GC) since the start of the application.So when this number becomes higher over the time, it is OK. It just should grow at steady pace.
if you create a simple program, that will create in cycle a lot of large objects and put them to some archive (this will be not really a memory leak however you’ll get an OOM). In this case private bytes and bytes in all heaps will grow at the
same rate, and this can be treated as excessive memory consuming in managed code.
Also I noticed that when you have this memory problem, number of GC collection is also jumping and growing high very quickly – because new large portions of memory should be allocated fast, so I also pay attention to GC behavior.
Happy Coding! 🙂

VS 2010 Find and Replace – Dual Monitor issue

Challenge:

If you are using Visual Studio 2010 and if your Find and Replace dialog covers both monitors? Then this post is for you!

Solution:

Microsoft has accepted it as a bug —http://connect.microsoft.com/VisualStudio/feedback/details/612939/visual-studio-find-replace-dialog-box-spans-on-multiple-monitors-if-you-have-multi-monitor-desktop
Solution can be found from this blog : http://weblogs.asp.net/scottgu/archive/2010/08/29/patch-for-vs-2010-find-and-replace-dialog-growing.aspx
Happy Coding! 🙂

DataSet Vs Custom Entities

Challenge:

Dear Readers, Apologize for not sharing anything with you since so long. As was bit busy with projects. (But as I told in my earlier posts as well, It’s good to be busy. Because during your busy time you will learn a lot, and needless to say once you get time you will have a lot to share!)
This week, We were discussing what to use for our new project for passing data from one layer to another layer. DataSet Or Entities.
I’m big fan of Entities and Generics. But thought to do some research on it, before concluding anything. And my research revealed that I’m (I know you as well) not only one who is searching on this topic. Lot of people shared their views on web. But I filtered out few links, which I liked most (along-with the Excerpt which is important to read from that link)  and thought to share with you! So, here you go
http://forums.asp.net/t/1129497.aspx/1
“The problem with DataSets is that they tend to be pretty memory hungry. They also get a bit difficult to manage as your application gets larger. When you need more complex solutions, the initial effort that you put into getting custom classes up and running can pay off with shorter development cycles if you do it right. “
Going with custom classes is certainly better in many ways.
i) easier to add logic
ii) business validation is easier. This is tougher when using DataSet
iii) if you are using DataSet, even when the number of rows returned are small, the whole dataset has to be constructed which is quite an overhead. Custom classes are more light-weight
http://codebetter.com/jefferypalermo/2005/05/20/displaying-aggregates-dataset-vs-domain-object-performance-level-300/
“The page that used an array of custom domain objects to present a read-only display was 3.7% FASTER than the same functionality using a DataSet. “
http://blogs.msdn.com/b/reinouth/archive/2006/03/08/546510.aspx
“Now, amazingly, this has sparked somewhat of a religious war between various parties within the project. Just to be clear – I prefer custom objects – partly for their simplicity and readability”
“I agree with you on custom objects, you will have more control and better performance.”
http://blogs.msdn.com/b/irenak/archive/2006/02/27/539832.aspx

  • Memory consumption using Dataset = 290,436 (3.5 times larger than using Products class)
  • Memory consumption using array of objects = 140,028 (1.7 times larger than using Products class)
  • Memory consumption using Product class = 82,656 (BEST)

So, no matter how you turn it, strongly typed custom classes are your best bet in terms of memory consumption!
http://weblogs.asp.net/paolopia/articles/dsvscustomentities.aspx
2) BIZ and DAL are written by people different from the presentation layer group, so they have different knowledge about the data structures
http://www.4guysfromrolla.com/articles/051805-1.aspx
While DataSets are an easy way to return data, I think they are less than ideal for a couple of reasons. First, they add a lot of bloat to the returned XML payload since DataSets return not only the data they contain but also the data’s schema.
In my original article one of my main thrusts for not using DataSets was the performance disparity between DataSets and DataReaders. As I cited from A Speed Freak’s Guide to Retrieving Data in ADO.NET, when bringing in several hundred or thousands of records, a DataSet can take several seconds to be populated, where as a DataReader still boasts sub-second response times. Of course, these comparisons against several hundred to several thousand records are moot if you are working with a much smaller set of data, say just 10 to 50 records in total. For these smaller sized result sets, the DataSet will only cost you less than a second (although the DataReader still is, percentage-wise, much more efficient).
http://swap.wordpress.com/2007/07/10/dataset-vs-custom-entity/
Benefit with Custom Entity Classes
– Take advantage of OO techniques such as inheritance and encapsulation
– You can add custom behavior
– Object-Relational Mapping
– Mapping Custom Collections
– Managing Relationships between two entities in Object oriented way
http://stackoverflow.com/questions/1679064/should-i-use-entity-framework-dataset-or-custom-classes
I would agree with Marc G. 100% – DataSets suck, especially in a WCF scenario (they add a lot of overhead for handling in-memory data manipulation) – don’t use those. They’re okay for beginners and two-tier desktop apps on a small-scale maybe – but I wouldn’t use them in a serious, professional app.
http://www.rosscode.com/blog/index.php?title=datasets_vs_custom_objects&more=1&c=1&tb=1&pb=1

Solution:

So, in summary, as per my understanding, performance, maintainability, and serialization point of view entities looks more promising than DataSet.
Few of my guidelines:
You should use DataSet when:
1. Project is small.
2. Only Single person is going to work on all layers.
3. Data size is small.
4. Application is not going to get changed in future. (Mainly Database structure).
5. You are not worried about Maintainability.
You should use Custom Entities when:
1. Project is big.
2. Different people will be working on different layers.
3. Data size is big.
4. Application is going to get changed in future. (Mainly Database structure).
5. You are worried about Maintainability.
6. If you love to follow OOPs concepts.
These all are my views, and they might look biased toward Entities. Because as i told earlier, I’m big fan of custom entities. But if you would like to use DataSet and have good reasons to use it. Don’t worry go for it!
Happy Coding! 🙂

Long-running processes and browser timeout issue (mainly Internet Explorer)?

Challenge:

This week we faced strange issue [Oh yes, Issues are always strange, that’s why we know them as an issue! :-)].
Basically we were running a long running operation on server and in between our browser displayed “Internet Explorer cannot display the webpage” page. (Needless to say, we are using Internet Explorer)  We checked at our server-side (logs, sql connection, web  server etc.) and everything was perfect! We were clueless whether our server operation got completed or not.
If you are also facing this same issue, then keep reading we have a solution for you!

Solution:

Okay, so we were clueless what to do? Then suddenly it stroked in my mind. As IE shown this error page, why not try the same process with Firefox? [So long back faced similar issue and tried with FF and it worked. But at that time never researched why it worked!]
And you guess what? It worked for us. i.e. the same process got completed without changing anything on server-side code!
Okay, so we were happy as our task got completed. But we were not sure why it worked. [And my colleague Muktesh asked me a question, why it worked?].
Really good question! Then I started my research and found something interesting to share with all of you! Really interesting to read here you go:
Following Stackoverflow thread has some good points on this:
http://stackoverflow.com/questions/633075/browser-timeouts-while-asp-net-application-keeps-running

CAUSE
By design, Internet Explorer imposes a time-out limit for the server to return data. The time-out limit is five minutes for versions 4.0 and 4.01 and is 60 minutes for versions 5.x, 6, and 7. As a result, Internet Explorer does not wait endlessly for the server to come back with data when the server has a problem.

Internet Explorer imposes a time-out limit for the server to return data. By default, the time-out limit is as follows:

Internet Explorer 4.0 and Internet Explorer 4.01 5 minutes
Internet Explorer 5.x and Internet Explorer 6.x 60 minutes
Internet Explorer 7 and Internet Explorer 8 60 minutes

When the server is experiencing a problem, Internet Explorer does not wait endlessly for the server to return data.
Source : http://support.microsoft.com/kb/181050
Proposed Solution: Found some good links which gives some solutions which you can try [Frankly, Haven’t tried them on my own, try at your own risk! — I strongly recommend to use Firefox]

http://intersoftpt.wordpress.com/2009/06/23/resolve-page-cannot-be-displayed-issue-in-ie8/
http://www.ehow.com/how_5943517_control-browser-timeouts-ie-7.html
Now, we know what’s wrong with IE? But now the second question comes up Why it works with Firefox? Don’t worry we have answer for this as well.
Currently, Firefox timeout is determined by the system-level connection establishment timeout [Source : http://kb.mozillazine.org/Network.http.connect.timeout]. It was earlier issue in Firefox as well and they fixed it – https://bugzilla.mozilla.org/show_bug.cgi?id=592284
If you would like to know what your System-level connection is, please refer : http://support.microsoft.com/default.aspx?scid=kb;en-us;314053 [Source: https://bugzilla.mozilla.org/show_bug.cgi?id=142326]

Summary : When you have long running operation running on server and would like to run it from browser and if browser is displaying client side error, Firefox is a good choice!

Other Resources:

http://stackoverflow.com/questions/1192375/timeout-behavior-of-different-browsers
Happy Long running operation! 🙂

Visual Studio 2010 with TortoiseSVN and AnkhSVN

Challenge:

Before couple of weeks, We switched from VS 2008 to VS 2010 and during that project the most time-consuming thing was deciding which TortoiseSVN and AnkhSVN version to use?
If you are also using TortoiseSVN and AnkhSVN with VS 2008 and planing to migrate over VS 2010 and not sure which TortoiseSVN and AnkhSVN Version to use? Then this post is for you!

Solution:

Below are the version which we finalized to use with VS 2010:

  • TortoiseSVN – Required version is TortoiseSVN-1.6.16.21511-win32-svn-1.6.17.msi (You can download it from here) [If you are using 64 bit, then please use 64 bit one!]
  • AnkhSVN  – Required version is AnkhSvn-2.1.10129.msi (You can download it from here)

Also, once you have installed it, you need to tell VS 2010 that your primary source control will be SVN and not TFS [By default it is TFS – and it’s obvious! :)]. How to do it? Steps are as below:
1. Open your VS 2010 Instance.
2. Go to Tools Menu and Select Options…
3. And do following settings:

That’s it!
Enjoy using VS 2010! 🙂

WCF Behavioral Contracts and Message Exchange Patterns

Challenge:

Architect was busy on other tasks, So, he was not able to share his WCF knowledge with you since last few days. He apologize for this!
Architect’s team liked his WCF Fundamentals notes and they requested him to share his all notes whatever he has related to WCF!
So, here’s the 3rd part (1st part, 2nd part) of WCF Story where our architect would like to share his WCF Behavioral Contracts and Message Exchange Patterns with you!

Solution:

Here’s the discussion between Architect and his team!
Contracts
Contract defines:

  • What service operations you are going to get?
  • How to format the messages you send to a given service.?
  • What will it do when it receives the messages?
  • What kind of response message you should expect in return, or if something goes wrong, what kind of fault does the service issue?

WCF Structures an overall contract by with its consumers by defining the following three core contracts:

  • Service Contract :- Defines which operations the service makes available to be invoked as request messages are sent to the service from the client.
  • Data Contract :- Defines the structure of the data included in the payloads of the messages flowing in and out of the service.
  • Message Contract :- Enables you to control the headers that appear in the messages and how the messages are structured.

Categorically there are two types of contracts:
1. Behavioral Contracts
2. Structural Contracts
Today we are going to delve in to first category — Behavioral contract
Behavioral Contracts

  • Tools to start defining WCF services.
  • It helps you to define how your service will behave (and in OOPs term we define class’s behavior using methods]

It focused on .NET attributes you need from System.ServiceModel namespace to specify the behavioral aspects of your WCF Service:

  • How the service behaves and what operations it exposes.
  • When the service might issue faults and what kind of faults it might issue.
  • What are the MEPs required to interact with the service? – Operation is request/response way, one way or duplex.

Basically there are 3 types of Behavioral contracts:

  1. ServiceContractAttribute
  2. OperationContractAttribute
  3. Fault Contracts

Let’s discuss them one by one.
ServiceContractAttribute
Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.

  • It describes the client-callable operations (functions) exposed by the service
  • It maps the interface and methods of your service to a platform-independent description
  • It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern
  • It is analogous to the element in WSDL

To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract.
Named parameter options:

Named Parameter Description
Name
•Specifies a different for the contract instead of the default,
which is simply the interface or class type name. This contract name will
appear in WSDL.
Namespace
•Specifies a target namespace in the WSDL for the service.
The default namespace is http://tempuri.org . It’s really good practice to provide
Namespace.

Just a note : Please note that there are other named parameters as well. But it has been omitted intentionally to make things simple.
[sourcecode language=”csharp”]
[ServiceContract(Name="CalculatorService",
Namespace="http://schemas.demo.com/2011/10/calc/")]
public interface ICalculator
{
[OperationContract]
double Add(double number1, double number2);
}
[/sourcecode]
TIP:

  1. Always use Namespace property to provide a URI that in some way uniquely identifies both your organization and the conceptual or business domain in which the service operates. W3C standard – year and month to differentiate versions of your service.
  2. Good practice to use the Name property to remove the leading I because I is more of a .NET idiom.

OperationContractAttribute

  • Can be applied only to methods
    Used to declare the method belonging to a Service contract.

Named parameter options:

Named Parameter Description
Name
•Specifies a different name for the operation instead of using the default
which is the method name.
IsOneWay
•Indicates whether the operation is one-way and has no reply.

Just a note : Please note that there are other named parameters as well. But it has been omitted intentionally to make things simple.
[sourcecode language=”csharp”]
[ServiceContract(Name="CalculatorService",
Namespace="http://schemas.demo.com/2011/10/calc/")]
public interface ICalculator
{
[OperationContract(Name=“AddMethod",
IsOneWay=true)]]
double Add(double number1, double number2);
}
[/sourcecode]
Fault Contracts

  • When something goes wrong – what to do? (When service issues some faults then what type of information should be issued)
  • Faults (SOAP Faults) Vs. Exceptions (Exceptions) : Faults and exceptions are not the same thing. Exceptions, as referred to here, are a .NET mechanism used to communicate problems encountered as a program executes. The .NET Lang. allows you to throw, catch/handle, and possibly ignore exceptions so that they can be further propagated up the call stack. At the same point they should be handled else .NET runtime will terminate that thread.
    Fault, refer to the SOAP fault mechanism for transferring error or fault conditions from a service. The SOAP specification includes definition for SOAP Faults. Issue faults in a standard way.
  • WCF FaultException Class :- Provides standard mechanism for translating between two world of .NET Exceptions and SOAP Faults – WCF serialized your exception in SOAP Fault.
  • FaultContractAttribute :- enables a service developer to declare which faults a given service might issue if things go wrong. It can be applied to operations only and also more than once if needed.

[sourcecode language=”csharp”]
// Service Contract
[OperationContract]
[FaultContract(typeof(string))]
double Divide(double numerator, double denominator);
// Service Implementation
public double Divide(double numerator, double denominator)
{
if (denominator == 0.0d)
{
string faultDetail = "cannot divide by zero";
throw new FaultException(faultDetail);
}
return numerator / denominator;
}
[/sourcecode]
Message Exchange Patterns (MEP)
MEPs describe the protocol of message exchanges a consumer must engage in to converse properly with the service. For instance, if a consumer sends a message, it needs to know whether it should expect a message back or whether simply sending the request is enough. Further, can the consumer expect unsolicited messages back from the service? WCF supports
the following three MEPs:
1. One-way

  • One-way operation can be enabled by setting IsOneWay property to true in Operation contract attribute.
  • It can’t be used in conjunction with Fault Contract – Because it needs two-way channel.  Also, One way is not really one way!

In One-Way operation mode, client will send a request to the server and does not care whether it is success or failure of service execution. There is no return from the server-side, it is one-way communication.
Client will be blocked only for a moment till it dispatches its call to service. If any exception thrown by service will not reach the server.
Client can continue to execute its statement, after making one-way call to server. There is no need to wait, till server execute. Sometime when one-way calls reach the service, they may not be dispatched all at once but may instead be queued up on the service side to be dispatched one at a time, according to the service’s configured concurrency mode behavior. If the number of queued messages has exceeded the queue’s capacity, the client will be blocked even if it’s issued a one-way call. However, once the call is queued, the client will be unblocked and can continue executing, while the service processes the operation in the background.
[sourcecode language=”csharp”]
[ServiceContract(Name = "PizzaService",
Namespace = "http://schemas.demo.com/2011/10/pizza/")]
public interface IPizzaService
{
[OperationContract(IsOneWay = true)]
void CancelPizza(int pizzaOrderNumber);
}
[/sourcecode]
2. Request / Response [Default Message exchange pattern]

By default all WCF will be operated in the Request-Response [IsOneWay property of OperationContractAttribute is false) mode. It means that, when client make a request to the WCF service and client will wait to get response from service (till receiveTimeout). After getting the response it will start executing the rest of the statement. If service doesn’t respond to the service within receiveTimeout, client will receive TimeOutException
Void method doesn’t mean OneWay. It can use Request/Response and it’s really good practice to use it because this MEP allows to receive faults.
3. Duplex
Duplex MEP is a two-way message channel whose usage might be applicable in following situation:

  • Consumer sends a message to the service to initiate longer-running processing and then subsequently requires notification back from the service, confirming the requested processing has been done.

Duplex MEP has following issues:

  • it’s problematic in real world because a service needs connection back to the client – Firewalls and NAT problems.
  • Not Scalable. – We want stateless.
  • You lose interoperability. Because to implement Duplex MEP we need to use Callback method in WCF. But what if client is JAVA – which doesn’t supports callback methods.
  • Threading problems.

In Short Duplex is Complex! – Avoid using it. Use it if you really need it! – Okay, then how to deal with above given situation without Duplex?
Stay tuned for next story! (Just a note : If you would like to get email update whenever new story get posted, please do subscribe using subscription form — given right side)
Happy WCF Programming! 🙂

WCF Fundamentals and Quick start

Challenge:

After receiving lot of appreciation and positive comments on my first WCF article Why we need Windows Communication Foundation? and suggestion from Manaday (Which was going back of my mind. But somehow I was not bringing it in implementation), Henceforth I am going to post full WCF Series based on last fictional story.
So, here’s the 2nd part of WCF Story where our architect would like to share his WCF Fundamentals with you!

Solution:

Architect was kind enough to share his WCF Fundamental notes what he created for his team with you! [We should be thankful to him :)]
WCF provides API for creating systems that send messages between clients and services. Which can be sent either Intranet or Internet over TCP,HTTP,MSMQ, Web Services etc. Also it’s Interoperable!

Following are most of the concepts and terms used in WCF:

  • Message: Self-contained packets of data that may consist of several parts including header and body. All parts of a message can be encrypted and digitally signed except for the header which must be in clear text.
  • Service: A software module (EXE or DLL) that provides 1 to n endpoints with each endpoint providing 1 to n service operations.
  • Endpoint: A single interface that is used to establish communications between clients and hosts. Each endpoint has its own address that is appended to the base address of the service, making it a unique entity. A WCF service is a collection of endpoints.
  • Binding: A set of properties that define how an endpoint communicates with the outside world. At the very least, the binding defines the transport (HTTP or TCP) that is necessary to communicate with the endpoint. A binding may also specify other details such as security or the message pattern used by the endpoint.
  • System-provided bindings: A collection of bindings that are optimized for certain scenarios. For example, WSHttpBinding is designed for interoperability with Web Services that implement various WS-* specifications.
  • Service Contract: The contract defines the name of the service, its namespace, and other global attributes. In practice, a contract is defined by creating an interface (interface in C#) and applying the [ServiceContract] attribute. The actual service code is the class that implements this interface.
  • Operation Contract: Given that a service contract is defined by creating an interface and annotating it with [ServiceContract], an operation contract is a member method of that interface that defines the return type and parameters of an operation. Such an interface method must be annotated with [OperationContract].
  • Data Contract: Data types used by a service must be described in metadata to enable clients to interoperate with the service. The descriptions of the data types are known as data contracts and the types may be used in any message (parameters or return types).
  • Service operation: A method that is implemented and exposed by a service for consumption by any client. If a service contract is defined by creating an interface, then a service operation is the class that implements this interface.The method may or may not return a value, and may or may not take any arguments. Note while a method invocation might appear as a single operation on the client, it can result in sending multiple messages to the service. For example, a method with two arguments called on a WCF client results in two messages sent to the service.
  • Host: A host is an application (typically .exe) that is used to control the lifetime of a service. A host can be a console, a Windows Service, a Window Activation Service (WAS) and Internet Information Service (IIS) among others. For IIS, you can set a virtual directory that contains the service assemblies and configuration file. When a message is received, IIS starts the service and control its lifetime. When a client (or clients) end(s) the session, IIS closes the application and releases it resources.
  • Behavior: A behavior is a type (i.e., class) that augments the runtime functionality of a service. Service behaviors are enabled by applying a [ServiceBehavior] attribute to a service class and setting properties to enable various behaviors. Behaviors are used to control various runtime aspects of a service or endpoint. Behaviors are grouped according to scope: Common behaviors affect all endpoints, service behaviors affect only service-related aspects, and endpoint behaviors affect only endpoint-related properties. For example, an endpoint behavior may specify where and how to find a security credential.
  • Instancing: A service has an instancing model which controls how many instances of the service can run at one time. There are four instancing models: single, per call, per session, and shareable. The first two are similar in concepts to the Singleton and Single Call SAOs in .NET Remoting. Instancing is a behavior and and as such it is specified as part of the [ServiceBehavior] attribute as follows: [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)].
  • Client Application: A program that exchanges messages with one or more endpoints. The client application typically creates a WCF Client Object and then calling methods on this proxy object.
  • Channel: This is the transport connection between a client application and an endpoint in a service. A client uses a transport (TCP, HTTP, etc.) and an address to construct a channel to a specific endpoint.
  • WCF Client Object: This a client-side construct that encapsulates service operations as methods, in other words, a WCF Client Object is a proxy to the service methods. Note that any application can host a WCF Client Object, even an application hosting a service. Therefore, it is possible to create a service that includes and uses proxies to other services. These proxies are typically generated using the svcutil.exe command-line utility.
  • Metadata: data that is generated by the svcutil.exe command-line utility. This data includes:
  1. XML schema that define the data contract of the service.
  2. WSDL to describe the methods of the service.
  3. Application configuration files.
  • Metadata exchange point: An endpoint with its own address that is used to publish metadata.
  • Security: Security in WCF includes encryption of messages, integrity of messages, authentication and authorization. These functions can be provided by either using existing security mechanisms such as HTTPS or by implementing one or more of the various WS-* security specifications.
  • Message pattern: The message pattern determines the relationship and direction of messages between the client and the service. The most basic pattern is the one-shot (or one way) pattern is which a message is sent to the server but not response is expected. The most complex pattern is a dual HTTP pattern where two HTTP channels are constructed between a client and a service, with both sides invoking operations on each other.
  • Reliable messaging: The assurance that a message is received only once and in the order in which it was sent.
  • Sessions: A session is used to establish communication between a client and a service in which all messages are tagged with an ID that identifies the sessions. If a session is interrupted, it can be restarted with the session ID. If a service contract supports a session, then you will need to use Instancing to determine how the class that implements the service contract behaves during the session. See the Duplex Message Pattern example in Designing Contracts chapter.

Basic WCF Programming Lifecycle

Here are the basic steps of WCF Programming Lifecycle – Order matters!

  1. Define the service contract. A service contract specifies the signature of a service, the data it exchanges, and other contractually required data.
  2. Implement the contract. To implement a service contract, create the class that implements the contract and specify custom behaviors that the runtime should have.
  3. Configure the service by specifying endpoint information and other behavior information.
  4. Host the service in an application.
  5. Build a client application.

Just a note : Although the topics in this section follow this order, some scenarios do not start at the beginning. For example, if you want to build a client for a pre-existing service, you start at step 5. Or if you are building a service that others will use, you may skip step 5.

WCF Quick start

Following steps will help you to create your first WCF service (In this example we are going to create two console applications one console application will be hosting the service and second one will be consuming the service):
Step 1 : Define a Windows Communication Foundation Service Contract : When creating a basic WCF service, the first task is to create the contract for the service that is shared with the outside world that describes how to communicate with the service. This contract specifies the collection and structure of messages required to access the operations offered by the service. This is done by creating an interface that defines the input and output types, which apply the ServiceContractAttribute to the interface and OperationContractAttribute to the methods that you want to expose.

NOTE : We need to add reference to System.ServiceModel

The service contract that is used here employees a request-reply message exchange pattern by default that is not explicitly specified. You can specify this and other message exchange patterns for client-service communications by setting properties of the OperationContractAttribute and ServiceContractAttribute in the contract.
Example:
[sourcecode language=”csharp”]
namespace WCFService
{
[ServiceContract]
public interface ICalculator
{
// It will be exposed to clients
[OperationContract]
double Add(double number1, double number2);
}
}
[/sourcecode]
Step 2 : Implement a Windows Communication Foundation Service Contract : Implement the Service Contract defined in step1.
Example:
[sourcecode language=”csharp”]
namespace WCFService
{
public class CalculatorService : ICalculator
{
#region ICalculator Members
public double Add(double number1, double number2)
{
Console.WriteLine("Service called at : {0}", DateTime.Now.ToString());
Console.WriteLine(@"Calculator Service got called
with two parameters {0} and {1}",
number1,
number2);
double result = number1 + number2;
Console.WriteLine("The result is : {0}",result);
Console.WriteLine("——————————-");
return result;
}
#endregion
}
}
[/sourcecode]
Step 3 : Run a Basic Windows Communication Foundation Service :
This topic describes how to run a basic Windows Communication Foundation (WCF) service. This procedure consists of the following steps:

  • Create a base address for the service.
  •  Create a service host for the service.
  •  Enable metadata exchange.
  •  Open the service host.

Example:
[sourcecode language=”csharp”]
namespace WCFService
{
class Program
{
static void Main(string[] args)
{
// Address
Uri baseAddress =
new Uri("http://localhost:8080/WCFService/Service");
// Host
ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService),
baseAddress);
try
{
// Binding, Contract
serviceHost.AddServiceEndpoint(typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");
// Metadatabehavior
// WSDL information we need to expose to clients
// it works on HTTP GET Method
ServiceMetadataBehavior serviceMetadatabehavior
= new ServiceMetadataBehavior();
serviceMetadatabehavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(serviceMetadatabehavior);
// Start the service
serviceHost.Open();
Console.WriteLine("Service started : {0}",
DateTime.Now.ToString());
// Stop the service
Console.WriteLine("Press ENTER to shut down the service");
Console.ReadLine();
serviceHost.Close();
Console.WriteLine(@"Service shutdown successfully.
Thank you for using our service!");
}
catch (CommunicationException ce)
{
Console.WriteLine(ce.Message);
serviceHost.Abort();
}
}
}
}
[/sourcecode]
Step 4: Create a Windows Communication Foundation Client : This topic describes how to retrieve metadata from a WCF service and use it to create a proxy that can access the service. This task is most easily completed by using the ServiceModel Metadata Utility Tool (Svcutil.exe) provided by WCF. This tool obtains the metadata from the service and generates a managed source code file for a client proxy in the language you have chosen. In addition to creating the client proxy, the tool also creates the configuration file for the client that enables the client application to connect to the service at one of its endpoints.

svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config

By default, the client proxy code is generated in a file named after the service (in this case, for example, CalculatorService.cs or CalculatorService.vb where the extension is appropriate to the programming language: .vb for Visual Basic or .cs for C#). The /out switch used changes the name of the client proxy file to “generatedProxy.cs”. The /config switch used changes the name of the client configuration file from the default “output.config” to “app.config”.

Just a note : If you would like to test your service quickly. You can use WCFTestClient.exe utility which will help you to test your service without writing a single line of code for your WCF Client!


Step 5: Configure a Basic Windows Communication Foundation Client : This topic adds the client configuration file that was generated using the Service Model Metadata Utility (Svcutil.exe) to the client project and explicates the contents of the client configuration elements. Configuring the client consists of specifying the endpoint that the client uses to access the service. An endpoint has an address, a binding and a contract, and each of these must be specified in the process of configuring the client.
svcutil.exe will provide you the default configuration automatically.
Step 6 : Use a Windows Communication Foundation Client : Once a Windows Communication Foundation (WCF) proxy has been created and configured, a client instance can be created and the client application can be compiled and used to communicate with the WCF service. This topic describes procedures for creating and using a WCF client. This procedure does three things: creates a WCF client, calls the service operations from the generated proxy, and closes the client once the operation call is completed.
Now, copy paste the svcutil generated files (CS and Config file) within your console project and then you can call your service from your client application as shown below:
Example:
[sourcecode language=”csharp”]
namespace WCFClient
{
class Program
{
static void Main(string[] args)
{
CalculatorClient calculatorClient = new CalculatorClient();
Console.WriteLine("Proxy calling service…");
Console.WriteLine(calculatorClient.Add(10, 20));
// Good practice
calculatorClient.Close();
Console.WriteLine("closed!");
}
}
}
[/sourcecode]
And then first start your service (your service must be in running state before you run the client) and then run the client. And this is how it will look like:

Resources

Mike Taulty’s Video : Windows Communication Foundation:” Hello World”:
http://go.microsoft.com/?linkid=4091084
http://download.microsoft.com/download/f/b/3/fb3c2a8b-604e-479b-ab22-e31dc094a40d/WCF_Hello_World.zip
Stay tuned for next story! (Just a note : If you would like to get email update whenever new story get posted, please do subscribe using subscription form — given right side) 🙂
Happy WCF Programming! 🙂