European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Hosting - Amsterdam :: Integrate Facebook Using ASP.NET

clock March 25, 2013 10:41 by author Scott

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!

Then, run your application/site. Hope this tutorial help.



European ASP.NET 4.5 Hosting - Amsterdam :: Create ASP.NET 4.5 File Security Process

clock March 20, 2013 07:24 by author Scott

Often when working with web applications it is necessary to secure access to documents or other user supplied resources.  If you look online you will find a number of different recommendations on how to accomplish this.  Some will recommend a HTTP Handler, some will recommend a simple ASPX, others will have other random ideas.  Regardless of the actual implementation there is always a common area of mixed recommendation, once you have validated that the user has the proper permissions to access the resource, how do you get the item to the user?  In this post I'll discuss a new API that is publicly available in .NET 4.5 that helps with one problem area.

The Problem

Determining if the user has access to the resource in question is rarely the area that causes trouble.  The problem comes with the process of serving the desired files to the user.  When you let IIS handle the serving of a file it automatically sets the Content Type on the HTTP Response to match the proper type for the file, however, if you are sitting in the middle of this process, you have to handle this yourself.

Recommendation to Solve Issue

If you look into this issue, try googleing "Determining File MIME Types" or similar.  You will find all kinds of recommendations.  They will range from creating a custom look up process based on file extension, to weird PInvoke calls into windows, or even from the really crafty individuals a reflection call to an internal member of previous versions of the .NET framework.

In the end, there has never really been a good, consistent way to handle this.  Often times if you are working with a limited subset of file types the switch statement solution will work, however, as new file types are added etc it becomes harder to manage.

New Solution

With .NET 4.5, there is a newly exposed class that can be used to solve this complicated process.  System.Web.MimeMapping is a class that has existed for a while prior to .NET 4.5 but was "internal" to the framework and could not easily be called without using reflection.  Now you can simply call a method with a file path and it will return the Content Type.

This makes it so that we can now use something as simple as the following to serve a secured document after validating that the user has permissions.

Response.Clear();
Response.ContentType =
  System.Web.MimeMapping.GetMimeMapping(Server.MapPath(document.ServerDocumentPath));
Response.AddHeader("Content-Disposition",
                    "attachment; filename=" + document.UploadedDocumentName);
Response.WriteFile(Server.MapPath(document.ServerDocumentPath));
Response.End();

As you can see here, it is just 5 lines of code. In the first line of code we clear anything that  might have already been written to the response.  In the second line we call out to MimeMapping's GetMimeMapping method providing it the filepath to our document.  The third line we are telling the browser that we want to force download the file and are specifying a custom file name.  Then in the last two lines we write the file to the response and end.

The nice thing with this approach as you can see in the above example we can have a different ServerDocumentPath than our actual document name.  This allows us to hide the files in a different manner and serve them up to users with a friendly name.

I hope this helps someone looking for a way to introduce a security process to file downloads.  This .NET framework MimeType mapping is very helpful for this type of situation.



European ASP.NET Hosting - Amsterdam :: Tips Submit Form with ASP.NET

clock March 11, 2013 06:11 by author Scott

In this article I try to explain the default submit behavior of form and panel. Suppose, you want to press/click submit button on Enter key press or you are trying to post the form on Enter key press. In asp.net, to achieve this functionality we need to set "Defaultbutton" property either in Form or in panel.

Form DefaultButton Property

     <form id="form1" runat="server" defaultbutton="btnSubmit">
    <div>
    <asp:TextBox ID="txtUserID" runat="server"/> <asp:TextBox ID="txtUserpwd" runat="server"/> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit _Click" Text="Submit"/>
    </div>
    </form>

Panel DefaultButton Property

     <asp:Panel ID="Panel1" runat="server" defaultbutton="btnSubmit">
    <div>
    <asp:TextBox ID="txtUserID" runat="server"/> <asp:TextBox ID="txtUserpwd" runat="server"/> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit _Click" Text="Submit"/>
    </div>
    </asp:Panel >

Note

1. We specify the defaultbutton property at the Form level in the form tag when there is only one Submit Button for post back.

2. We specify the defaultbutton property at the Panel level in the Panel tag when there are multiple Submit Button for post back.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in