Facebook external login using oauth returns null email


Need to install Facebook SDK from NuGet packages.
In StartUp File
app.UseFacebookAuthentication(new FacebookAuthenticationOptions { AppId = "XXXXXXXXXX", AppSecret = "XXXXXXXXXX", Scope = { "email" }, Provider = new FacebookAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); return Task.FromResult(true); } } });
In Controller or Helper
var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie); var accessToken = identity.FindFirstValue("FacebookAccessToken"); var fb = new FacebookClient(accessToken); dynamic myInfo = fb.Get("/me?fields=email,first_name,last_name,gender"); // specify the email field
Sorce: Facebook external login using oauth returns null email

Twitter external login using oauth returns null email


For getting twitter user email using oauth external login we need to getting the Twitter support to allow the permission on our app. Please refer this link : Get user’s email address from twitter OAuth API in .Net applications

Using StreamReader To Read HTML File/TextFile

Here I will explain how to read text or html file using StreamReader
In previous articles I explained write a html file using StreamWriter,now I will explain how to read text or html file using StreamReader.


we need to write the following code in aspx page

<asp:Button ID="btnread" runat="server" Text="Read" onclick="btnread_Click" />      


Now in code behind add the following namespaces
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnread_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(Request.PhysicalApplicationPath + "nam_email.htm");
        while (sr.Peek() >= 0)
        {
            Response.Write(sr.ReadLine() + "<br />");
        }
        sr.Close();
    }
}                  
           

   
 


Using StreamWriter To Write HTML File

Here, I will explain how to add textbox text into HTML file using StreamWriter.
First,we need to write the following code in aspx page.
Default.aspx


<div>
        <table border="1">
            <tr>
                <td>
                    <asp:Label ID="lbnname" runat="server" Text="Name"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lbnemail" runat="server" Text="Email"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnwrite" runat="server" Text="Write" 
                        onclick="btnwrite_Click" />
                </td>
                <td>                    
                    <asp:Button ID="btnreset" runat="server" Text="Reset" 
                        onclick="btnreset_Click" />
                </td>
            </tr>         
        </table>
    </div>

    
Now, first we add namespace System.IO  in Default.aspx.cs  page  and also add html file  from addNewItem  and give "name nam_email.htm".
 Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnwrite_Click(object sender, EventArgs e)
    {       
        int id = 0,;   
        StreamWriter sw = new StreamWriter(Request.PhysicalApplicationPath + "nam_email.htm", true);      
       sw.WriteLine("<tr><td>" + id +"</td><td>" + txtname.Text + "</td><td>" + txtemail.Text + "</td></tr>");        
        sw.Close();
    }  
    protected void btnreset_Click(object sender, EventArgs e)
    {
        txtname.Text = string.Empty;
        txtemail.Text = string.Empty;
    } 
}

Create Cookie In C#

Here simple code for creating cookie and value show on button click..!!

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

public partial class _Default : System.Web.UI.Page
{
    HttpCookie mycookie = new HttpCookie("malvik");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["malvik"] != null)
        {
         
            Response.Write(Request.Cookies["malvik"].Value);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        mycookie.Value = TextBox1.Text;
        mycookie.Expires = DateTime.Now.AddMinutes(1);
        Response.Cookies.Add(mycookie);
   
    }
    protected void btn1_Click(object sender, EventArgs e)
    {
        Page.Theme = "Theme1";
    }
}

3 Tier Architecture Example In Asp.Net With C#

Here I will how to create or implement 3-tier architecture for our project in asp.net 
Basically 3-Tier architecture contains 3 layers

1.    Property Layer 
2.    Business Logic Layer(BLL
3.    Data Access Layer(DAL)

Here I will explain each layer with simple example that is MangeCategory page


Now, let us see what we have here in Visual Studio 2010 projects. We try to make the source code folder structure clear and simple; below is the folder structure for the whole application in solution explorer of Visual Studio:


Property Layer

Property layer contains UI part of our application i.e., our aspx pages or input is taken from the user. This layer mainly used for design purpose and get or set the data back and forth. Here I have designed my ManageCategory aspx page like this.


This is Property Layer for our project Design your page like this and double click on button Add now in code behind we need to write statements to insert data into database this entire process related to Business Logic Layer and Data Access Layer.

PropertyLayer(PL)
PL.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PropertyLayer
{
    public class PL
    {
        private string _Id;
        private string _CategoryName;
        private string _ImageName;  
        public string Id
        {
            get { return _Id; }
            set { _Id = value; }
        } 
        public string CategoryName
        {
            get { return _CategoryName; }
            set { _CategoryName = value; }
        }

        public string ImageName
        {
            get { return _ImageName; }
            set { _ImageName = value; }
        }                                   
    }
} 

Now we will discuss about Business Logic Layer 

Business Logic Layer (BLL)



This layer contains our business logic, calculations related with the data like insert data, retrieve data and validating the data. This acts as a interface between Application layer and Data Access Layer



Now I will explain this business logic layer with my sample



Don't get confuse just follow my instructions enough

How we have to create entity layer it is very simple 


Right click on your project web application---> select add new item ----> select class file in wizard --->give name as BLL.CS because here I am using this name click ok

 Open the BLL.CS class file declare the parameters like this in entity layer 

Don’t worry about code it’s very simple for looking it’s very big nothing is there just parameters declaration that’s all check I have declared whatever the parameters I need to pass to data access layer I have declared those parameters only 

BLL.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAcessLayer;
using System.Data;
using PropertyLayer;
using System.Data.SqlClient;
  
namespace BussinessLogicLayer
{
    public class BLL
    {
        public DataTable GetCategoryData()
        {
            DL objCategoryData = new DL();
            return objCategoryData.DataSet("usp_BindCategory");
        }

        public int AddCategoryDetails(PL objCategoryPL)
        {          
            SqlParameter[] sqlparam = new SqlParameter[2];
            sqlparam[0] = new SqlParameter("@Name",objCategoryPL.CategoryName);
            sqlparam[1] = new SqlParameter("@Image", objCategoryPL.ImageName);

            DL objCategoryDetails = new DL();
            return objCategoryDetails.ExecuteNonQuery("usp_AddCategory",sqlparam);          
        }

        public void UpdateCategoryDetails(PL objUpdateCategoryPL)
        {
            SqlParameter[] sqlparam = new SqlParameter[3];
            sqlparam[0] = new SqlParameter("@Id",objUpdateCategoryPL.Id);
            sqlparam[1] = new SqlParameter("@Name",objUpdateCategoryPL.CategoryName);
            sqlparam[2] = new SqlParameter("@Image",objUpdateCategoryPL.ImageName);

            DL objUpdateCategoryDetails = new DL();
            objUpdateCategoryDetails.ExecuteNonQuery("usp_UpdateCategoryDetails",sqlparam);
        }

        public void DeleteCategoryDetails(PL objDeleteCategoryPL)
        {
            SqlParameter[] sqlparam = new SqlParameter[1];
            sqlparam[0] = new SqlParameter("@Id",objDeleteCategoryPL.Id);

            DL objDeleteCategoryDetails = new DL();
            objDeleteCategoryDetails.ExecuteNonQuery("usp_DeleteCategoryDetails",sqlparam);
        } 
    }
}

Data Access Layer(DAL)



Data Access Layer contains methods to connect with database and to perform insert,update,delete,get data from database based on our input data



I think it’s to much data now directly I will enter into DAL



Create one more class file like same as above process and give name as DL.CS

Write the following code in DL class file

DL.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace DataAcessLayer
{
    public class DL
    {
        private readonly string _Connection = string.Empty;

        public DL()
        {
            _Connection = WebConfigurationManager.AppSettings["PrestaShopDatabse"].ToString();
        }

        public DataTable DataSet(string SPname)
        {
            SqlConnection con = new SqlConnection(_Connection);                  
            SqlDataAdapter da = new SqlDataAdapter(SPname,con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;          
        }

        public int ExecuteNonQuery(string SPname,params SqlParameter[] sqlparam)
        {
            SqlConnection con = new SqlConnection(_Connection);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = SPname;


Here if you observe above functionality I am getting all the parameters by simply creating BLL. If we create one entity file we can access all parameters through out our project by simply creation of one object for that entity class based on this we can reduce redundancy of code and increase re usability


Now our Business Logic Layer is ready and our Data access layer is ready now how we can use this in our application layer write following code in your Add button click like this and  that data  show in Gridview  and also update,delete event .

ManageCategory.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using BussinessLogicLayer;
using PropertyLayer;
  
namespace Prestashop
{
    public partial class ManageCategory : System.Web.UI.Page
    {
   
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack == false)
            {
                gvCategoryBind();
            }
            else
            {
                DataTable dtCategory = (DataTable)ViewState["dtCategory"];
            }
        }

        protected void gvCategoryBind()
        {
            BLL objGetCategoryData = new BLL();
            DataTable dtCategory = new DataTable();
            dtCategory = objGetCategoryData.GetCategoryData();
            ViewState["dtCategory"] = dtCategory;
          //  DataTable dtCategory = (DataTable)ViewState["dtCategory"];
            gvCategory.DataSource = dtCategory;
            gvCategory.DataBind();
        }

        protected void btnadd_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = Path.GetFileName(fuploadcategory.PostedFile.FileName);
                fuploadcategory.SaveAs(Request.PhysicalApplicationPath + "Images/"+txtcategoryname.Text+".jpg");

                PL objAddCategoryPL = new PL();
                objAddCategoryPL.CategoryName = txtcategoryname.Text;
                objAddCategoryPL.ImageName = "Images/" + txtcategoryname.Text+".jpg";

                BLL objGetCategoryDetails = new BLL();
                int check;
                check = objGetCategoryDetails.AddCategoryDetails(objAddCategoryPL);
                if (check == 0)
                {
                    Response.Write("Category Not Added");
                }
                else
                {
                    Response.Redirect("ManageCategory.aspx");
                    Response.Write("Category Added");
                }
            }
            catch (Exception ee)
            { } 
        }

        protected void gvCategory_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvCategory.EditIndex = e.NewEditIndex;
            gvCategoryBind();
        }

        protected void gvCategory_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {         
            PL objCategoryDetails = new PL();
            objCategoryDetails.Id = gvCategory.Rows[e.RowIndex].Cells[0].Text;
            objCategoryDetails.CategoryName = ((TextBox)gvCategory.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
            objCategoryDetails.ImageName = "Images/" + objCategoryDetails.CategoryName + ".jpg";
            ((FileUpload)gvCategory.Rows[e.RowIndex].FindControl("fuploadEditGv")).SaveAs(Request.PhysicalApplicationPath + "Images/" + objCategoryDetails.CategoryName + ".jpg");
           
            BLL objUpdateCategoryDetails = new BLL();
            objUpdateCategoryDetails.UpdateCategoryDetails(objCategoryDetails);       
            gvCategory.EditIndex = -1;
            gvCategoryBind();
            Response.Redirect("ManageCategory.aspx");          
        }

        protected void gvCategory_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvCategory.EditIndex = -1;
            gvCategoryBind();
        }

        protected void btncancle_Click(object sender, EventArgs e)
        {
            txtcategoryname.Text = "";           
        }

        protected void gvCategory_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            PL objDeleteCategoryDetailsPL = new PL();
            objDeleteCategoryDetailsPL.Id = gvCategory.Rows[e.RowIndex].Cells[0].Text;

            BLL objDeleteCategoryDetails = new BLL();
            objDeleteCategoryDetails.DeleteCategoryDetails(objDeleteCategoryDetailsPL);
            gvCategoryBind();
            Response.Redirect("ManageCategory.aspx"); 
        }

        protected void gvCategory_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvCategory.PageIndex = e.NewPageIndex;
            gvCategoryBind();
        } 
    }
}

Store Procedure:

Select
ALTER PROCEDURE dbo.usp_BindCategory
AS
       Begin
        SELECT FROM Category
       End

 Delete
ALTER PROCEDURE dbo.usp_DeleteCategoryDetails
       @Id bigint
AS
      
       Begin
       DELETE FROM Category WHERE Id=@ID
       End
Update 
ALTER PROCEDURE dbo.usp_UpdateCategoryDetails
       @Id bigint,
       @Name nvarchar(50),
       @Image nvarchar(500)
AS
       Begin
        UPDATE Category SET Name=@Name,Image=@Image WHERE Id=@Id
       End
 InsertInto
ALTER PROCEDURE dbo.usp_AddCategory
       @Name nvarchar(50),
       @Image nvarchar(500)
AS
       Begin
       INSERT INTO Category (Name,ImageVALUES (@Name,@Image)

       End


I hope it helps you.