WCF # 22 Error Handling , Error Logging , ErrorHandlerAttribute using WCF Extensions
In this article , we will see how to write the generic error handler in the WCF which is used for custom error logging and in returning the appropriate fault message to the user if any error comes while processing the user request.
IErrorHandler interface is used for error handling and logging in the WCF.
- public interface IErrorHandler
- {
- bool HandleError(Exception error);
- void ProvideFault(Exception error, MessageVersion version, ref Message fault);
- }
HandleError method logs an error.
It returns true if the error is considered as already handled other wise false will be returned and error will be handled as usual.
ProvideFault method can only be used in DUPLEX communication.
This method allows to create the custom FaultException
This method accepts the parameter error which is of type Exception , this exception is the exception occurs during the execution of a service method.
Following is the code for IErrorHandler interface Implementation.
- [AttributeUsage(AttributeTargets.Class)]
- public class ErrorHandlerBehaviorAttribute : Attribute, IErrorHandler, IServiceBehavior
- {
- //IErrorHandler Implementation
- bool IErrorHandler.HandleError(Exception error)
- {
- try
- {
- //Write your code here for Logging the errors
- }
- catch { }
- return false;
- }
- void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
- {
- if (OperationContext.Current != null && OperationContext.Current.IncomingMessageHeaders != null)
- {
- //Write code here for modifying the Fault Messages to be returned to the USER
- }
- }
- //IServiceBehavior implementation"
- void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase host)
- {
- //attach the object implementing the IErrorHandler interface(this class itself) to each ChannelDisp
- foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
- {
- dispatcher.ErrorHandlers.Add(this);
- }
- }
- void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase host)
- {
- //implementation not required at present. Can be added later if required.
- }
- void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase host,
- Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
- {
- //implementation not required at present. Can be added later if required.
- }
- }
Brief Summary for the code above
1) It has been derived from the Attribute class so that it can be used as an attribute over the service class directly.
2)It has been also derived from IServiceBehaviour interface which is used to apply this ErrorHandler behavior to the channel dispatcher in the Service
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase host)
{
//attach the object implementing the IErrorHandler interface(this class itself) to each ChannelDispatcher
foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
{
dispatcher.ErrorHandlers.Add(this);
}
}
Now our ErrorHandlerBehavior attribute is ready to use on any WCF service.The benefit of creating the atttribute for this behavior is we can directly use this in the c# code on the service class as below
- [ErrorHandlerBehavior()]
- public class Service : IService
- {
- //Implement your IService methods here
- }
Thanks
Ganesh D
LINQ # 10 – Join with multiple columns of the same table using Linq
While using LINQ as Linq to Sql queries , We often come across a scenario where we have to join the same table for multiple columns in it.
Following example illustrates how we can achieve it in Linq :
We have two tables Table1 and Table2 with columns column1 and column2 and we have to join the Table1 with Table2 for both the columns.
We can achieve it using AnonymousType introduced by Microsoft.
Following is the code used for it
- var lstDetails=(from tbl1 in Table1
- join tbl2 in Table2
- on new {tbl1.column1,tbl1.column2}
- equals new {tbl2.column1,tbl2.column2}
- select tbl1 );
Thanks, Ganesh
ASP.NET – Call Synchronous Method Asynchronously using C# ,.net (Fire and forget pattern)
Hi Friends,
Many times we come across a situation when we need to call a method asynchronously and don’t want to wait till it completes its execution.
- class Program
- {
- public delegate void AsyncMethodCaller(int Application_Type_Id);
- public static void AsynchronousMethod(int Application_Type_Id)
- {
- Console.WriteLine("My Application_Id is {0}",Application_Type_Id);
- }
- static void Main()
- {
- AsyncMethodCaller caller = new AsyncMethodCaller(AsynchronousMethod);
- IAsyncResult result = caller.BeginInvoke(1, null, null);
- Console.Read();
- }
- }
For Example In the above code, if I want to call AsynchronousMethod() and not wait for it to finish executing? In fact, to make things interesting, what if I didn’t care when it is finished?
Let’s say, I just wanted to call AsynchronousMethod() without waiting for any of the function calls to complete. Basically, doing something called Fire and Forget. You call the function, you don’t wait for it, and you just forget about it.
Note :
* BeginInvoke() is the line of code that executes the AsynchronousMethod() function. However, the control is returned to the caller right away, without waiting for AsynchronousMethod() to complete.
* The code above does not know when a call to AsynchronousMethod() completes.
* BeginInvoke() is used instead of Invoke(). For now, don’t worry about the parameters this function takes; I will cover that in more detail later.
How .NET works in background to make this Possible?
Once you ask the framework to call something asynchronously, it needs a thread to do the work. It can not be the current thread, because that would make the invocation synchronous (blocking). Instead, the runtime queues a request to execute the function on a thread from the .NET Thread Pool. You don’t really need to code anything for it, all of it happens in the background. But, just because it is all transparent doesn’t mean you should care about it. There are a few things to remember:
* AsynchronousMethod() is executed on a separate thread, a thread that belongs to the .NET Thread Pool.
* A .NET Thread Pool contains threads in it , and each time AsynchronousMethod() is called, it is going to be executed on one of these threads. You can’t control which one.
* The Thread Pool has its limits! Once all the threads are used, an async method invocation is queued until one of the threads from the pool is freed. This is called Thread Pool Starvation, and normally when it comes to that, performance is compromised.
Thanks,
Hope this Helps!!!!!!![]()
ASP.NET–Asynchronous HTTP Module
Hi Friends,
An HTTP module is an object that sits in the ASP.NET pipeline, where it can see-and even modify-incoming requests and outgoing responses.
Today while working with website containing multiple applications , I faced a scenario where i need to log incoming requests in database . By collecting the login name, a date and time, and the application that the user accessed during the login session.
By thinking on above scenario one would say what’s a big deal in this!! we can make entry every time the user clicks on the application .but problem with this solution is it would give call to the database every time user clicks on any application. First, it performs database insert. Second, it uses a request-processing thread to perform the I/O-a thread that could otherwise be used to service additional incoming requests, which imposes a penalty on throughput.
So for this we decided to write a http module which made it possible for us, but Question is How httpModule improve our performance / throughput the answer is ASYNCHRONOUS HttpModule.
- public class AsyncModule : IHttpModule
- {
- /// <summary>
- /// You will need to configure this module in the web.config file of your
- /// web and register it with IIS before being able to use it. For more information
- /// see the following link: http://go.microsoft.com/?linkid=8101007
- /// </summary>
- #region IHttpModule Members
- string conString = "Data Source=localhost;initial catalog=OpenLDAP;integrated security=true;Asynchronous Processing=true";
- SqlConnection con;
- SqlCommand cmd;
- public void Dispose()
- {
- if (con != null)
- con.Close();
- }
- public void Init(HttpApplication context)
- {
- context.AddOnPreRequestHandlerExecuteAsync(new BeginEventHandler(OnBeginAsync), new EndEventHandler(OnEndAsync));
- }
- #endregion
- public void OnLogRequest(Object source, EventArgs e)
- {
- //custom logging logic can go here
- }
- IAsyncResult OnBeginAsync(Object source, EventArgs e, AsyncCallback cb, Object state)
- {
- //Write your logic here to track the Request//
- con = new SqlConnection(conString);
- con.Open();
- cmd = new SqlCommand();
- cmd.Connection = con;
- cmd.CommandText = "Insert into documents values('abstract3','title',null)";
- return cmd.BeginExecuteNonQuery(cb, state);
- }
- public void OnEndAsync(IAsyncResult result)
- {
- cmd.EndExecuteNonQuery(result);
- }
- }
How above module works asynchronous???
Its Init method calls HttpApplication.AddOnPreRequestHandlerExecuteAsync in order to register begin and end methods for PreRequestHandlerExecute events.
The HttpApplication class features other AddOn methods for other per-request events. For example, an HTTP module can call AddOnBeginRequestAsync to register async handlers for BeginRequest events.
AsyncRequestLogModule’s OnBeginAsync method uses the framework’s BeginExecuteNonQuery method to begin an asynchronous insert. The moment OnBeginAsync returns, the thread goes back into the thread pool.
Thank You,
Hope this helps ![]()
ASP.NET–What is ISAPI ?/What is CGI?/ Advantage Of ISAPI Over CGI
Hi Geeks ,
In this article we will see the Advantage of ISAPI (Internet Server Application Provide Interface) over CGI(Common Gateway Interface).
* What is ISAPI?
It is an API developed to provide the application developers with a powerful way to extend the functionality of IIS.
ISAPI consists of two components:
Extensions and Filters:
These are the only two types of applications that can be developed using ISAPI. Both Filters and Extensions must be compiled into DLL files which are then registered with IIS to be run on the web server.
Extensions An ISAPI server extension is a DLL that can be loaded and called by an HTTP server. Internet server extensions, also known as Internet server applications (ISAs), are used to enhance the capabilities of an Internet Server API (ISAPI)-compliant server. An ISA is invoked from a browser application and provides similar functionality to a Common Gateway Interface (CGI) application
Advantages of ISAPI Server Extensions
Users can fill out forms and click a submit button to send data to a Web server and invoke your ISA, which can process the information to provide custom content or store it in a database. Web server extensions can use information in a database to build Web pages dynamically, and then send them to the client computers to be displayed. Your application can add other custom functionality and provide data to the client using HTTP and HTML.
Both server extensions and filters run in the process space of the Web server, providing an efficient way to extend the server’s capabilities.
Filter
An ISAPI filter is a DLL that runs on an ISAPI-enabled HTTP server to filter data traveling to and from the server. The filter registers for notification of events, such as logging on or URL mapping. When the selected events occur, the filter is called, and you can monitor and change the data (on its way from the server to the client or vice versa). ISAPI filters can be used to provide enhanced logging of HTTP requests (for example, to track who is logging on to your server), custom encryption, custom compression, or additional authentication methods.
Common ISAPI applications
This is a list of common ISAPI applications implemented as ISAPI extensions:
- Active Server Pages (ASP), installed as standard
- Asp.Net, installed as standard on IIS 6.0 onwards
- PHP, available for free to install.
- * What is CGI?
It is a gateway for transferring information between a World Wide Web server and a CGI program.
A CGI program is any program designed to accept and return data that conforms to the CGI specification. The program could be written in any programming language, including C, Perl, Java, or Visual Basic or ASP.NET.
CGI programs are the most common way for Web servers to interact dynamically with users. Many HTML pages that contain forms, for example, use a CGI program to process the form’s data once it’s submitted. Another increasingly common way to provide dynamic feedback for Web users is to include scripts or programs that run on the user’s machine rather than the Web server. These programs can be Java applets, Java scripts, or ActiveX controls. These technologies are known collectively as client-side solutions, while the use of CGI is a server-side solution because the processing occurs on the Web server.
* ISAPI over CGI
->The Internet Server Application Programming Interface (ISAPI) model was developed as a faster alternative to the Common Gateway Interface (CGI).
->ISAPI provides a number of advantages over CGI, including lower overhead, faster loading, and better scalability. T
->The chief difference between the CGI and ISAPI programming models is how processing is handled.
With CGI, the system creates a unique process for every request. Each time an HTTP server receives a request, it initiates a new process. Because the operating system must maintain all these processes, CGI requires many of resources. This inherent limitation makes it difficult to develop responsive Internet applications with CGI.
With ISAPI, requests do not require a separate process. Threads are used to isolate and synchronize work items, resulting in a more efficient use of system resources.
Thanks,
Authenticate Multiple Applications using Single Forms Authentication in ASP.NET / Form Authentication Across multiple Applications
Hi Geeks,
Today I came across a situation where i needed to authenticate more than 3 applications using single forms Authentication , I had the structure of my applications on IIS as follows :
As you see in the above Hosting Structure I have one Main Login Application and
I have to authenticate the application 1,2,3 from the MainLogin application which is at root level and rest of the applications are on sub roots.
At start i thought it would be very critical to do this but Microsoft made it so easy that it wont take so much efforts.
First You need to add the following code to Web.Config file the MainLogin Application
- <authentication mode="Forms">
- <forms loginUrl="login.aspx"></forms>
- </authentication>
- <machineKey validationKey="45AC1CA923F4DC8E5AE294064AFD7810FFB178B21D747B32D3A4765BFA27F892318589A59F09B08C704051504D74969F2EDADBD51CE489343C2A3CF834DEA9D6"
- decryptionKey="917CF306390024BBDBC94817A22506FDB19123D88D159B524345CB4022895BB8" validation="SHA1"
- decryption="AES" />
-> Important Note : Dont Ignore…
Paste the same code to the Web.Config file of all the applications with same machine key,validation key,deception key otherwise it wont work.
If you are adding other forms authentication parameters like name ,Protection,path,domain,timeout , you should add same parameters with same values in Web.Config file of all applications.
To Configure the Machine key for the application see Configure Machine key
-> So the main Question here is HOW did it WORK????
1) Whenever user sends request to the server it always checks for the .ASPXAUTH Cookie.
Note : .ASPXAUTH Cookie is the cookie which is generated by the the logon page creates a cookie that contains a forms authentication ticket that is set for the session only if you are using ASP.NET inbuilt Login Control otherwise you need to generate the ticket using following code
- if (Membership.ValidateUser(userName.Text, password.Text))
- {
- if (Request.QueryString["ReturnUrl"] != null)
- {
- FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
- }
- else
- {
- FormsAuthentication.SetAuthCookie(userName.Text, false);
- }
- }
- else
- {
- Response.Write("Invalid UserID and Password");
- }
So whenever user successfully log in using Main Login Application it will generate the .ASPXAUTH Cookie with Forms Authentication Ticket which contains all the credentials for the authentication and this cookie is used by the other applications to start their authenticated session.
Thanks.
Hope This Will Help You ![]()
WCF # 21 # – WCF Encoder , Types of WCF Encoders , Choose Appropriate encoder
Hi Geeks,
Today We will see WCF Encoder ,their types and how to chose the appropriate encoder according to the situation.
-> First we will see what does Encoding mean in WCF ????
It is the term used to describe the process of converting a WCF message into an array of bytes. This is done so that the message can be sent across a transport protocol.
Note : Encoding is not something that you work with directly. Instead, it is specified by the binding used to expose a service.
For Ex In this example we have used
- <bindings>
- <basicHttpBinding>
- <binding name="testBinding"
- messageEncoding="Text">
- </binding>
- </basicHttpBinding>
- </bindings>
-> Types of WCF Encoders
WCF provides five types of encoding formats:
1.Binary
2.Text
3.Message Transmission Optimization Mechanism(MTOM )
4.JavaScript Object Notation
5.Plain Old XML (POX)
We will go in depth with first three types as those are used the most.
1.Binary Encoding
Binary encoding, the first thing to understand is that it is not a interoperable encoding. If your clients and service are all built with WCF then go ahead and use Binary Encoding.
Binary Encoding is great stuff if you are using Message level security. In message security 90% of the SOAP header is security!
the binary message encoder, uses a compact binary format and is optimized for WCF to WCF communication, and hence is not interoperable. This is also the most performant encoder of all the encoders WCF provides.
2.Text (DataContractSerializer)
The text message encoder, supports both plain XML encoding and SOAP encoding. The plain XML encoding mode of the text message encoder is called "plain old XML" (POX) to distinguish it from text-based SOAP encoding.
Text encoding was acceptable for ASP.NET Web Services because it allowed for interoperability across platforms. WCF abstracts out the encoding mechanism and
allows for bindings that allow for both styles of encoding. This allows WCF to provide functionality that replaces both .NET Remoting and ASP.NET Web Services.
The text encoder converts messages into text-based XML. This is great for interoperability.
3.Message Transmission Optimization Mechanism(MTOM )
The text encoder converts messages into text-based XML. This is great for interoperability, but it is not efficient at transmitting large chunks of binary data.
MTOM is used to send large amounts of binary data as raw bytes in interoperable scenarios.
As mentioned previously,MTOM refers to Message Transmission Optimization Mechanism.This is standard for optimizing the binary data by sending the binary data
- <bindings>
- <basicHttpBinding>
- <binding name="testBinding"
- messageEncoding="Mtom">
- </binding>
- </basicHttpBinding>
- </bindings>
4.JavaScript Object Notation
One of the emerging popular formats for sharing content online is JSON, shorthand for JavaScript Object Notation. Intended to be slightly more efficient than XML, it’s found a home in lots of AJAX powered web applications. Some companies actually require you talk to their APIs in terms of JSON too, so having the ability to parse and emit arbitrary JSON in a strongly typed way is a valuable tool to have. As of .NET 3.5 SP1, we are equipped with the DataContractJsonSerializer.
To know more on the WCF classes and for choosing appropriate encoder belonging to each type please visit WCF Encoders.
Thank You.
Hope this Will help you..
![]()