Quantcast
Saturday 4 december 2010 6 04 /12 /Dec /2010 14:21

4 Steps to Enable Instrumentation in WCF


Get Interview tutorials and videos on .NET 3.5, 4.0, WCF,Instrumentation,.NET, SQL Server, CAS, Security, WCF, SharePoint, Azure, OOPS and many more on www.questpond.com

 

Table of Contents

Introduction and Goal

Many times, we would like to monitor events of WCF application in production environment. We would like to monitor events like errors, security audits, performance, etc. This can be achieved by extending the ASP.NET health monitoring system in WCF. The health monitoring system is also termed as instrumentation.

The Event Provider Model

Instrumentation is provided using the event provider model. Events are notifications which you receive from the WCF application which can be a security event like password change, UI click events, or exception events like application level errors. These events are captured by the provider and routed to some source like event viewer, SQL Server, etc.






Both events and provider are specified in the web.config file. The eventMappings element is where you specify your provider and ‘rules’ elements help you tie up the event with the provider.

<healthMonitoring>
<eventMappings>...</eventMappings>
<rules>...</rules>

</healthMonitoring>

What Will We Do in this Article?

In this article, we will create a simple audit function which will help us to track all calls made to the WCF service in to event viewer. So any calls by the WCF client will be tracked and audited in to the event viewer. For every call, we will be tracking details like number of threads, working sets, app domains, when the message was created and when was it raised. Below is the snippet for the same which will be tracked in the event viewer.

***************start health monitoring event*******************
message created at:Event Created at :3/14/2010 11:32:37 AM
message raised at:Event Created at :3/14/2010 11:32:37 AM
Heap size 3480664
Number of threads 19
Number of Working sets 32165888
Number of domains 1
Request rejected 0******************End Health Monitoring event*********************


Step 1: Create the Main Event Class

The first step is to create a class which will help us to track the calls made to the WCF service. This class needs to be inherited from WebAuditEvent class. This class helps us to track audit events, generate information about security related operation and provide both success and failure audit events.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Management;

namespace healthmonitering
{
    public class CustomAudit:WebAuditEvent
    {
    }
}

In the same class, let's add 3 private fields, msgcreated , msgraised and WebProcessStatistics. By using msgcreated and msgraised, we can track at what time event is created and raised. WebProcessStatistics will provide information for assessing the health of a running process.

private string msgcreated = string.Empty;
private string msgraised = string.Empty;
private static WebProcessStatistics processStatistics;

Implement the necessary public constructors that call the protected equivalents in the parent WebAuditEvent class. Base keyword is used to access the member of base class within the derived class as shown in the below code snippet. Note that we have created the WebProcessStatistics object and set it to the private member variable.

public CustomAudit(string message, object eventsource, int eventcode)
       : base(message, eventsource, eventcode)
{
    msgcreated = string.Format("Event Created at :{0}", EventTime.ToString());
    processStatistics = new WebProcessStatistics();
} 

In both the constructors, we are checking at what time event is created. Now override the Raise method as shown in the below code snippet.

public override void Raise()
{
    msgraised = string.Format("Event Created at :{0}", EventTime.ToString());
    base.Raise();
}

Override the FormatCustomEventDetails method with the message we want to log in the event viewer. Note, we have used WebProcessStatistics to get information like heap size, number of threads, number of working sets, number of domains and Request rejected.

public override void FormatCustomEventDetails(WebEventFormatter formatter)
{
    formatter.AppendLine("");
    formatter.IndentationLevel += 1;
    formatter.AppendLine
        ("***************start health monitoring event*******************");
    formatter.AppendLine(string.Format("message created at:{0}",msgcreated));
    formatter.AppendLine(string.Format("message raised at:{0}", msgraised));
    formatter.AppendLine(string.Format
        ("Heap size {0}", processStatistics.ManagedHeapSize.ToString()));
    formatter.AppendLine(string.Format
        ("Number of threads {0}", processStatistics.ThreadCount.ToString()));
    formatter.AppendLine(string.Format
        ("Number of Working sets {0}", processStatistics.WorkingSet.ToString()));
    formatter.AppendLine(string.Format
        ("Number of domains {0}", processStatistics.AppDomainCount.ToString()));
    formatter.AppendLine(string.Format
        ("Request rejected {0}", processStatistics.RequestsRejected.ToString())); ;
    formatter.AppendLine
        ("******************End Health Monitoring event*********************");
    formatter.IndentationLevel -= 1;
}

In the Raise method, we are checking at what time event raised and in FormatCustomEventDetails, we are appending the result in the audit event.

Step 2: Create the WCF Service and Change web.config

namespace WcfService3
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string Audit();
    }
}

In the Audit function, we are going to implement our health monitoring functionality in health operation contract.

In the Service1.svc.cs class, implement the Audit function by creating the CustomAudit object and calling the Raise function as shown in the below code snippet:

public class Service1 : IService1
{
    public string Audit()
    {
        Healthmonitering.CustomAudit webevent = 
                new Healthmonitering.CustomAudit("Some on called", 
                    this, WebEventCodes.WebExtendedBase + 1);
        webevent.Raise();
        return "Event Audited";
    }
}

In the constructor, we are sending message, event source, and event code as a parameter.

Now go to the web.config and under system.web element, add the healthmonitoring tag. Specify CustomAudit class in the eventMappinga element and mapping of the class with event viewer in the rules element tag as shown in the below code snippet.

<healthMonitoring>
<eventMappings>
<add name="healthmonitering" type="Healthmonitering.CustomAudit "/>
</eventMappings>
<rules>
<add name="healthmonitering" eventName="healthmonitering" 
        provider="EventLogProvider" minInterval="00:00:01"/>

</rules>
</healthMonitoring>


Step 3: Consume the WCF Service in the ASPX Client

So let’s add an ASPX button, consume the client service and call the Audit function in the button click event as shown in the below code snippets:

<asp:Button ID="Button1" runat="server" Text="Invoke" onclick="Button1_Click" />

Now in the button click event, write these lines:

protected void Button1_Click(object sender, EventArgs e)
{
    ServiceReference1.Service1Client proxy = 
                new WebApplication1.ServiceReference1.Service1Client();
    string result = proxy.Audit();
    Response.Write(result);
}

Here we are creating the proxy, invoking the Audit method and displaying the result of the Audit method.

Step 4: See the Audit Data in Event Viewer

Run the web application which is consuming the WCF service and press the button to invoke the WCF audit function. The Audit function internally calls the Raise event which logs the message in an event viewer. So go to Start->run->type eventvwr. It contains information like Heap size, Number of threads, Number of Working sets, Number of domains and Request rejected as shown in the below figure:


 

By Shivprasad koirala
Enter comment - View the 0 comments
Saturday 4 december 2010 6 04 /12 /Dec /2010 14:05

 

3 ways to do WCF instance management (Per call, Per session and Single)

Get Interview tutorials and videos on .NET 3.5, 4.0, WCF, Management, SQL Server, CAS, Security, WCF, SharePoint, Azure, OOPS and many more on www.questpond.com

Introduction
WCF service object instancing basics
Per Call instance mode
How to implement WCF per call instancing?
Per session Instance mode
How to implement per session Instancing?
Single Instance mode
How to implement Single Instance mode?
When should you use per call, per session and single mode?
Per call
Per session
Single
References
Source code

Introduction

Many times we would like to control the way WCF service objects are instantiated on WCF server. You would like to control how long the WCF instances should be residing on the server.


WCF framework has provided 3 ways by which we can control the WCF instance creation. In this article we will first try to understand those 3 ways of WCF service instance control with simple code samples of how to achieve them. Finally we will compare when to use under what situations.

WCF service object instancing basics

In a normal WCF request and response communication following sequence of actions takes place:-
• WCF client makes a request to WCF service object.
• WCF service object is instantiated.
• WCF service instance serves the request and sends the response to the WCF client.
Following is the pictorial representation of how WCF request and response work.





Following are different ways by which you would like to create WCF instances:-


• You would like to create new WCF service instance on every WCF client method call.
• Only one WCF service instance should be created for every WCF client session.
• Only one global WCF service instance should be created for all WCF clients.
To meet the above scenarios WCF has provided 3 ways by which you can control WCF service instances:-
• Per Call
• Per session
• Single instance

Per Call instance mode

When we configure WCF service as per call, new service instances are created for every method call you make via WCF proxy client. Below image shows the same in a pictorial format:-

• WCF client makes first method call (method call 1).
• New WCF service instance is created on the server for this method call.
• WCF service serves the request and sends response and the WCF instance is destroyed and given to garbage collector for clean up.
• Now let’s say WCF client makes a second method call, again a new instance is created, request is served and the WCF instance is destroyed.

In other words for every WCF client method call one WCF service instance is created and destroyed once the request is served.






How to implement WCF per call instancing?


In order to specify instancing mode we need to provide ‘InstanceContextMode’ value in the ‘ServiceBehavior’ attribute as shown below. This attribute we need to specify on the ‘Service’ class. In the below code snippet we have specified ‘intCounter’ as a class level variable as shown below and the class counter is incremented by one when method ‘Increment’ is called.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Percall)] 
public class Service : IService
{
private int intCounter;

public int Increment()
{
intCounter++
return intCounter;
}
}

 

At the client we have consumed the WCF client and we have called ‘Increment’ method twice.

ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 
MessageBox.Show(obj.Increment().ToString());
MessageBox.Show(obj.Increment().ToString());

 

Even though we have called the ‘Increment’ method twice we get value ‘1’. In other words the WCF service instance is created for every method call made to the WCF service instance so the value will always be one.



.




Per session Instance mode

Many times we would like to maintain state between method calls or for a particular session. For those kind of scenarios we will need to configure the service as per session. In per session only one instance of WCF service object is created for a session interaction. Below figure explains the same in a pictorial format.

• Client creates the proxy of WCF service and makes method calls.
• One WCF service instance is created which serves the method response.
• Client makes one more method call in the same session.
• The same WCF service instance serves the method call.
• When client finishes his activity the WCF instance is destroyed and served to garbage collector for clean up.







How to implement per session Instancing?


To configure service as per session we need to configure ‘ServiceBehavior’ attribute with ‘PerSession’ value in the ‘InstanceContextMode’ object.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
public class Service : IService
{
private int intCounter;
public int Increment()
{
intCounter++
return intCounter;
}}

 

At the client side when we run the below client code. You should see the value as ‘2’ after the final client code is executed. We have called the method twice so the value will be seen as two.

ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); 
MessageBox.Show(obj.Increment().ToString());
MessageBox.Show(obj.Increment().ToString());








Single Instance mode

Many times we would like to create one global WCF instance for all WCF clients. To create one single instance of WCF service we need to configure the WCF service as ‘Single’ instance mode. Below is a simple pictorial notation of how single instance mode will operate:-

• WCF client 1 requests a method call on WCF service.
• WCF service instance is created and the request is served. WCF service instance is not destroyed the service instance is persisted to server other requests.
• Now let’s say some other WCF client i.e. client 2 requests a method call.
• The same WCF instance which was created by WCF client 1 is used to serve the request of WCF client 2. In other words only one global WCF server service instance is created to serve all client requests.







How to implement Single Instance mode?

In order to create a single instance of WCF service we need to specify the ‘InstanceContextMode’ as ‘Single’.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 
public class Service : IService
{
}

If you call the WCF from different client you will see the counter keep incrementing. The counter has become a global variable.






When should you use per call, per session and single mode?

Per call


• You want a stateless services
• Your service hold intensive resources like connection object and huge memory objects.
• Scalability is a prime requirement. You would like to have scale out architecture.
• Your WCF functions are called in a single threaded model.

Per session


• You want to maintain states between WCF calls.
• You want ok with a Scale up architecture.
• Light resource references

 

Single


• You want share global data through your WCF service.
• Scalability is not a concern.

Source code

You can download source code for this tutorial from here http://www.codeproject.com/KB/WCF/WCFInstance/WCF_Instancing.zip

By Shivprasad koirala
Enter comment - View the 0 comments
Friday 3 december 2010 5 03 /12 /Dec /2010 14:09

34 important ASP.NET Interview questions

Below are 34 important ASP.NET interview questions which repeat again and again in .NET Interviews .

  1. What is an application object?

  2. what is the difference between Cache object and application object?

  3. How can get access to cache object?

  4. What are dependencies in cache and types of dependencies?

  5. Can you show a simple code showing file dependency in cache?

  6. What is Cache Callback in Cache?

  7. What is scavenging?

  8. What are different types of caching using cache object of ASP.NET?

  9. How can you cache different version of same page using ASP.NET cache object?

  10. How will implement Page Fragment Caching?

  11. Can you compare ASP.NET sessions with classic ASP?

  12. Which are the various modes of storing ASP.NET session?

  13. Is Session_End event supported in all session modes? 106

  14. What are the steps to configure StateServer Mode?

  15. What are the steps to configure SQLServer mode?

  16. Where do you specify session state mode in ASP.NET?

  17. What are the other ways you can maintain state?

  18. What are benefits and Limitation of using Hidden fields?

  19. What is ViewState?

  20. Does the performance for viewstate vary according to User controls?

  21. What are benefits and Limitation of using Viewstate for state management?

  22. How can you use Hidden frames to cache client data ?

  23. What are benefits and limitations of using Hidden frames?

  24. What are benefits and limitations of using Cookies? 109

  25. What is Query String and What are benefits and limitations of using Query Strings?

  26. What is Absolute and Sliding expiration?

  27. What is cross page posting?

  28. How do we access viewstate value of this page in the next page ?

  29. Can we post and access view state in another application?

  30. What is SQL Cache Dependency in ASP.NET 2.0?

  31. How do we enable SQL Cache Dependency in ASP.NET 2.0?

  32. What is Post Cache substitution?

  33. Why do we need methods to be static for Post Cache substitution?

  34. Can you explain page life cycle ?

By Shivprasad koirala
Enter comment - View the 0 comments
Wednesday 1 december 2010 3 01 /12 /Dec /2010 14:11

C# and .NET OOP (Object oriented  programming) interview questions - Abstract classes and interfaces.


I have yet to remember a .NET interviewer who never asked about abstract classes ,  interfaces and object oriented interview questions . I am putting forward questions which comes around abstract classes and interfaces again and again...Hope every one benefits.

Normally the C# interviewer starts with.....

What is abstract class ?

Abstract class is a base class or a parent class. Abstract classes can  have empty abstract methods or it can have implemented methods which can be overridden by child classes.

The next question i expected was on interfaces and yes there it comes.

What are interfaces?

Interface is a contract class with empty methods , properties and functions. Any class which implements the interface has to compulsory implement all the empty methods , functions and properties of the interface.

Now the 1000% sure question was bound to come difference between them...


What's the difference between abstract class and interface?

There are many differences, below are some key two differences :-

  • Abstract class are base class or parent class while interfaces are contracts.
  • Abstract class can have some implemented methods and functions while interfaces methods and functions are completely empty.
  • Abstract classes are inherited while interfaces are implemented.
  • Abstract classes are used when we want to increase reusability in inheritance while interfaces are used to force a contract.

Can we create a object of abstract class or interface?

No we can not.

Now the practical question..

In what scenarios will you use a abstract class and in what scenarios will you use a  interface?

If you want to increase reusability in inheritance then abstract classes are good. If you want implement or force some methods across classes must be for uniformity you can use a interface. So to increase  reusability via inheritance use abstract class as it is nothing but a base class and to force methods use interfaces.

Really friends having C#  experience is one thing and cracking  Dot net  and C# interviews is a different ball game all together .

By Shivprasad koirala
Enter comment - View the 0 comments
Tuesday 30 november 2010 2 30 /11 /Nov /2010 20:19

Garbage Collection in .Net

.Net Framework's -Memory Management Garbage Collector which manages allocation and release of memory from application.Now developers no need to worry about memory allocated for each object which is created on application . garbage collector automatically manages memory on application

Garbage Collection Interview Questions

I would like share this horrible experience which I faced in one of the big IT multinational company. Even though I have 8 years of experience, I flunked very badly and I flunked due to 1 topic "Garbage collector". I hope the below discussion will help some one down the line when facing c sharp and dot net interviews. I just hope dot net interviews get more matured down the line and ask practical questions rather than asking questions which we do not use on day to day to basis.

The interviewer started with a basic question which I knew pretty well

.NET Interview Questions and answers on Garbage Collector

What is a garbage collector?

Garbage collector is a background process which checks for unused objects in the application and cleans them up.

After that answer my guess was the interviewer will not probe more....but fate turned me down , came the bouncer.

What are generations in garbage collector?

Generation define the age of the object.

Well i did not answer the question , i have just written down by searching in google....

How many types of Generations are there in GC garbage collector?

There are 3 generations gen 0 , gen 1 and gen 2.

Then came a solid tweak questions which i just slipped by saying Yes...

Does garbage collector clean unmanaged objects ?

No.

Then came the terror question...which i never knew...

When we define clean up destructor , how does it affect garbage collector?

If you define clean up in destructor garbage collector will take more time to clean up the objects and more and more objects are created in Gen 2..

How can we overcome the destructor problem ?

By implementing "Idisposable" interface.

The above question was tricky , you can search in google for finalize and dispose patterns.

Where do we normally put unmanaged code clean up?.

In finalize a.k.a destructor.

One thing i learnt from this interview experience is one thing but we also should know core concepts in detail to crack Dot net interviews .

By ShivPrasad Koirala

For more Queries please visit : http://www.questpond.com

By Shivprasad koirala
Enter comment - View the 0 comments

Important .NET and C# interview questions and answers

.Net interview questions: - Explain why it is not preferred to use finalize for clean up?

.Net interview questions: - Show the five levels in CMMI?

.NET interview questions and answers: – Which is the best place to store connection string in .NET projects?

C# interview questions and answers: – Explain the use of Icomparable in c#?

C# interview questions: - How can we check which rows have changed since dataset was loaded?

C# interview questions and answers: - Can you write a simple c# code to display Fibonacci series?

.NET interview questions and answers: - What is difference betweenIcomparable VS Icomparer ?

C# and .NET interview question: -What is short circuiting in C#?

C# and .NET interview question: - What are symmetric and asymmetric algorithms?

Important c# and .NET interview question on object pooling and Gridview events?

.NETinterview questions and answers: – Will the finally run in this code?

How to prepare for c# and .NETinterviews?

C# and .NET Interview questions: - What is Thread.Join () in threading?

.NET Interview questions and answers: -What is serialization and deserialization in .NET?

C# and .NET interview question: - What is hashing?

c# and .NET interview question:- what connects dataset and data source ?

.Net interview questions and answers: - What is the difference between “Web.config” and “Machine.Config”?

.NET interview questions and answers: - What is TPL?

.NET Interview questions and answers: -What are different access modifiers?

.NET and c# Interview Question and answers: – If we want to update interface with new methods, what is the best practice?

 MVC ( Model view controller) interview questions and answers      

ASP.NET Application and Page Life Cycle 

12 Important FAQ’s on VSTS Testing (Unit testing, load testing, automated testing, database testing and code coverage) 

 6 important use of Partial/Mock testing

6 important uses of Delegates and Events

7 Simple Steps to Run Your First Azure Blob Program

8 Steps to Create Workflows using SharePoint Designer

Azure FAQ Part 1

C# Code Reviews using StyleCop – Detailed Article

Four real world uses of Partial classes and Partial methods

SharePoint Quick Start FAQ Part 1

SharePoint Quick Start FAQ Part 6 – Workflows, Workflows and Workflows

SharePoint Workflow Basics

 

 

 

 

. NET and C# interview questions videos

MVC Interview questions videos

Viewdata,viewbag,tempdata

 

 

MVC Interview questions and answers Article

 

(Model view controller)MVC Interview questions and answers

MVC interview questions with answers video: – What is Web API how to implement the same?

 

 

WCF Interview questions videos

 

overloading in WCF

WCF fault exceptions ?

 

C# Interview Questions & Answers Article

 

12 Important FAQ’s on VSTS Testing (Unit testing, load testing, automated testing, database testing and code coverage)

6 important use of Partial/Mock testing

6 important uses of Delegates and Events

7 Simple Steps to Run Your First Azure Blob Program

8 Steps to Create Workflows using SharePoint Designer

Azure FAQ Part 1

C# Code Reviews using StyleCop – Detailed Article

Four real world uses of Partial classes and Partial methods

SharePoint Quick Start FAQ Part 1

SharePoint Quick Start FAQ Part 6 – Workflows, Workflows and Workflows

SharePoint Workflow Basics

C# (Csharp) interview questions and answers: – What are indexers in .NET?

C# OOP interview questions and answers: - I do not want to implement all the interface methods?

C# design pattern (UNIT of Work Design Pattern)

C# design pattern interview questions – What is Dependency injection ?

C# interview questions and answers: - What is the difference between “==” and .Equals()?

How questions are asked in c# interviews?

C# design pattern interview question: - DI vs IOC

8 important C# Interview questions on IL code, JIT, CLR, CTS, CLS and CAS

What is the difference between Reflection and Dynamic in C#?

Algorithm Interview Questions

Algorithm interview questions and answers: – Can you write code for bubble sort algorithm?

Algorithm interview questions and answers: – What is inserted sort algorithm?

ASP.NET Interview Questions & Answers Article







 

SQL Server Interview Questions & Answers Article

 

SQL Server Interview Questions & Answers Article

SQL Server interview questions and answers: - What is HID data type in SQL Server ?

 

.NET INTERVIEW QUESTIONS & ANSWERS ARTICLE

 

.NET interview questions and answers: - How to reverse a string in .NET ( DotNet)?

.NET interview questions and answers: - What is the use of Click Once?

.NET interview questions and answers: - Will the below codes create new instances?

C# and .NET interview questions with answers – What is Nuget?

Dependency injection (DI) VS Inversion of Control (IOC)

.NET interview questions with answers: - What is the difference between Reflection and Dynamic?


WPF INTERVIEW QUESTIONS & ANSWERS ARTICLE

 

6 important WPF and Silverlight Multi-threading interview questions with answers


Create your blog for free on over-blog.com - Contact - Terms of Service - Earn Royalties - Report abuse - Most commented articles