Pages

Ruchi Tech

Tuesday, 12 June 2012

How to Integrate Gmail Login into your ASP.Net Website

Google supports the OpenID 2.0 protocol, providing authentication support as an OpenID provider. On request from a third-party site, Google authenticates users who are signing in with an existing Google account, and returns to the third-party site an identifier that the site can use to recognize the user. This identifier is consistent, enabling the third-party site to recognize the user across multiple sessions.

Note: OpenID authentication now supports Google Apps (hosted) accounts. 

OpenID authentication process

OpenID login authentication for web applications involves a sequence of interactions between your web application, Google's login authentication service, and the end user.

 

Working with OpenID

1. The web application asks the end user to log in by offering a set of log-in options, including using their Google account.


2. Login by credentials.

 3. The web application sends a "discovery" request to Google to get information on the Google login authentication endpoint.

4. Google returns an XRDS document, which contains the endpoint address and then web application sends a login authentication request to the Google endpoint address.

5. Once logged in, Google displays a confirmation page and notifies the user that a third-party application is requesting authentication. Page ask for allow approval and don't approval.


6. If the user approves the authentication, Google returns the user details.

7. If you want to retrieve the user's details of currently logged in google user, then use OpenAuth/OpenID. For .Net, a library is available to do all this task, DotNetOpenAuth. Download it, extract it and add in your bin folder of application.

Source Code:


Add code in your login.aspx page:

<style type="text/css">
.btngoogle
{
    background-image:url(images/google+login+button.png);
    border:1px solid white;
    cursor:pointer;
    }
</style>
<script type="text/javascript">
    function showimage() {
        var i = document.getElementById("imggoogle");
        i.src = "images/google+logout+button.png";
        i.style.border = "1px solid white";
    }

</script>
<asp:Button ID="btnLoginToGoogle" runat="server" OnCommand="OpenLogin_Click"
                            ToolTip="Google_Login" CssClass="btngoogle"
                            CommandArgument="https://www.google.com/accounts/o8/id" Height="34px"
                            Width="143px" />
  <a id="btngmaillogout" runat="server" onserverclick="btngmaillogout_click"> 
        <img src="http://accounts.google.com/logout" id="imggoogle" title="Google_LogOut" onerror="javascript:return showimage();" />
    </a>

 Add code in login.aspx.cs page

using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

OpenIdRelyingParty openid = new OpenIdRelyingParty();
       
        protected void Page_Load(object sender, EventArgs e)
        {
                HandleOpenIDProviderResponse();        
        }

        protected void HandleOpenIDProviderResponse()
        {          
                var response = openid.GetResponse();
              
                    if (response != null)
                    {
                        switch (response.Status)
                        {
                            case AuthenticationStatus.Authenticated:
                                NotLoggedIn.Visible = false;
                                btngmaillogout.Visible = true;

                                var fetchResponse = response.GetExtension<FetchResponse>();
                                Session["FetchResponse"] = fetchResponse;
                                var response2 = Session["FetchResponse"] as FetchResponse;

                                lblemail.Text = response2.GetAttributeValue(WellKnownAttributes.Contact.Email);
                                lblname.Text = GetFullname(response2.GetAttributeValue(WellKnownAttributes.Name.First),response2.GetAttributeValue(WellKnownAttributes.Name.Last));
                                lblbirthdate.Text = response2.GetAttributeValue(WellKnownAttributes.BirthDate.WholeBirthDate);
                                lblphone.Text = response2.GetAttributeValue(WellKnownAttributes.Contact.Phone.Mobile);
                                lblgender.Text = response2.GetAttributeValue(WellKnownAttributes.Person.Gender);
                                break;
                            case AuthenticationStatus.Canceled:
                                lblAlertMsg.Text = "Cancelled.";
                                break;
                            case AuthenticationStatus.Failed:
                                lblAlertMsg.Text = "Login Failed.";
                                break;
                        }
                    }
                    else
                    {
                        return;
                    }
        }

        protected void OpenLogin_Click(object src, CommandEventArgs e)
        {
            string discoveryUri = e.CommandArgument.ToString();
            var b = new UriBuilder(Request.Url) { Query = "" };
            var req = openid.CreateRequest(discoveryUri, b.Uri, b.Uri);
            var fetchRequest = new FetchRequest();
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Person.Gender);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Phone.Mobile);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.BirthDate.WholeBirthDate);
            req.AddExtension(fetchRequest);
            req.RedirectToProvider();
        }

        private static string GetFullname(string first, string last)
        {
            var _first = first ?? "";
            var _last = last ?? "";
            if (string.IsNullOrEmpty(_first) || string.IsNullOrEmpty(_last))
                return "";
            return _first + " " + _last;
        }

        protected void btngmaillogout_click(object sender, EventArgs e)
        {
           // logout from gmail and return to website default/home page    
            Response.Redirect("~/Default.aspx");        
        }

Download Files  google_login.rar

That’s it! Execute the page and see it in action.
Now you can easily access gmail logged in user details in your asp.net website. If you have any query, please feel free to ask.


Monday, 11 June 2012

Upload Multiple Attachment in Email With Progress Bar Using Uploadify in asp.net

We develop a system where users can select multiple files at a time and upload it one by one or in parallel with a progress bar and cancel button near it, simply like a GMAIL style upload system.

Something like:

1. Select multiple files


2. Upload multiple files


How to do this?

 

This can be done very easily by using a JQuery file upload plug-in called Uploadify which uses flash for rich Ajax like interface.

If you are not familiar with Uploadify here is a description from their web site:
"Uploadify is a jQuery plugin that integrates a fully-customizable multiple file upload utility on your website. It uses a mixture of JavaScript, ActionScript, and any server-side language to dynamically create an instance over any DOM element on a page."
You will need to download the JQuery plugin. Download this plugin from here.
http://www.uploadify.com/download/
after u download this file, extract this folder and put it in the root folder of your project. I add it into my "_scripts" folder like:


Now Add code in your aspx page ("Default.aspx")

<head>
<link href="_scripts/uploadify.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="_scripts/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="_scripts/swfobject.js"></script>
    <script type="text/javascript" src="_scripts/jquery.uploadify.v2.1.4.min.js"></script>
    <title>Multiple Upload</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#fuFiles').uploadify({
                'uploader': '_scripts/uploadify.swf',
                'script': 'Default.aspx',
                'cancelImg': '_scripts/cancel.png',
                'auto': 'true',
                'multi': 'true',
                'buttonText': 'Add Attachment',
                'queueSizeLimit': 5,
                'simUploadLimit': 1,
                'fileExt': '*.pdf;*.txt;*.doc',
                'fileDesc': 'text Files',
                'sizeLimit': 5242880 // The size limit in bytes for each file upload(5MB).
            });
        });
    </script>  
</head>
<body>
 <form id="form1" runat="server">
 <div id="fuFiles"> 
  </div>
</form>
</body>

Add code in Default.aspx.cs


    HttpPostedFile postedFile;
    public string DestinationPath;
    protected void Page_Load(object sender, EventArgs e)
    {
       
        postedFile = Request.Files["FileData"];
        if (postedFile != null)
        {
            DestinationPath = Server.MapPath("~/Uploads//" + postedFile.FileName);
            postedFile.SaveAs(DestinationPath);
        }
    }

Download Files  MultipleUploads.rar

It's done just run your Default.aspx page and click on "Add Attachment" button to upload the file.if u face any problem feel free to comment.

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.