ASP.net – implementing Asynchronous HTTP handler
March 3, 2010 at 4:26 pm | Posted in .Net | Leave a commentAsynchronous programming has its own benefits. It helps in better usage of resources. In ASP.net when a user request for a resource which is to be processed by HTTP Handler a thread is created an allocated to the handler file. The thread will be idle till the file finish it’s processing. So as to minimize this “idle” period using asynchronous programming we can release the thread back to pool after passing the execution to handler file. When the asynchronous handler completes its work, the framework reassigns a thread to the original request and the handler can render content to the browser. For a better understanding of Asynchronous programming in .Net visit: Asynchronous Programming Overview
We can create an asynchronous HTTP handler by implementing the IHttpAsyncHandler interface, which is derived from the IHttpHandler interface. It adds two additional
methods:
- IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);—Called to start the asynchronous task.
- void EndProcessRequest(IAsyncResult result)—Called when the asynchronous task completes
Create a new class like the following
public class NewClass : IHttpAsyncHandler
{
private HttpContext _context;
private WebRequest _request;
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
}
public void EndProcessRequest(IAsyncResult result)
{
}
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
throw new Exception("The ProcessRequest method is not implemented.");
}
}
You can use this class to do a variety of tasks.
In the below Code I have used created a clss to read RSS data from web
public class RSSHandler : IHttpAsyncHandler
{
private HttpContext _context;
private WebRequest _request;
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
// Store context
_context = context;
// Initiate call to RSS feed
_request = WebRequest.Create(context.Request.QueryString["rssURL"]);
return _request.BeginGetResponse(cb, extraData);
}
public void EndProcessRequest(IAsyncResult result)
{
// Get the RSS feed
string rss = String.Empty;
WebResponse response = _request.EndGetResponse(result);
using (response)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
rss = reader.ReadToEnd();
}
_context.Response.Write(rss);
}
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
throw new Exception("The ProcessRequest method is not implemented.");
}
This class will read the RSS feed asynchronously.
The BeginProcessRequest() method uses the WebRequest class to request the page that
contains the RSS headlines. It received the URL as QueryString.The WebRequest.BeginGetResponse() method is used to retrieve the remote page asynchronously. When the BeginGetResponse() method completes, the handler’s EndProcessRequest() method is called. This method retrieves the page and renders the contents of the page to the browser.
Before we start using this handler we have to register this handler like the following in web.config
<httpHandlers>
<add verb="*" path="*.rss" validate="false" type="AspNet.RSSHandler"/>
<add verb="*" path="*.xml" validate="false" type="AspNet.RSSHandler"/>
httpHandlers>
After building and typing the following URL
http://localhost:2141/xyz.rss?rssURL=http://feeds.feedburner.com/blogspot/anKd
http://localhost:2141/sample.xml?rssURL=http://feeds.feedburner.com/blogspot/anKd
I got an output similar to the one shown below
There was no file xyz.rss or sample.xml but since these extensions were mapped to the recently created HTTP handler output was generated by the framework
Related Articles :
–
Posted By Abhi to The Tech Jungle at 3/02/2010 10:41:00 AM
The Tech Jungle Asp.Net – Creating a new custom HTTP Module
March 3, 2010 at 4:25 pm | Posted in .Net | Leave a commentAn HTTP Module is a .NET class that executes with each and every page request. You can use an HTTP Module to handle any of the HttpApplication events that you can handle in the Global.asax file.
You are already familiar with some of the HTTP Modules like
- FormsAuthenticationModule handles the Forms authentication
- WindowsAuthenticationModule handles the Windows authentication
- SessionStateModule manages the session state of ASP.net application
- OutputCacheModule deals with output caching
- ProfileModule used for interaction with user profiles
Each HTTP Module subscribes to one or more HttpApplication events. For example, when the HttpApplication object raises its AuthenticateRequest event, the FormsAuthenticationModule executes its code to authenticate the current user.
Below I have included a sample class which implements the IHttpModule interface
In the Init event I have created an EventHandler for the PostAuthorizeRequest event of Http Application
namespace AspNet
{
public class CustomContentModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.PostAuthorizeRequest += new EventHandler(SendRequest);
}
public void SendRequest(Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Response.Write("Hi content from HTTP Module
Pay my tax also !!!");
}
public void Dispose() { }
}
}
You can use any of the following events of HTTP Application; the events are raised in the following order:
- BeginRequest
- AuthenticateRequest
- PostAuthenticateRequest
- AuthorizeRequest
- PostAuthorizeRequest
- ResolveRequestCache
- PostResolveRequestCache
After the PostResolveRequestCache event and before the PostMapRequestHandler event, an event handler (which is a page that corresponds to the request URL) is created. When a server is running IIS 7.0 in Integrated mode and at least the .NET Framework version 3.0, the MapRequestHandler event is raised. When a server is running IIS 7.0 in Classic mode or an earlier version of IIS, this event cannot be handled.
- PostMapRequestHandler
- AcquireRequestState
- PostAcquireRequestState
- PreRequestHandlerExecute
The event handler is executed.
- PostRequestHandlerExecute
- ReleaseRequestState
- PostReleaseRequestState
After the PostReleaseRequestState event is raised, any existing response filters will filter the output.
- UpdateRequestCache
- PostUpdateRequestCache
- LogRequest.
This event is supported in IIS 7.0 Integrated mode and at least the .NET Framework 3.0
- PostLogRequest
This event is supported IIS 7.0 Integrated mode and at least the .NET Framework 3.0
- EndRequest
After creating this class add the following entry in Web.config
<httpModules>
<add name="CustomContentModule" type="AspNet.CustomContentModule"/>
httpModules>
When you excute any page in this application HTTP Runtime will add the content from the HTTP module created by us. You can build on this to create more complex scenarious like custom authitication, generation.processing of data based on the paraametr availalle in the Http Application objects etc.
–
Posted By Abhi to The Tech Jungle at 3/03/2010 07:17:00 AM
Anonymous types for dummies
December 27, 2009 at 2:57 pm | Posted in .Net | Leave a commentAnonymous types are used to define strong types without defining the type. Anonymous types are strongly typed and checked at compile time. It provides a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object. This type is widely used by LINQ, because LINQ returns dynamically-shaped data, whose type is determined by the LINQ query
To understand better look at the following code
static void Main(string[] args)
{
string[] names = { "Abhi1", "abhi", "abhi11",
"george", "bush", "britney",
"gandhi", "David" };
IEnumerable<string> varAnnoyType = from str in names
orderby str
select str;
//following code also valid
//var varAnnoyType = from str in names
// orderby str
// select str;
foreach (string strname in varAnnoyType)
Console.WriteLine(strname);
Console.ReadLine();
}
As discussed in http://thetechjungle.blogspot.com/2009/12/linq-for-dummies-overview.html
anonymous type is an object which supports IEnumerable interface.
In the above example an array of names is created (took the array collection from msdn) , an IEnumerable<string> type is created, see the keyword like from used to iterate eact item in collection, orderby clause orders (without LINQ imagine the dictionaries , temp variables and other techniqies used to sort items now this is really cool). You can add a Where clause also before the select keyword. If any conditions are specified then select will retrieve only those items which satisfies the where clause.
var varAnnoyType = from str in names
where str.StartsWith("abhi")
orderby str
select str;
The for each iteration can be written like the following also.
foreach (var strname in varAnnoyType)
Console.WriteLine(strname);
If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.
An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.
Anonymous types cannot contain unsafe types as properties.
Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
–
Posted By Abhi to The Tech Jungle at 12/26/2009 08:06:00 AM
LINQ for dummies – an overview
December 26, 2009 at 12:35 pm | Posted in .Net, ASP.net, C#, VB.NET | Leave a commentTags: ASP.NET, C#, LINQ, VB.NET
Why do we need LINQ?
Most of us would have wrote code to access data from different data sources a database, in memory objects , XML files or from other formats. We have different guidelines, architectures and methods to process and retrieve these data collection. For a data control in form it is immaterial whether the data is from XML or any other data sources. We have many relational OO databases but there always the gap between the data and its processing in Objects in any modern languages.
Is LINQ the Holy Grail?
I can’t decide on that. But LINQ tries to fill the vacuum between the datasources and their successful interpretation in Objects. With LINQ, Microsoft’s intention was to provide a solution for the problem of object-relational mapping, as well as to simplify the interaction between objects and data sources. LINQ eventually evolved into a general-purpose language-integrated querying toolset. This toolset can be used to access data coming from in-memory objects (LINQ to Objects), databases (LINQ to SQL), XML
documents (LINQ to XML), a file-system, or any other source.
LINQ can be used to access any type of object or datasource. The syntax remains the same. Previously we had to use different methods like ADO.Net. XPath, IO packages etc to retrieve data ( ok still we can use these methods and in many cases I still prefer them over LINQ)
Broadly classifying we have three major categories of LINQ
- LINQ to Objects,
- LINQ to SQL,
- LINQ to XML
Don’t worry there are other categories like LINQ to datasets. LINQ to Entities ( with ADO.net entity framework). In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents,ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable(T) interface. In short .NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. Third parties are also free to replace the standard query operators with their own implementations that provide additional services such as remote evaluation, query translation, optimization, and so on. By adhering to the conventions of the LINQ pattern, such implementations enjoy the same language integration and tool support as the standard query operators.
Next – LINQ in action …
Difference between a constant and readonly variables/fields : (constant vs readonly)
December 26, 2009 at 12:34 pm | Posted in .Net, ASP.net, C#, VB.NET | 1 CommentTags: .Net, C#. VB.Net
- What is the difference between constant and readonly fields?
- When to use constant and when to use readonly fields?
- What is the advantage/disadvantage of each?
- In C# you can declare a constant like this “const” is a keyword.
public const string _constStrVar = “I am a static const str val”; - A constant variable should have value at design time.
- All the constant variables are static ie they are shared across all the instances of the class. You dont have to add the keyword “static”.
- Constants are copied to all the dlls where is refereeing the parent class ie even if you change the the original constant value and recompile the parent dll , the other dll will still use the old value. The size of the executable goes up since all these constants are copied to the respective dlls
- Read only variables are created usually in the constructor of class. there fore it will have values before the constructor of the class exists
{
public readonly string _strReadonly;
public void MyClass(string strVal)
{ _strReadonly = strVal;
}
}
Return top N rows from datatable
December 26, 2009 at 12:32 pm | Posted in .Net, ASP.net, C#, VB.NET | Leave a commentTags: .Net, ADO.NET, C#, DATATABLE, LINQ, VB.NET
{
var dtTrec = from item in dtSource.AsEnumerable()
select item;
var topN = dtTrec.Take(TopRowCount);
DataTable dtNew = new DataTable();
dtNew = dtSource.Clone();
foreach (DataRow drrow in topN.ToArray())
{
dtNew.ImportRow(drrow);
}
return dtNew;
}
{
Mastlog.ldf” is compressed but does not reside in a read-only database or filegroup.
December 26, 2009 at 12:30 pm | Posted in SQL Server | Leave a commentTags: Sql Server 2005
I install a lot of trial & beta softwares to get a first feel of the application. So I usually keep all the services disabled. I had kept the SQL server also disabled for quites some time. Today when i tried to start it again it refused
.. (it seems that she was angry for leaving her alone).
When i checked the event viewer i saw the following message
The file “C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\DATA\mastlog.ldf” is compressed but does not reside in a read-only database or filegroup. The file must be decompressed.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
so the compression was the culprit
( to save space windows had compressed these folders )
I opened “c:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\DATA\” and uncompressed all the files in it by select the advanced properties of the files & un-checking – compress contents to save disk. Now it works like a brand new BMW
Viewstate error : 12031
December 26, 2009 at 12:28 pm | Posted in .Net, ASP.net, C# | Leave a commentTags: .Net, AJAX, ASP.NET, C#, EXCEPTION, VIEWSTATE
Few days ago I was asked to look into an issue. In our application we have created dynamic grids to show data from database. This ASPX page was Ajax enabled. Moreover all the rows of the grid were in edit mode ie. the normal controls like textbox,dropdowns etc were displayed in all the rows. This grid was Paginated. But for the past few days the paging was not working.
I executed the page and found that the page was generating an error 12031 with the following message
Sys.webForms.PageRequestManagerServerErrorException:An unknown error occurred while processing the request on the server .the status code returned from the server was:12031.
On my first round of analysis I found the issue with Viewstate. If the viewstate is large then connection is reset (ERROR_INTERNET_CONNECTION_RESET ). In local machine with less load this problem will not occur but as the load & network latency increases this error will come. Once this error is generated the general events of grid is not triggered. So advised my team to minimize the use of viewstate. It will help in to load the page faster & reduce the network traffic. I can increase the maxRequestlength value to allow more data but ideally i shouldn’t increase that.
In the page tested by me a page with grid with 372 rows generated a viewstate of 4.2 mb. you can disable viewstate using EnableViewState=”false” for the individual controls and for the entire page also.
With every post back this much of data is transferred back & fro & this will result in low response time.
The developer was saving all the data into viewstate in page load and from that the data was populated to the grid.
Better solution is to retrieve only the required data from database, minimize the use of viewstate, Viewstate can be compressed also. About all these I will update in another post.
Add Web service reference- Components required to enumerate web references not installed
December 26, 2009 at 12:26 pm | Posted in .Net, C#, VB.NET | Leave a commentTags: .Net, ASP.NET, VISUAL STUDIO, WCF, WEB SERVICE
After playing with Web services for so many years this was a tricky error which kept me thinking for few minutes.
Today when i tried to add WCF reference to my application it gave the following error,
Error
—————————
Microsoft Visual Studio
—————————
Failed to update Service Reference ‘XXXBusiness.Reference’.
Error:The components required to enumerate Web references are not installed on this computer. Please re-install Visual Studio.(0×80004002)
What could have caused this error? Then i remembered there was a alert box from VS few hours ago which informed that some package was not loaded successfully and whether i wanted VS to stop loading that package in future.Without reading the full message I accidentally pressed “YES” I know mea cupla.
But i have to move forward …
- Close all open Visual Studio instances
- Open the Command prompt available with Visual Studio and type devenv /resetskippkgs (You can directly type this to Run command or normal command prompt)
- Add reference to the Web service/WCF service
Now I am back in business
WCF 8192 issue
November 10, 2009 at 6:27 pm | Posted in Uncategorized | Leave a commentTags: ASP.NET, WCF
this was a simple issue which baffled few brains in my project. For the past few weeks i was seeing the mails about this. What was the exact problem?
Whenever a large xml stream is passed through WCF it generated the following error. Everything was fins at the ASP.net client side. Almost all the known properties of
Problem:
The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader.
Cause:
By default WCF allows a string content of size 8192 (8K) to pass through without any problems. If the size increases above this set limit WCF treats the incoming message as bad message & hence throws an exception. This level was set considering the security aspect of distributed system.
If we have to pass more data we will have to manually override this default setting.
Now here the trick. Everyone looked at the client side but there is a server part also ![]()
When a WCF client is created automatically all the properties required to run that service is added by default by visual studio.
http://thetechjungle.blogspot.com/2009/11/wcf-8192-issue.html
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.