Wednesday, November 23, 2011

Google chart, load on request - ASP.NET MVC 3, C# & JQuery

This is a sample to create Google chart (line chart), on request (button click or any event) with data in DataTable format using Bortosky .NET Google visualization helper.
Bortosky .NET Google visualization helper can be downloaded from here http://code.google.com/p/bortosky-google-visualization/.
UI code:
Add following script tags.
<script
src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery-1.5.1.min.js")%>"

type="text/javascript"></script>



Load google chart API
<script language="javascript" type="text/javascript"> 
     google.load("visualization", "1", { "packages": ["corechart"] });
</script>


Add a placeholder div tag for displaying the chart.
<div id="chart_div" ></div>

Button to request chart load
<input type="button" id="btnLoadChart" value="Generate Chart" />

JQuery button click event handler
$(document).ready(function () {
     $("#btnLoadChart").click(function () {
        loadChart();
    });
}

JS method to load chart, ajax call to the controller to get chart data and generate chart.
function loadChart() {

    $.ajax({
        type: "GET",
        url: "/Chart/GetChartData",
        data: "startDate=" + startDate + "&endDate=" + endDate, //pass required data to your controller

        success: function (result) {

        if (result.success) {
            var evalledData = eval("(" + result.chartData + ")");
            var opts = { width: 800, height: 300};
                new google.visualization.LineChart($("#chart_div").get(0)).draw(
new google.visualization.DataTable(evalledData, 0.5), opts);
            $('#chart_div').show();
            return false;
        }
        else {
            $('#chart_div').html('<span style="color:red;"><b>' + result.Error +                     '</b></span>');
            $('#chart_div').show();

            return false;
        }
        }
    });
    }
    return false;
}


Controller code:
 
public ActionResult GetChartData(string startDate, string endDate)
{
    try{
              //Get your data table from DB or other source
   
    DataTable chartTable = GetChartTable(startDate, endDate);

        //convert datetime value to google datetype, if your first column is date
   
    Bortosky
            .Google
            .Visualization
            .GoogleDataTable
            .SetGoogleDateType(chartTable.Columns["Date"],
                 Bortosky.Google.Visualization.GoogleDateType.Date);
         //convert DataTable to GoogleDataTable
        var googleDataTable =  
                    new Bortosky.Google.Visualization.GoogleDataTable(chartTable);
        //Pass the google datatable to UI as json string

return new JsonResult { Data = new { success = true
                        chartData = googleDataTable.GetJson() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
    }
    catch (Facebook.FacebookOAuthException ex)
    {
        return newJsonResult { Data = new { success = false,
Error = "Error generating chart!" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}


Try it out!

Block an user from accessing your facebook fanpage! - C# SDK

Here is a simple piece of code to block an user from accessing your facebook fan page.

/// <summary>
/// Block annoying user from my fan page
/// </summary>
/// <param name="BlockUserId">Facebook userid to be blocked</param>
/// <param name="FacebookPageID">Facebook fanpage id</param>
/// <returns></returns>
private bool BlockFan(string BlockUserId, string FacebookPageID, string AccessToken)
{
         try
         {
                  var app = new FacebookClient(AccessToken);
                  dynamic parameters = new ExpandoObject();
                  parameters.method = "pages.blockFan";
                  parameters.uid = BlockUserId;
                  parameters.page_id = FacebookPageID;
                  app.Post("/" + FacebookPageID + "/users", parameters);
                  return true;
         }
         catch(Exception ex)
         {
                  //Handle exception
                  return false;
         }
}
 
Happy Coding!

Tuesday, November 22, 2011

Remove a post from Facebook fan page using C# SDK

Wondering how to delete (or) remove a post (or) comment from a facebook fan page wall, here it is!

///<summary\>
/// Remove post from facebook fanpage wall
///</summary\>
///<param name="accesstoken"\>user access token</param>
///<param name="fanPageId"\>Fan Page Id</param>
///<param name="contentId"\>Post or Comment Id </param>
public void removePost(string accesstoken, string fanPageId, string contentId)
{
       var fb = new FacebookClient();
       dynamic parameters = new ExpandoObject();
       parameters.access_token = accesstoken;
       parameters.uid = fanPageId;
       //pass the content id you like to remove - pageid_postid format
     if(fb.Delete("/" + contentId, parameters))
       {

                  Console.Write("Delete Success!");
       }
       else
       {
                  Console.Write("Delete failed!");
       }
}
 
Call this method and the content is cleaned (removed) from your fanpage wall.

Happy coding!

Monday, November 21, 2011

Get Facebook accesstoken ASP.NET C#

A simple code sample to retrieve FB accesstoken of a FB user, using Facebook C# SDK.

Step 1:
Create a Authenticate button, on button click event build FBLoginURL with a specific return URL.
Note: your return url should match the site URL specified in your FB app settings.

Pass "scope" parameter to get required permission.
Details of scope parameters are available here https://developers.facebook.com/docs/reference/api/permissions/.

protected void btnAuthenticate_Click(object sender, EventArgs e)
{
        var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
        //Specify a return url, where you would like to get the access token
        oAuthClient.RedirectUri = new Uri("http://localhost:2647/default.aspx?fbRedir=1");
        var loginUri = oAuthClient.GetLoginUrl(
                                     new Dictionary
                                     {
                                         { "scope", "read_stream,publish_stream, offline_access, manage_pages" }
                                      });
         Response.Redirect(loginUri.AbsoluteUri, true);
}


Step 2:

Retrieve access token on redirect.
Note the "fbRedir" query string parameter in the redirect uri, this parameter is used to identify if the request is from facebook redirect.

On the page load event check for querystring "fbRedir" and proceed with accesstoken retrival.

protected void Page_Load(object sender, EventArgs e)
{
     if (!IsPostBack)
     {
          if (Request.QueryString["Redir"] != null && Request.QueryString["Redir"].Equals("1"))
          {
               string code = Request.QueryString["code"];
               string state = Request.QueryString["state"];
               getAuthToken(code, state);
          }
     }



private void getAuthToken(string code, string state)
{
     FacebookOAuthResult oauthResult;
     //check the result 
     if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
     {
          //check if authentication is successfull
          if (oauthResult.IsSuccess)
          {
               var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
               oAuthClient.RedirectUri = new Uri(redirectUrl);
               dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
               //Get access token
               string accessToken = tokenResult.access_token;
               //Get token expiry date (if "offline_access" not requested
               DateTime expiresOn = DateTime.MaxValue;
               if (tokenResult.ContainsKey("expires"))
               {
                    DateTimeConvertor.FromUnixTime(tokenResult.expires);
               }
               //verify access token
               FacebookClient fbClient = new FacebookClient(accessToken);
               dynamic me = fbClient.Get("me?fields=id,name");
               long facebookId = Convert.ToInt64(me.id);
          }
     }
}


Happy coding!

Monday, February 15, 2010

General migration issues - .NET 1.1 to .NET 3.5 [Part - 1]

1. New method "GetObjectData" is added to DataSet class: Since we were using this name for our custom Dataset, we had to overload this method.
Check This out.

2. Warning as Error: 'System.Xml.Xsl.XslTransform' is obsolete: 'This class has been deprecated. Please use System.Xml.Xsl.XslCompiledTransform instead.

XSLTransform calss is depricated and better performing XslCompiledTransform is inroduced.
Check this out for Migrating From the XslTransform Class.

3. Warning as Error: 'System.Xml.Schema.XmlSchemaCollection' is obsolete: 'Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation.

XmlSchemaCollection calss is depricated and better performing XmlSchemaSet is inroduced.

To traverse through XmlSchemaSet we should use XmlSchemaSet.Schemas() method.
foreach (XmlSchema schema in schemaSetObject.Schemas())
{
      xmlSchemaObject = schema;
      .....
      ....
}
4. Warning as Error: 'System.Configuration.ConfigurationSettings.GetConfig(string)' is obsolete: 'This method is obsolete, it has been replaced by System.Configuration! System.Configuration.ConfigurationManager.GetSection'
Visit this link if you need more info on how to use GetSection Method. 

5. Warning as Error: 'System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(System.Runtime.Remoting.Channels.IChannel)' is obsolete: 'Use System.Runtime.Remoting.ChannelServices.RegisterChannel(IChannel chnl, bool ensureSecurity) instead.'

More info here.

Friday, February 12, 2010

StringBuilder.Append vs string.Join

This is most common situation we encounter, joining an array (list) of string into a delimiter seperarted string (most commonly comma seperated). We use string builder to append the array items and make it as one string using a foreach loop.


string[] stringArray = new string[] { "This", "is", "single", "string" };
_______________________________________
Stringbuilder way

StringBuilder sbObject = new StringBuilder();


foreach (string strItem in stringArray)
        sbObject.Append(strItem + " ");
string finalString = sbObject.ToString();


//remove the last character
finalString = finalString.Substring(0, finalString.Length);

output for this code is
"This is single string"
________________________________________
Instead of the above code we can use string.Join(), a built in method which is much efficient and reduces coding effort significantly.

string finalString = string.Join(" ", stringArray);
--
happy coding