Tuesday 6 January 2015

How to Create Facebook Login In Asp.Net using JQuery

How to create App Id In Facebook
===========================================================



---------------------For Login Button and show facebook Login Screen---------------------------
<script src="../js/jquery-latest.js"></script>

     <script>
         window.fbAsyncInit = function () {
             FB.init({
                 appId: 'Your App Id',
                 xfbml: true,
                 version: 'v2.2'
             });
         };

         (function (d, s, id) {
             var js, fjs = d.getElementsByTagName(s)[0];
             if (d.getElementById(id)) { return; }
             js = d.createElement(s); js.id = id;
             js.src = "//connect.facebook.net/en_US/sdk.js";
             fjs.parentNode.insertBefore(js, fjs);
         }(document, 'script', 'facebook-jssdk'));
</script>
    <script type="text/javascript">
        function loginByFacebook() {
            debugger;
            FB.login(function (response) {
                if (response.authResponse) {
                    FacebookLoggedIn(response);
                } else {
                    console.log('User cancelled login or did not fully authorize.');
                }
            }, { scope: 'user_birthday,user_about_me,user_hometown,user_location,email,publish_stream' });
        }

        function FacebookLoggedIn(response) {
            debugger;
            $.ajax({

                url: "Login.aspx/FetchUserList",
                data: "{ 'access_token': '" + response.authResponse.accessToken + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    $.each(data.d, function (i, item) {

                        if (item.Regstatus == "Registered") {
                            var loc = '/FMSDashboard.aspx';
                            window.location.href = loc;
                        }

                        else {
                            var loc = 'FacebookRegistraion.aspx';

                            if (loc.indexOf('?') > -1)
                                window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
                            else
                                window.location = loc + '?authprv=facebook&access_token=' + response.authResponse.accessToken;
                        }

                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });


        }
    </script>
------------------------------------LoginIn Design---------------------------------------------------------------------
 <a>  <input id="btnFbLogin" type="button" value="Facebook Login" class="btn btn-info pull-left" onclick="loginByFacebook();" /></a>

--------------------In Page Behind Write This Code Means C# Page----------------------------------------
  private static string GetFacebookUserJSON(string access_token)
    {
        string url = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name,first_name,last_name,link,gender", access_token);

        WebClient wc = new WebClient();
        Stream data = wc.OpenRead(url);
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        data.Close();
        reader.Close();

        return s;
    }
    [WebMethod]
    public static List<FacebookUser> FetchUserList(string access_token)
    {
        //CloudStorageAccount account = new CloudStorageAccount(
        //            new StorageCredentials(EnumStorageCredentialsAccount1.StorageName, EnumStorageCredentialsAccount1.StorageKey), true);
        //CloudTableClient tableClient = account.CreateCloudTableClient();
        //CloudTable table = tableClient.GetTableReference("users");
        //table.CreateIfNotExistsAsync();
        //TableQuery<UserEntity> query = new TableQuery<UserEntity>();
        //List<UserEntity> lst = table.ExecuteQuery(query).ToList();

        List<FacebookUser> _AppUser = new List<FacebookUser>();
        string json = GetFacebookUserJSON(access_token);
        //and Deserialize the JSON response
        JavaScriptSerializer js = new JavaScriptSerializer();
        FacebookUser oUser = js.Deserialize<FacebookUser>(json);


        //if (lst.Where(x => x.PartitionKey == oUser.email).ToList().Count > 0)
        //{
        //    HttpContext.Current.Session["uname"] = oUser.email;
        //    oUser.Regstatus = "Registered";
        //}
        _AppUser.Add(oUser);
        return _AppUser;
    }
    public class FacebookUser
    {
        public long id
        { get; set; }

        public string email
        { get; set; }

        public string name
        { get; set; }

        public string first_name
        { get; set; }

        public string last_name
        { get; set; }

        public string gender
        { get; set; }

        public string link
        { get; set; }

        public DateTime updated_time
        { get; set; }

        public DateTime birthday
        { get; set; }

        public string locale
        { get; set; }

        public string picture
        { get; set; }

        public FacebookLocation location
        { get; set; }

        public string MobileNo
        { get; set; }

        public string Regstatus
        { get; set; }

    }

    public class FacebookLocation
    {
        public string id
        { get; set; }

        public string name
        { get; set; }
    }

    public class FBRegistrationDetails
    {
        public long id
        { get; set; }

        public string email
        { get; set; }

        public string name
        { get; set; }

        public string first_name
        { get; set; }

        public string last_name
        { get; set; }

        public string gender
        { get; set; }

        public string OrgName
        { get; set; }

        public string OrgUrl
        { get; set; }
        public string OrgDomain
        { get; set; }

        public string MobileNo
        { get; set; }

        public string ProfilePicUrl
        { get; set; }

    }
=========================================================
When Login Successfull At that time login dat retrive from Facebook Database
============================================================
In View Page Design  And Code and the page name is FacebookRegistraion
------------------------------------------------------
    <div style="margin-left: 15px; margin-right: 15px">

                                    <div class="form-group">
                                          <input type="hidden" id="hdnfbid" />
                                        <input type="text" class="form-control" id="txtFirstname" placeholder="First name"/>
                                    </div>
                                    <div class="form-group">
                           
                                        <input type="text" class="form-control" id="txtLastname" placeholder="First name"/>
                                    </div>
                                    <div class="form-group">
                                         <input type="text" class="form-control" id="txtEmail" placeholder="Email address"/>
                                       
                                    </div>

                                    <div class="form-group">
                                       <input type="text" class="form-control" id="txtOrgName" placeholder="Organization Name"/>
                                    </div>

                                    <div class="form-group">
                                         <input type="text" class="form-control" id="txtOrgUrl" placeholder="Organization Url"/>
                                    </div>


                                    <div class="form-group">
                                   
                                        <select id="ddlgender" class="form-control">
                                            <option value="0" selected="" disabled="">Gender</option>
                                            <option value="1">Male</option>
                                            <option value="2">Female</option>
                                            <option value="3">Other</option>
                                        </select>
                                                 <i></i>

                                    </div>
                                    <div class="form-group">
                                         <input type="text" class="form-control" id="txtMobile" placeholder="Mobile No"/>
                                    </div>

                                    <div class="form-group">
                                        <div class="row" style="margin-left: 115px;">
                                             <img id="fbimgid" src="#" />
                                </div>
                                    </div>

                                    <div class="form-group">
                                        <div class="checkbox">
                                            <label>
                                             <input type="checkbox" id="chkSelect" name="checkbox"><i></i>I agree to the Terms of Service</label>
                                     
                                        </div>
                                    </div>

                                    <div class="form-group">
                                          <button type="button" class="button" id="btnSave">Submit</button>
                                    </div>
                         
                    </div>
=================================================================
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            var access_token = GetParameterValues('access_token');
            //alert(name);
            var fbid = 0;
            $.ajax({
                //url: "FB_Registration.aspx/FetchUserList",
                url: "Login.aspx/FetchUserList",
                data: "{ 'access_token': '" + access_token + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    $.each(data.d, function (i, item) {

                        if (item.Regstatus == "Registered") {
                            var loc = '/FMSDashboard.aspx';
                            window.location.href = loc;
                        }

                        else {
                            $("#txtFirstname").val(item.first_name);
                            $("#txtLastname").val(item.last_name);
                            $("#txtEmail").val(item.email);
                            $("#txtMobile").val('');
                            $("hdnfbid").val(item.id);

                            $('#txtFirstname').attr("disabled", "disabled");
                            $('#txtLastname').attr("disabled", "disabled");
                            $('#txtEmail').attr("disabled", "disabled");
                            $('#ddlgender').attr("disabled", "disabled");
                            var genderid = 0;
                            if (item.gender == "male") {
                                genderid = 1;
                            }
                            else if (item.gender == "female") {
                                genderid = 2;
                            }
                            $("#ddlgender").val(genderid);
                            //alert( item.id);
                            $("#fbimgid")[0].src = "http://graph.facebook.com/" + item.id + "/picture?height=110&type=normal&width=110";
                        }

                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });


            $("#btnSave").click(function () {
                // alert('click');
                var isValidated = true;
                $("#regErrors").html('');
                var fbid = $("hdnfbid").val();
                var txtOrgDomain = $("#txtOrgDomain").val();
                var txtFirstname = $("#txtFirstname").val();
                var txtLastname = $("#txtLastname").val();
                var txtEmail = $("#txtEmail").val();
                var txtOrgName = $("#txtOrgName").val();
                var txtOrgUrl = $("#txtOrgUrl").val();
                var txtMobile = $("#txtMobile").val();
                var ddlgender = $("#ddlgender").val();
                var ProfilePicUrl = $("#fbimgid").attr('src');
                var isChecked = $('#chkSelect:checked').val() ? true : false;
                var name = txtFirstname + ' ' + txtLastname;
                // alert(isChecked);
                if (isChecked) {
                    if (txtOrgName == "") {
                        $('#txtOrgName').focus();
                        isValidated &= false;

                    }
                    else if (txtOrgUrl == "") {
                        $("#txtOrgUrl").focus();
                        isValidated &= false;

                    }
                    else if (txtMobile == "") {
                        $("#txtMobile").focus();
                        isValidated &= false;

                    }

                    if (isValidated == true) {

                        var gender = "";
                        if (ddlgender == 1) {
                            gender = "Male";
                        }
                        else if (ddlgender == 2) {
                            gender = "Female";
                        }

                        var user = {};
                        //var str = [{ id: fbid, email: txtEmail, name: name, first_name: txtFirstname, last_name: txtLastname, gender: ddlgender, OrgName: txtOrgName, OrgUrl: txtOrgUrl, OrgDomain: txtOrgDomain, MobileNo: txtMobile, ProfilePicUrl: ProfilePicUrl }];
                        user.id = fbid;
                        user.email = txtEmail;
                        user.name = name;
                        user.first_name = txtFirstname;
                        user.last_name = txtLastname;
                        user.gender = gender;
                        user.OrgName = txtOrgName;
                        user.OrgUrl = txtOrgUrl;
                        user.OrgDomain = txtOrgUrl;
                        user.MobileNo = txtMobile;
                        user.ProfilePicUrl = ProfilePicUrl;
                        $.ajax({
                            type: "POST",
                            url: "FB_Registration.aspx/InsertFBDetails",
                            data: '{item: ' + JSON.stringify(user) + '}',
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            async: false,
                            success: function (data) {
                                //alert(data);
                                // alert(data.d);
                                // alhttp://www.c-sharpcorner.com/UploadFile/c4cfca/how-to-save-data-into-database-using-jquery-and-json-in-asp/Images/Result.jpgert(data);
                                if (data.d == "Saved") {
                                    // alert('saved');
                                    var loc = '/FMSDashboard.aspx';
                                    // if (loc.indexOf('?') > -1)
                                    //window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
                                    window.location.href = loc;
                                }
                                else {
                                    alert('' + data + '');
                                }
                            }
                        });
                    }

                }
                else {
                    alert('Please check I agree to the Terms of Service.');
                }
            });



        });

        function GetParameterValues(param) {
            var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < url.length; i++) {
                var urlparam = url[i].split('=');
                if (urlparam[0] == param) {
                    return urlparam[1];
                }
            }
        }
    </script>

1 comment:

  1. Blogspot Blogger Sitemap Generator special (Google - Yahoo - Bing)Gadgets For Blogger - Ideally, a sitemap file must contain all the URLs from a site, but if our blog hosted on blogspot. create facebook login

    ReplyDelete