Showing posts with label ASP.NET-MVC. Show all posts
Showing posts with label ASP.NET-MVC. Show all posts
Monday, January 24, 2011

Programmatically creating request and handling response

Recently one of the my friends asked about how to create a web request in to a url outside of project. So I decided to write a small blog post regarding this. This web request can be easily created with httpwebrequest class and you can easily consume the response we are getting from this. This kind of request can be very useful when you are implementing payment gateways or other third party components. Following is a code for it. It is very easy.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;

namespace Experiment
public partial class WebForm1 : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
string url = "http://localhost:1798/WebForm2.aspx";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";

HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string response = streamReader.ReadToEnd();

Here in the above code you can see I have created a webrequest with name space and then I have typecast that request in HttpWebRequest Class. There are several parameters are available with request like method which HTML submit method you want to use like “Get” or “Post”. After that I have created a object of HTTPResponse and then with the help of stream reader I have print a response we are getting from the URL.

That’s it. It’s very easy. Hope you will find it useful. Stay tuned for more. Happy Programming..

Technorati Tags: ,,,
Shout it
Monday, December 20, 2010

ASP.NET MVC 3 RC2 Razor- Syntax Intellisense in view.

Microsoft has recently launched Razor view engine with ASP.NET MVC RC2. It’s going to be promising one. There are lots of features bundled with this view engine. But in earlier version of ASP.NET 3 MVC. We were are not having Synatx intellisense provided for mvc views in Visual Studio 2010. So either we have to depend third party tools like Resharper or we have to manage it without intellisesnse. But with ASP.NET MVC 3 RC2 Microsoft has moved one step forward and its providing syntax intellisense without installing any third party addons in Visual Studio. Here is example of it.

Hope you liked it. Stay tuned for more.. Happy Programming..

Shout it
Friday, December 3, 2010

ASP.NET MVC Razor IsPost property with IF –Else loop

ASP.NET MVC Razor a new view engine from Microsoft looks very promising. Here are example of code where we can determine page is post back or not. It support a IsPost Property which will tell you whether page is post back or not. So based on that we can write code for handling post back. Also one of greatest feature of razor is we can write code for decision making like if else and other stuff with single @ statement isn’t that great stuff.

Here is the stuff how we can write the code with IsPost property.

var Message="";
Message ="This is from the postback";
Message="This is without postback";
And we can now print that variable with following HTML Form.
<form method="POST" action="" >
<input type="Submit" name="Submit" value="Submit"/>

Here submit button will submit the form and based on that it will print message. Let’s see how it looks in browser before post back and after post back.


And After post back


So that’s it. Now you can do lots of stuff with IsPost property possibilities are unlimited!!. Hope this will help you..Happy Programming.

Technorati Tags: ,,
Shout it
kick it on
Thursday, December 2, 2010

What is difference between HTTP Handler and HTTP Module.

Here are the difference between HTTP Handlers and HTTP Modules.

Http Handlers:

Http handlers are component developed by developers to work as end point to pipeline. It has to implement System.Web.IHttpHandler interface and this will act as target for requests. Handlers can be act as ISAPI dlls the only difference between ISAPI dlls and HTTP Handlers are Handlers can be called directly URL as compare to ISAPI Dlls.

Http Modules:

Http modules are objects which also participate in the request pipeline but it does job after and before HTTP Handlers complete its work. For example it will associate a session and cache with request. It implements System.Web.IHttpModule interface.

HTTP Handler implement following Methods and Properties

  1. Process Request: This method is called when processing requests. Here you can perform all the things related to processing request.
  2. IsReusable: This property is to determine whether same instance of HTTP Handler can be used to fulfill another request of same type.

Http Module implements following Methods and Properties.

  1. InIt: This method is used for implementing events of HTTP Modules in HTTPApplication object.
  2. Dispose: This method is used perform cleanup before Garbage Collector destroy everything.

An Http Module can Support following events exposed to HTTPApplication Object.

  1. AcquireRequestState: This event is raised when request is ready to acquire the session state in http module.
  2. AuthenticateRequest: This event is raised when runtime ready to authenticate user.
  3. AuthorizeRequest: This event is raised when request try to authorize resources with current user identity.
  4. BeginRequest: This event is raised when HTTP Modules receive new request.
  5. EndRequest: This event is raised before sending response to client.
  6. Disposed: This event is raised when http modules completes processing of request
  7. Error: This event is raised when any error occurs during processing of request.
  8. PreRequestHandlerExecute: This event is raised just before ASP.NET begins executing a handler for the HTTP request. After this event, ASP.NET will forward the request to the appropriate HTTP handler.
  9. PostRequestHandlerExecute: This event is raised when when HTTP Handler will finish the execution of current request.
  10. PreSendRequestContent: This event is raised just before ASP.NET sends the response contents to the client. This event allows us to change the contents before it gets delivered to the client. We can use this event to add the contents, which are common in all pages, to the page output. For example, a common menu, header or footer.
  11. PreSendRequestHeaders: This event is raised before Just send response header to client browser.
  12. ReleaseRequestState: This event is raised when runtime finishes handling of all the request.
  13. ResolveRequestCache: This event is raised to determine whether the request can be fulfilled by returning the contents from the Output Cache.
  14. UpdateRequestCache: This event is raised when ASP.NET has completed processing the current HTTP request and the output contents are ready to be added to the Output Cache.

Hope this will help you better understanding of HTTP Handler and HTTP Modules. I will post an real time implementation code in forthcoming blog post.

Shout it
kick it on
Wednesday, March 24, 2010

ASP.NET- Using span tag instead of label for performance

In ASP.NET controls used in to the user controls are generate Client Id which unique for the control and If you have so many user controls hierarchy then you will have very long client id like ‘ctl00_CPH_ctl02_BM_userLogin_UserName’.It will increase the Kilo Bytes of html rendered in the browsers. Label control is the control which is used to display text and its render as span tag in the html render by the browser. So in such type of scenario if you have so many label controls then your html is going to increase very much. And overall it will decrease the your application performance.

In 4.0 we can manage the Client Id via different options i have already posted over here. But for 3.5 and lower version we have to write our own code for doing that there are two options either we have to create a our own custom control inherited from label which override the ClientID generated by system or we can use the span tag instead of label control because ultimately label control will be rendered as span tag in browser.

We having same scenario in the one of the project we are having so many label controls in one of the form in our page. So it is going to kill our application because rendered HTML will be heavy. So we have decided to use span tag. Now you guys are having questions that how we can manage span text from the server side we have used static string variables for to manage the text of span. Let’s create a simple example to understand how its works.

We have created a static string which will contain the text for the label. We are assigning text in page_load event of page or control then we have used that static string directly in html in between span tag which will have same style sheet as label control. Following is code for that.

protected static string UserName;

protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
//asssign text here for first time
UserName = "User Name";
Now in the html of user control or page you need to write span tax as follows.
<span class="label"><%=UserName%></span>
That’s it will render span tag in your browser with same look as label and there will not be any id generated for this span tag and ultimately your html rendered in browser will have less Kilo Bytes. We able to reduce 10 to 12 KB bytes of our page via this technique. Hope this will help you too..

Technorati Tags: ,,,
Shout it
kick it on
Friday, February 26, 2010

How to send mail asynchronously in

With Microsoft.NET Framework 2.0 everything is asynchronous and we can send mail also asynchronously. This features is very useful when you send lots of bulk mails like news letter. You don’t have to wait for response from mail server and you can do other task .

Let's create a simple example to send mail. For sending mail asynchronously you need to create a event handler that will notify that mail successfully sent or some errors occurred during sending mail. Let’s create a mail object and then we will send it asynchronously. You will require System.Net.Mail space to import in your page to send mail.

//you require following name space
using System.Net.Mail;

//creating mail message object
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("Put From mail address here");
mailMessage.To.Add(new MailAddress("Put To Email Address here"));
mailMessage.CC.Add(new MailAddress("Put CC Email Address here"));
mailMessage.Bcc.Add(new MailAddress("Put BCC Email Address here"));
mailMessage.Subject = "Put Email Subject here";
mailMessage.Body = "Put Email Body here ";
mailMessage.IsBodyHtml = true;//to send mail in html or not

SmtpClient smtpClient = new SmtpClient("Put smtp server host here", 25);//portno here
smtpClient.EnableSsl = false; //True or False depends on SSL Require or not
smtpClient.UseDefaultCredentials = true ; //true or false depends on you want to default credentials or not
Object mailState = mailMessage;

//this code adds event handler to notify that mail is sent or not
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
smtpClient.SendAsync(mailMessage, mailState);
catch (Exception ex)
Following is a code for event handler

void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
MailMessage mailMessage = e.UserState as MailMessage;
if (!e.Cancelled && e.Error != null)
Response.Write("Email sent successfully");
So that’s it you can send mail asynchronously this 30-40 lines of code.

Technorati Tags: ,

Shout it

kick it on
Saturday, November 14, 2009

Visual Studio 2010- New Features Selected Text.

I am loving more and more visual studio 2010 for some of the cool things. One of the new feature i have found in visual studio 2010 is the selected text. In the earlier version of visual studio 2010 when we select tax then its not maintaining the highlighted code but with visual studio 2010 it is maintain the colored syntax. Isn't that cool?. We can still know that what we are selecting. Like following.


Shout it
Tuesday, October 27, 2009

Review of Microsoft Visual Web Developer 2010 beta 2 express edition.

Microsoft visual studio express editions are light weight IDE provided free by Microsoft and also having almost all the functionality of its big brother Microsoft Visual Studio Professional edition except few. My pc is bit old now Its P4 and its having only 1gigs of ram so the express edition are the best suited for pc like mine. Microsoft has recently provided the beta 2 version of Microsoft new generation IDE called Visual Studio Twenty Ten(2010).

There are lots of changes from visual studio 2008 express edition and Microsoft Visual Studio 2010 Express edition. The first changes you will notice is the brand new splash screen and brand new colored logo for visual studio.

LogoVisual Splash

Another thing you will notice is the look and fill of IDE. It all looks like blue every where. Its is best suited for the Microsoft forthcoming operating system Microsoft Windows 7.


Another the difference is the create new project window which is bit stylish and having more options compare the to the visual studio 2008. There are two new things in new project dialog the first one the windows azure tools which is Microsoft's new steps towards the could computing(I will blog about this later one). and another thing is the Silver light application option. Now you can create three kind of application with the Microsoft SilverLight Application

  1. Silverlight Application
  2. Silverlight Navigation Application
  3. Silverlight class library


Another difference is the default font for the IDE earlier it was Courier New and now its Consolas which is the next generation programming font. Which is more visual than the other fonts.

Another major difference is when you create a web application then its now having more default folders compare to visual studio 2008. There are site.master is also there and some default style sheet just like mvc applications. You will have default login control like mvc application. There are two more folder scripts and styles. In style you will have default style sheet for the application. Another folder is for the scripts which are having default JQuery as per earlier announcement Microsoft and JQuery will go together.


Another new things in Microsoft Visual Studio 2010 Visual Web Developer Expression edition is the Tool Setting menu which are having three setting by default.

  1. Basic Settings
  2. Code Optimized
  3. Expert Settings.

All the three option will have different setting for solution explorer and all other stuff. Another new thing is visual web developer 2010 express edition having multi monitor support which is not there in earlier express editions.Visual web developer express also having windows presentation foundation code editor.

Another cool feature is the maximized windows in design view now you will have whole window is maximized in design view hiding other windows. So you visually look all the control more better. Another cool thing is the percentage dropdown through which you can set all screen by percentage as per your requirement.

There are lots of more features like Improved css compatibility,HTML and Javascript snippets,support for mvc application and support for multi target etc. I will blog about each feature in much more detail. T

If you still not downloaded the future version of visual studio express edition 2010 then you can download it from the following link.

Shout it
Saturday, July 25, 2009

Sending mail with secure service layer in 3.5/2.0

In earlier post i have mentioned that how to send the email using new System.Net.Smtpmail with 2.0 or higher version. Now lets learn how to send the mail with the secure service layer in the

Security is the one of the most important requirement in today’s world as you are doing your business online you have keep secure from other wrong elements. Secure service layer add an

extra layer of security to your web application and sending mail with the SSL with tighten your security for mails. Your emails are more secure then ever and your valuable information will not going to wrong hands.

Here is the code from which we can send the email with the secure service layer. As i have mentioned in earlier post you need to to send email with authentication to use SSL. So you need to write following code. First you need to create message like following..

MailAddress fromAddress = new MailAddress("[email protected]","Nameofsendingperson");
message.From = @”fromAddress”;//here you can set address
message.To.Add("mailto:[email protected]%22%29;//");//
message.Subject = "Sending email with ssl";
message.CC.Add("[email protected]");//ccing the same email to other email address
message.Bcc.Add(new MailAddress("[email protected]"));//here you can add bcc address
message.IsBodyHtml = true;//To determine email body is html or not
message.Body =@"Plain or HTML Text";
Then you have to sent message with following code.
System.Net.Mail.SmtpClient mailClient =
 new System.Net.Mail.SmtpClient("your smptp","ssl port");
//This object stores the authentication values
System.Net.NetworkCredential basicCrenntial = 
new System.Net.NetworkCredential("username", "password");
mailClient.Host = "Host";
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicCrenntial;
// You have to add one other properties for SSL
Friday, July 17, 2009

Subsonic 3.0 is out now- Next Generation Object Relational Mapper

There lots of ORM(Object Relational Mapper) is available now like entity framework,nhibernate, linq, dlinq but i choose subsonic 3.0 for my next application which will be a question answer site for the following reason

  1. Now subsonic 3.0 is with linq support so you can write your lambda expression and linq queries along with the subsonic
  2. It comes with simple repository.
  3. Built in T4 Templates for 4.0
  4. Linq to subsonic.
  5. Subsonic 3.0 templates.
  6. Can handle thousand of queries at a times.
  7. Full support with 3.5 features.
  8. Ease of Use.
  9. Great support with mvc

And another great news is that Rob Conery is hired by the Microsoft and subsonic will official ORM for Applications.

You can download subsonic 3.0 from here.

Happy Coding..


Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog


My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews