Friday, April 15, 2011

Tutorial - Post data on a Facebook Company Page as Admin

Its been a while I have blogged about something.
Have been working on the Facebook API and one of the requirement is to post data into a Facebook company page from one's website.

Here is a step by step procedure on posting data to a company page(on which you have admin rights) using the Facebook API.
Feel free to skip the first two steps if you know how to set up a Facebook Application and to create pages in Facebook.

Step 1 - Creating a Facebook Application

Sign in to your Facebook Account and key in the following URL to your address bar

Set Application Name as "My Demo Application"

Now I am adding the following data also to the Website tab of the core settings
(Lets come to that later)

Set Site URL as http://localhost/FacebookPost/

After entering, click on the Save Changes Button.
Now you will be re directed to a page where your App Settings are displayed.
Copy the values App ID, App Key and App Secret and store them securely.

Step 2 - Creating a Facebook Page

Now, key in the following URL to your address bar

Now select the Page Type. Here is what I selected.

Type : Company, Organisation (Click on the type you want to create.
Category : Computers/Technology
Comapany Name: MyCompany

Now agree to the Facebook Pages Terms and click Get Started.
Your page is created by Facebook and you will be landed on a URL like that
Please copy the PageID and store it securely.

Step 3 - Create a website locally in your system

Open up your Visual Studio and Create an empty website.
Create a page "Default.aspx" and run the website and allow the web.config to be created.

(I have mapped my site to my IIS with the application name FacebookPost.
Please note that it is being done to match the Site URL I have set at the Facebook Application Page)

Step 4 - Pick a Facebook C# SDK to communicate with the Facebook Graph API.

My research came up with two options
1. Use the Facebook's own lesser used SDK found at GitHub ( link here )

2. Use the more widely used third party C# SDK hosted at Codeplex ( link here )

I preferred Facebook's own SDK. Actually, you can also write your own API if you want. Its set of simple WebRequest/WebResponse. So I went to GitHub where the SDK was hosted and downloaded the folder named facebook and changed it to Facebook ( :) Pascal Casing) and pasted it inside my App_Code

Step 5 - Modify your AppSettings at web.config

Remember those AppID, AppKey, AppSecret, PageID I asked you to keep securely?
Lets now store them at AppSettings of web.config.
(Ideally you would be much better of encrypting them, but details on encrypting is beyond the scope of this tutorial.)

    <add key="AppID" value="Your App ID"/>
    <add key="AppKey" value="Your App Key"/>
    <add key="AppSecret" value="Your App Secret"/>
    <add key="PageID" value="Your Page ID"/>

Step 6 - Create a form for entering the data

Open up Default.aspx in Visual Studio and change Source like this.

<html xmlns="">
<head runat="server">
    <title>Codovations Demo - Posting to Facebook Company Page</title>
    <style type="text/css">
        .title {
    <form id="form1" runat="server">
    <label class="title">Message</label><asp:TextBox ID="MessageText" runat="server" TextMode="MultiLine" Width="200px"></asp:TextBox><br />
    <label class="title">Name</label><asp:TextBox ID="NameText" runat="server" Width="200px"></asp:TextBox><br />
    <label class="title">Description</label><asp:TextBox ID="DescriptionText" runat="server" TextMode="MultiLine" Width="200px"></asp:TextBox><br />
    <label class="title">Picture(URL)</label><asp:TextBox ID="PictureText" runat="server" Width="200px"></asp:TextBox><br />
    <label class="title">Caption</label><asp:TextBox ID="CaptionText" runat="server" Width="200px"></asp:TextBox><br />
    <label class="title">Link</label><asp:TextBox ID="LinkText" runat="server" Width="200px"></asp:TextBox><br />
    <label class="title"></label>
        <asp:Button ID="PostToCompanyButton" runat="server" 
                Text="Post to Company Page" onclick="PostToCompanyButton_Click"/>

Step 7 - Posting data on the Company Page.

This is the trickiest part in this project. Facebook provides no straight forward way to post data to a company page. Here is how we achieve that.

First we will request oAuth from Facebook and on successful authorisation we get an access token.
Using the token we fetch "me/accounts" and will check in that account array, an account that matches the stored PageID. If found, we fetch the associated accesstoken for that page. When we get that we post the content to "me/feeds" using that accesstoken like this.

if (Request.Params["code"] != null)
    Status.Text = "";
    string accessToken = GetAccessToken(Request.Params["code"]);
    FacebookAPI api = new FacebookAPI(accessToken);

    JSONObject me = api.Get("me/accounts");
    Dictionary dictionary = me.Dictionary;
    JSONObject myPage = me.Dictionary["data"].Array
        .SingleOrDefault(d => d.Dictionary["id"].String.Equals(ConfigurationManager.AppSettings["PageID"].ToString()));
    if (myPage != null)
        Dictionary parameters = Session["DataForFacebook"] as Dictionary;
        string newToken = myPage.Dictionary["access_token"].String;
        var app = new FacebookAPI(newToken);
        var response = app.Post("me/feed", parameters);
        if (response != null && response.Dictionary[""] != null)
            Status.Text = "Data posted successfully to company page.";
            Status.Text = "An error occured while posting.";

Two helper methods used are

private string GetAccessToken(string accessToken)
        Dictionary args = GetOauthTokens(accessToken);
        return args["access_token"];

    private Dictionary GetOauthTokens(string accessToken)
        Dictionary tokens = new Dictionary();
            string url = String.Format("{0}client_id={1}&redirect_uri={2}&client_secret={3}&code={4}&scope={5}",

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string retVal = reader.ReadToEnd();

                foreach (string token in retVal.Split('&'))
                    tokens.Add(token.Substring(0, token.IndexOf("=")),
                        token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
        catch (Exception err)

        return tokens;

Thats all to it. Happy coding.

Tuesday, January 18, 2011

Generating PDF from DataTable using iTextSharp

iTextSharp is a wonderful open-source tool for generating PDF in C#.

Here is a simple generic helper class for Exporting data from a DataTable to a PDF file.

using System;
using System.Web;
using System.Data;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace yetanothercoder
    /// Summary description for CreatePdf
    public class PDFExporter

        private readonly DataTable dataTable;
        private readonly string fileName;
        private readonly bool timeStamp;

        public PDFExporter(DataTable dataTable, string fileName, bool timeStamp)
            this.dataTable = dataTable;
            this.fileName = timeStamp ? String.Format("{0}-{1}", fileName, GetTimeStamp(DateTime.Now)) : fileName;
            this.timeStamp = timeStamp;

        public void ExportPDF()
            HttpResponse Response = HttpContext.Current.Response;
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");

            // step 1: creation of a document-object
            Document document = new Document(PageSize.A4, 10, 10, 90, 10);

            // step 2: we create a writer that listens to the document
            PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);

            //set some header stuff
            document.AddSubject(String.Format("Table of {0}", fileName));

            // step 3: we open the document

            // step 4: we add content to the document

            // step 5: we close the document

        private void CreatePages(Document document)
            PdfPTable pdfTable = new PdfPTable(dataTable.Columns.Count);
            pdfTable.DefaultCell.Padding = 3;
            pdfTable.WidthPercentage = 100; // percentage
            pdfTable.DefaultCell.BorderWidth = 2;
            pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

            foreach (DataColumn column in dataTable.Columns)
            pdfTable.HeaderRows = 1;  // this is the end of the table header
            pdfTable.DefaultCell.BorderWidth = 1;

            foreach (DataRow row in dataTable.Rows)
                foreach (object cell in row.ItemArray)
                    //assume toString produces valid output


        private static Phrase FormatPageHeaderPhrase(string value)
            return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 10, Font.BOLD, new BaseColor(255, 0, 0)));

        private static Phrase FormatHeaderPhrase(string value)
            return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 8, Font.UNDERLINE, new BaseColor(0, 0, 255)));

        private Phrase FormatPhrase(string value)
            return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 8));

        private string GetTimeStamp(DateTime value)
            return value.ToString("yyyyMMddHHmmssffff");

Now if you have an Export to Excel Button, you can generate pdf easily like this

protected void ExportToPDFLink_Click(object sender, EventArgs e)
    PDFExporter pdf = new PDFExporter(GetCostumers(), "customer", true);


SQLite in ASP.NET Web Forms

What is SQLite?

SQLite is a in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

SQLite is a must have tool for manipulating database for small to mid size projects, there by cutting the cost of maintaining an extra database server. Its very fast and has less percentage of crashing also.
Next, download an SQLite Manager from which we can create and manipulate a sample database and its objects. For that I used the SQLite Manager add on for Firefox. Feel free to use any other tools.
Now we are all set to use the SQLite database in our ASP.NET application.

Steps to follow

1. Create a Sample Database called Northwind.sqlite using the firefix addon.
2. Add a table named Customers to it with some fields and some dummy data to it.
3. Create an empty website in .NET 3.5 using Visual Studio
4. Create an App_Data folder in it and place the Northwind.sqlite to it
5. Add to the empty website as reference, the dll
using System.Data.SQLite
6. Create a default page in your application and place a gridview in that

<asp:GridView ID="CustomersGrid" runat="server">

7. At code behind, add reference to System.Data.SQLite;
8. Write the code to get data from Customers Table here.

private void BindCustomerGrid()
    string commandText = "SELECT * FROM Customers";
    string path_to_db = System.IO.Path.Combine(Server.MapPath("."), "App_Data", "Northwind.sqlite3");
    string connectionString = String.Format("Data Source={0};Version=3;", path_to_db);
    DataTable dataTable = new DataTable();
    using (SQLiteConnection connection = new SQLiteConnection(connectionString))
        using (SQLiteCommand cmd = new SQLiteCommand(commandText, connection))
            cmd.CommandType = CommandType.Text;
            using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd))
    CustomersGrid.DataSource = dataTable;

Thats all to it. Happy Coding!