Thursday, July 10, 2014

Difference between HttpGet and HttpPost Method


The Hypertext Transfer Protocol (HTTP) is a communication protocol that is designed to enable request-response between clients and servers. Here, a web browser is the client and an application on a computer that hosts a web site is the server

Http GET method

Take an html form named "get_form.htm" and write the following code.
  1. <html>
  2. <head>
  3. <title>Using Http Get Method</title>
  4. </head>
  5. <body>
  6. <form id="frm_get" action=" Receiving_Get_Form.aspx" target="_blank" method="GET" >
  7. <table>
  8. <tr>
  9. <td>First Name : </td> <td><input type="text" id="txtF_Name" name="F_name" /></td>
  10. </tr> <tr>
  11. <td>Last Name : </td> <td><input type=" text" id="txtL_name" name="L_name" /></td>
  12. </tr> <tr>
  13. <td>Email-Id : </td> <td><input type="text" id="txtE_mail" name="E_mail" /></td>
  14. </tr> <tr>
  15. <td>Password: </td> <td><input type="password" id="txtP_word" name="P_word"/> </td>
  16. </tr> <tr>
  17. <td><input type="submit" value="Submit" /></td>
  18. </tr>
  19. </table>
  20. </form> </body>
  21. </html>
When we click submit button of this form, it will be redirected to "Receiving_Get_Form.aspx" in a new window.

Page.Request.QueryString["param_name"]

  1. <%@ page language="C#" AutoEventWireup="true" codeFile="Receiving_ Get_Form.aspx.cs" Inherits="Receiving_ Get_Form"% >
  2. <html>
  3. <head>
  4. <title>Data Received Here </title>
  5. </head>
  6. <body>
  7. <table border="1" cellpadding="6" cellspacing="3" >
  8. <tr>
  9. <td>First Name : </td> <td> <% Response.Write(Page.Request.QueryString["F_name"]); %> </td>
  10. </tr>
  11. <tr>
  12. <td>Last Name : </td> <td> <% Response.Write(Page.Request.QueryString["L_name"]); %> </td>
  13. </tr>
  14. <tr>
  15. <td>Email-Id : </td> <td> <% Response.Write(Page.Request.QueryString["E_mail"]); %> </td>
  16. </tr>
  17. <tr>
  18. <td>Password : </td> <td> <% Response.Write(Page.Request.QueryString["P_word"]); %> </td>
  19. </tr>
  20. </table>
  21. </body>
  22. </html>
The First Name, Last Name, Email-Id and Password text boxes of get_form.htm form will be sent as parameter of query string with the field name are F_name, F_name, E_mail and P_word respectively. The name of query string fields automatically taken from name attribute of each HTML element, so don’t forget to specify the name attribute So that values should be retrieving using Page.Request.QueryString ["param_name"] here in "Receiving_Get_Form.aspx" automatically.

Key points about data submitted by using HttpGet

  1. GET - Requests data from a specified resource
  2. An hyperlink or anchor tag that points to an action will ALWAYS be an HttpGet.
  3. Data is submitted as a part of url.
  4. Data is visible to the user as it posts as query string.
  5. It is not secure but fast and quick.
  6. It use Stack method for passing form variable.
  7. Data is limited to max length of query string.
  8. It is good when you want user to bookmark page.

HttpPost method

The POST request method is designed to request that a web server accepts the data enclosed in the request message's body for storage
Take an html form named “post_form.htm" and write the following code.
  1. </head>
  2. <body>
  3. <form id="frm_post" action=" Receiving_Post_Form.aspx" target="_blank" method=" POST" >
  4. <table>
  5. <tr>
  6. <td>First Name : </td> <td><input type="text" id="txtF_Name" name="F_name" /></td>
  7. </tr> <tr>
  8. <td>Last Name : </td> <td><input type=" text" id="txtL_name" name="L_name" /></td>
  9. </tr> <tr>
  10. <td>Email-Id : </td> <td><input type="text" id="txtE_mail" name="E_mail" /></td>
  11. </tr> <tr>
  12. <td>Password: </td> <td><input type="password" id="txtP_word" name="P_word"/> </td>
  13. </tr> <tr>
  14. <td><input type="submit" value="Submit" /></td>
  15. </tr>
  16. </table>
  17. </form> </body>
  18. </html>
When we click submit button of this form, it will be redirected to "Receiving_Post_Form.aspx" (opened in new window too). In ASP.NET, if data passed through HTTP Post method we need the following code to retrieve the data (as written in "Receiving_Post_Form.aspx").

Page.Request.Form["param_name"]

  1. <%@ page language="C#" AutoEventWireup="true" codeFile="Receiving_Post_Form.aspx.cs" Inherits=" Receiving_Post_Form"% >
  2. <html>
  3. <head>
  4. <title>Data Received Here </title>
  5. </head>
  6. <body>
  7. <table border="1" cellpadding="6" cellspacing="3" >
  8. <tr>
  9. <td>First Name : </td> <td> <% Response.Write(Page.Request.Form["F_name"]); %> </td>
  10. </tr>
  11. <tr>
  12. <td>Last Name : </td> <td> <% Response.Write(Page.Request.Form["L_name"]); %> </td>
  13. </tr>
  14. <tr>
  15. <td>Email-Id : </td> <td> <% Response.Write(Page.Request. Form["E_mail"]); %> </td>
  16. </tr>
  17. <tr>
  18. <td>Password : </td> <td> <% Response.Write(Page.Request. Form["P_word"]); %> </td>
  19. </tr>
  20. </table>
  21. </body>
  22. </html>
Values of "post_form.htm"(that used method="POST") form sent using POST method therefore, the URL still intact, we retrieve The First Name, Last Name, Email-Id and Password text using Page.Request.Form["param_name"] value taken from the name each of HTML element of second form (Once again don’t forget to specify name attribute for all textboxes so that we are able to get value automatically here in this page). When you click Submit button, values of "post_form.htm" passed to "Receiving_Post_Form.aspx".
Key points about data submitted using HttpPost
  1. POST - Submits data to be processed to a specified resource
  2. A Submit button will always initiate an HttpPost request.
  3. Data is submitted in http request body.
  4. Data is not visible in the url.
  5. It is more secured but slower as compared to GET.
  6. It use heap method for passing form variable
  7. It can post unlimited form variables.
  8. It is advisable for sending critical data which should not visible to users.

When we develop web applications we always have to deal with the HTML.
Today we will see the difference between the HTTPGet and HTTPPost attributes of ASP.NETMVC.
These attributes encode request parameters as name-and-value pairs in the HTTP request. The HTTP-GET protocol and the HTTP-POST protocol provide backward compatibility in the following ways.

* For example, you may want two versions of the Edit method, one that renders the edit form and the other that handles the request when that form is posted:

[HttpGet]
public ActionResult Edit(string id)
{
return View();
}
[HttpPost]
public ActionResult Edit(string id, FormCollection form)
{
//Save the item and redirect…}

When a POST request for /home/edit is received, the action invoker creates a list of all methods of the Controller that match the edit action name. In this case, you would end up with a list of two methods.
Afterward, the invoker looks at all of the ActionSelectorAttribute instances applied to
each method and calls the IsValidForRequest method on each. If each attribute returns true, then the method is considered valid for the current action.
For example, in this case, when you ask the first method if it can handle a POST request, it will respond with false because it only handles GET requests.
The second method responds with true because it can handle the POST request, and it is the one selected to handle the action.
If no method is found that meets these criteria, the invoker will call theHandleUnknownAction method on the Controller, supplying the name of the missing action. If more than one action method meeting these criteria is found, an InvalidOperationExceptionis thrown.

Difference between HTTPGet and HTTPPost methods –
Fundamental Difference is probably the Visibility -
The HTTPGet protocol creates a query string of the name-and-value pairs and then appends the query string to the URL of the script on the server that handles the request. Therefore, you can mark the request.
The HTTPPost protocol passes the name-and-value pairs in the body of the HTTP request message.
Length -
Since, HTTPGet request goes via URL, so it has a limitation for its length. It can’t be more than 255 characters long (though this is browser dependent, but usually the max is 255 characters only).
Whereas
No such maximum length limitation holds for the HTTPPost request for the obvious reason that it becomes a part of the body of the HTTP request and there is no size limitation for the body of an HTTP request/response.
Performance -
HTTPGet request is comparatively faster as it’s relatively simpler to create a GET request and
the time spent in the encapsulation of the HTTPPost request in the HTTP body is saved in this case. In addition, the maximum length restriction facilitates better optimization of HTTPGet implementation.
Type of Data -
HTTPGet request is sent via URL string and as we all know that URL can be text-only, so GET can carry only text data
whereas
HTTPPost has no such restriction and it can carry both text as well as binary data.
Caching/Bookmarking – again for the obvious reason that a HTTPGet request is nothing but an URL hence it can be cached as well as Bookmarked.
No such luxuries with a HTTPPost request.
FORM Default -
HTTPGet is the default method of the HTML FORM element.
To submit a FORM using POST method, we need to specify the method attribute and give it the value “HTTPPost”.

For more on ASP.NET MVC visit http://microsoftmentalist.wordpress.com/asp-net-2/

Wednesday, July 9, 2014

Windows Forms Application versus Web Application

 Comparison between Windows Forms and ASP.NET Web Applications.


Windows Forms
ASP.NET Web Application
User Interfaces, data binding etc.
Easy to build
Difficult to build
Deployment and Maintenance
Complex. New versions of assemblies, configuration files, and other required files must be deployed on all client machines. Usually user interaction required.
Easy. Need to deploy assemblies and configuration files on the server only. Transparent to the client.
Performance
Faster
Slower
Robustness and Reliability
One client machine goes down, other users are still live.
Usually web servers are never down. However if the server goes down, all users are affected.
Network Congestion
Depending on the data transfer and connections made to the server from various clients.
Depends
Resources
Runs on the client machine.
Runs on a Web server.
Catastrophic failure
User interaction required.
Usually user interaction not required.
Framework dependency
All client machines have to install required versions of .NET framework and other required libraries.
Only server needs to have .NET framework and other required libraries.

Thursday, May 1, 2014

Behavior Based Safety (BBS) is the "application of science of behavior change to real world problems".[1] BBS "focuses on what people do, analyzes why they do it, and then applies a research-supported intervention strategy to improve what people do".[2] At its very core BBS is based on a larger scientific field called Organizational behavior management.[3]
To be successful a BBS program must include all employees, from the CEO to the front line workers. Including but not limited to hourly, salary, union employees, contractors and sub-contractors. To achieve changes in behavior, a change in policy, procedures and/or systems most assuredly will also need some change. Those changes cannot be done without buy-in and support from all involved in making those decisions.
BBS is not based on assumptions, personal feeling, and/or common knowledge. To be successful, the BBS program used must be based on scientific knowledge.


How to Integrate Facebook in your ASP.Net website



Facebook is one of the top rated social media networking sites that impress everyone. More than 270 million users are using Facebook. 
Facebook connect -- this enables users to integrate Facebook platform to your website. This allow a user to connect with your site using the Facebook account and can share posts on your pages with friends on Facebook. The connection is established between Facebook and your website using a trusted authentication.
Before integrating Facebook on your website, you need to follow these steps:

Setting Up with Facebook

You’ll need to set up your application with Facebook. Set-up is free and happens pretty much instantaneously, because there’s no application approval process to go through.

1. Register your website with Facebook.

 

Log in to Facebook and visit the developer’s application at Facebook.com/developers. Here you can set up new applications and edit existing ones. You can also access SDK documentation and interact with the Facebook developer community.


In App Name: give the name of your site and continue. It will give you the Unique App ID/App Secret.



The URL of your website and the website URL you registered with Facebook should be same.

Note: If you want to access some additional information like Email ID etc, you have to use OAUTH (which is authorize the user and provide grant permissions to access).

2. Add Facebook DLL Refrences to your website/bin folder


  • Facebook.dll  
  • Facebook.web.dll

3. Web.config 

 

 Add the App ID/App Secret  value 
 <appSettings>
    <add key="redirect_uri" value="<your_redirect_uri>">
    <add key="AppKey" value="<your_App_ID>"/>
    <add key="AppSecret" value="<your_App_Secret>"/>
 </appSettings>

 

 4. Add Facebook login button in your login.aspx page


<asp:Panel ID="pnlLogin" runat="server">
                    <a href="https://www.facebook.com/dialog/oauth?client_id=your_app_id&redirect_uri=your_redirect_uri">
                        <img src="../../images/f_login.png"  />
                    </a>
 </asp:Panel>
<a id="lbllogout" runat="server" onserverclick="lbllogout_Click" visible="false" > </a>


For accessing some additional information like offline_access,email etc, you have to add scope feature in login like

<a href="https://www.facebook.com/dialog/oauth?client_id=your_app_id&redirect_uri=your_redirect_uri&scope=offline_access,user_status,publish_stream,email,manage_pages,user_groups">


It will ask you for allowing the permissions. Click Allow.

 5. Now add code in login.aspx.cs to access Facebook user details in your page


using Facebook.Web;
using Facebook;

string getAccessToken = "";
WebClient client = new WebClient();

 protected void Page_Load(object sender, EventArgs e)
  {
           string fbCodeGiven = Request.QueryString["code"];
            if ((fbCodeGiven != null))
            {
                WebRequest AccessTokenWebRequest = WebRequest.Create("https://graph.facebook.com
                 /oauth/access_token?client_id=" + your_App_ID + "&redirect_uri=" +
                 your_redirect_uri  +  "&client_secret=" + your_App_Secret"] + "&code=" +
                 fbCodeGiven);

                StreamReader AccessTokenWebRequestStream = new
                StreamReader(AccessTokenWebRequest.GetResponse().GetResponseStream());
                string WebRequestResponse = AccessTokenWebRequestStream.ReadToEnd();
                getAccessToken = WebRequestResponse.Substring(13, WebRequestResponse.Length -
                                                13);

                Session["getAccessToken"] = getAccessToken;
                string url, userInformation, email = null, CorrectEmail = null, id = null,
                first_name = null, last_name = null;

                Regex getValues;
                Match infoMatch;
                string username = "me";
                url = "https://graph.facebook.com/" + username + "/" + "?access_token=" +
                          getAccessToken;

                userInformation = client.DownloadString(url);
                getValues = new Regex("(?<=\"email\":\")(.+?)(?=\")");
                infoMatch = getValues.Match(userInformation);
                email = infoMatch.Value;
                CorrectEmail = email.Replace("\\u0040", "@");

                getValues = new Regex("(?<=\"id\":\")(.+?)(?=\")");
                infoMatch = getValues.Match(userInformation);
                id = infoMatch.Value;
                Session["facebookuserID"] = id;

                getValues = new Regex("(?<=\"first_name\":\")(.+?)(?=\")");
                infoMatch = getValues.Match(userInformation);
                first_name = infoMatch.Value;

                getValues = new Regex("(?<=\"last_name\":\")(.+?)(?=\")");
                infoMatch = getValues.Match(userInformation);
                last_name = infoMatch.Value;
            }
}

protected void lbllogout_Click(object sender, EventArgs e)
{
            if (Convert.ToString(Session["facebookuserID"]) != "")
            {
                string getAccessToken = Convert.ToString(Session["getAccessToken"]);
                Session.Remove("facebookuserID");
                Response.Redirect("https://www.facebook.com/logout.php?next=" + your_redirect_uri
                                                 + "&access_token=" + getAccessToken);
                Session.Remove("getAccessToken");
            }
 }

The URL supplied in the next parameter must be a URL with the same base domain as your application as defined in your app's settings.

IMPORTANT NOTE -- You must replace "your_App_ID", "your_App_Secret" with the APP ID, APP Secret you find in your application details in the Developer application on Facebook!

Download Files  loginwithfacebook.rar

6. Testing 


Now we are done with the coding. Its time for testing.

  • Run your Website 

I hope this article will give you good knowledge about integration with Facebook into your ASP.Net website. Please share your feedback and comments with us.