Post on Facebook Wall From GridView

Introduction

In this article, I will show you how to post on a Facebook Wall from a GridView.

This article shows how to post various data from multiple rows of a GridView. I will create an application where every row will have a button and every button will post the data in it's row.

Step 1

First of all you need to create an app on the developers profile of Facebook. This can be done by clicking on this link: Facebook Developers

As you create the application you will get an "app_id" and "app_secretId", these ID's will help you to utilize your app using .NET.

post on fb using grid 

Step 2

Now create a new application on .NET and add Facebook Nugets, for adding the Nugets first open the "Package Manager Console".

Nugets can be installed by writing this simple line in the console: "PM> Install-Package Facebook".

post on fb using grid

Step 3

Now create a Grid and add a button to each column in this manner:

<asp:GridView ID="GridView1" runat="server" CellPadding="4" OnRowCommand=
    "GridView1_RowCommand1" ForeColor="#333333" GridLines="None">
    <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:TemplateField HeaderText="Share To">
                <ItemTemplate>
                    <asp:Button ID="btnFB" runat="server" Text="Facebook" CommandName="Facebook" />
                </ItemTemplate>
             </asp:TemplateField>
        </Columns>
    <EditRowStyle BackColor="#2461BF" />
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#EFF3FB" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F5F7FB" />
    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
    <SortedDescendingCellStyle BackColor="#E9EBEF" />
    <SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>

Bind the Grid with the data that is to be posted on the Facebook Wall, do this on the page load:

public string Url { get { return ("http://localhost:2754/WebApplication80/SharePage.aspx&quot;); } }
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        con = new SqlConnection(@"Your Connection");
        con.Open();
        com = new SqlCommand("select * from Feedback", con);
        SqlDataAdapter adp = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

The URL that you are seeing is the URL of the user to be redirected after posting the data on Facebook.

Step 4

Now we need to provide the coding for the button click in the grid, write this code in the row event of the Grid: 

protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
    GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer; 
    int rowIndex = gvr.RowIndex; 
    if (e.CommandName == "Facebook")
    { 
        string app_id = "Your App Id";
        string app_secret = "Your App Secret";
        string scope = "publish_stream,manage_pages,email";
        if (Context.Session["AccessToken"] != null)
        {
            var client = new FacebookClient(Context.Session["AccessToken"].ToString()); 
            client.Post("/me/feed", new
            {
                message = GridView1.Rows[rowIndex].Cells[4].Text,
                name = "C-SharpCorner.Com",
                link = "http://www.c-sharpcorner.com/conference2014/&quot;,
                picture = "http://www.c-sharpcorner.com/conference2014/gallery/2013/image1Thumb.jpg&quot;,
                description = GridView1.Rows[rowIndex].Cells[3].Text
            });
        }
        else
        {
            Response.Redirect(string.Format(
               "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}"
               app_id, "http://localhost:2754/WebApplication80/WebForm2.aspx&quot;, scope));
        }
    }
}

This code will check whether or not an access token is available, in other words whether or not the user is logged in, if the user is not logged in then the Facebook login page will be shown and the user will need to authenticate himself by providing his user name and password, this will create an access token for posting on the user's wall. On getting the user's access token he will be redirected to WebForm2, a new page that I added to my application.

Step 5

Write this code on the page load of WebForm2:

protected void Page_Load(object sender, EventArgs e)
{
    string app_id = "Your App Id";
    string app_secret = "Your App Secret";
    string scope = "publish_stream,manage_pages,email";
    if (Request["code"] != null)
    {
        Dictionary<string, string> tokens = new Dictionary<string, string>();
        string url = string.Format("https://graph.facebook.com/oauth/access_token?
                    client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                    app_id, "http://localhost:2754/WebApplication80/WebForm2.aspx", 
                       scope, Request["code"].ToString(), app_secret); 
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream()); 
            string vals = reader.ReadToEnd(); 
            foreach (string token in vals.Split('&'))
            {
                tokens.Add(token.Substring(0, token.IndexOf("=")),
                  token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
            }
        }
        string access_token = tokens["access_token"];
        Context.Session["AccessToken"] = access_token;
        Response.Redirect("~/SharePage.aspx"); 
    }
}

This page uses oauth for posting the content to the Facebook wall, this code will check the app Id and secret Id of the app and will correspondingly grant the permission to post.

It will redirect the user to SharePage.aspx that was our main page. This time share page will get the access token and it's If condition will execute and will post the data.

Output

On running the application you will get an output like this one:

post on fb using grid

Now I will click on the "Facebook" button and since I was not logged on you can see that the Facebook account is asking me to log in first.

post on fb using grid

You can see a change in the URL, in other words now it has the access token for posting the data on the Facebook Wall.

post on fb using grid

Now I click on the button of that row that I want to post to Facebook and you can see that it's posted on my wall.

 


Similar Articles