Prabir's Blog

open source geek and lover of all tech  

When I was going through Scott Hansleman’s blog posts, I had realized that he makes extensive use the the nuget style Install-Package buttons like the one shown below.

image

I was a bit jealous and wanted to see for myself if I could have those nuget install-package buttons too. As of now I have around 18 unique nuget packages (most popular ones being Facebook C# SDK, SimpleJson and FluentHttp) hosted at nuget.org so I thought it was lame to do a print screen, a bit of editing and then pasting the image. So, I needed to come up with a new solution, a replacement to using images.

In the mean time, I seriously needed to make more people aware of nuget’s awesomeness. In Facebook C# SDK, we ship two files from the codeplex download tab – binary/assembly files (also available through nuget) and source code. But at the end of the day, the number of assembly files downloaded from codeplex always seems to be the higher than that of the source code and almost double than from nuget. (most probably VS2008 users.). So I decided that I ‘m going to start putting the Install-Package button in my blog on almost every blog post I do about Facebook C# SDK.

So my answer to both the above problems – a Javascript based solution that works with minimal amount of code the way you want too in any of your existing sites, just like Facebook’s like button, Google’s +1 button or Github’s “Fork me on Github” ribbons.

Enough of the history crap, show me the code

First of all you will need to add the following code just before the end of the body tag. nuget-button.min.js is download asynchronously using the below code.

<script type="text/javascript">
    (function () {
        var nb = document.createElement('script'); nb.type = 'text/javascript'; nb.async = true;
        nb.src = 'http://s.prabir.me/nuget-button/0.1/nuget-button.min.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(nb, s);
    })();
</script>

Then use “pre” tag and assign a class called “nuget-button” to it where ever you want the nuget Install-Package button to be rendered.

<pre class="nuget-button">Install-Package Facebook</pre>

You can see a live working example at http://s.prabir.me/nuget-button/0.1/nuget-button.htm

The best part about nuget-button is that you could now copy/paste the code and execute directly in the nuget package manager. No worries about Javascript being disabled coz pre is a standard html tag and will still get rendered.

Some of you may be wondering why its named “nuget-button” when there is nothing to do with behavior of a button like clicking. For vNEXT I plan to add anchor tag for the name of the project, so when you click, it will open http://nuget.org/List/Packages/Facebook. It is just the beginning and since all the code for nuget-button is open source, make sure to fork it or send suggestions/patches at https://github.com/prabirshrestha/nuget-button.

Here is a live sample showing nuget-button working in my blog.

Install-Package Facebook

And before I forget, nuget button is super lightweight (less than 3kb) with no dependencies on any javascript framework and yes it work on IE6 too.

Lately I have been working on some libraries to support different platforms such as Windows, Silverlight and Windows Phone. You can read the more on MSDN at http://msdn.microsoft.com/en-us/library/ff921092(PandP.20).aspx on how to solve it.

It recommends you to use conditional symbols such as SILVERLIGHT and WINDOWS_PHONE. But what if you want to have it only in desktop version and not in Silverlight and Windows Phone. Define another symbol for DESKTOP? But this DESKTOP symbol is not standard. If your writing this application for yourself and don’t want to open source or distribute it to others, it may probably be just fine. But incase you want others to use it, it isn’t a good idea to have these non-standard symbols and tell the your users to use the one you use (feels bossy).

So I needed to solve this. Find a better way to do it. Then all of a sudden I realized that it had been somewhere back in my head all the time and I just needed to implement it.

So what is the solution?

Let's look back into one of the Computer Science knowledge – The Logic Gates, particularly the NOR gates. This is a perfect solution to solve it. I’m not going to dive deep into these gates (bing it or google it, whatever you prefer). But will rather give you a simple recap by using the truth table.

A B A OR B NOR : NOT(A OR B)
0 0 0 1
0 1 1 0
1 0 1 0
1 1 1 0

Did you see anything? Thats the answer. Try replacing A with SILVERLIGHT and B with WINDOWS_PHONE, and then it might make more sense.

The table basically is telling you to OR the two values and then apply NOT to it and you get a NOR.

In C# it would be done as

#if !(SILVERLIGHT || WINDOWS_PHONE)
   // desktop (its not a silverlight or windows phone)
#endif

You could add more. !(SILVERLIGHT || WINDOW_PHONE || MONOTOUCH).

In Silverlight and Windows Phone, Microsoft doesn’t allow us to make synchronous web requests. So we need to hide synchronous functions if its in those platforms but show it in desktop versions. Using NOR gates is the perfect solution for it.

Summary of NOR gate: If any one of them is true, it evaluates it to false otherwise true.

Lesson to Learn: What you learned in Computer Science is never a waste (for those of you who complain about it). I just showed you how to apply it in a real life application. :-)

 

Recently I had been developing a facebook app and got frustrated by the support in C# or .NET in general. There were plenty of Facebook wrappers floating around the .NET community but unfortunately they were too old and outdated and or didn’t support the new Facebook Graph API. Then I finally thought to give up the search and write my own.

After sitting down and searching for Facebook SDK around for other languages and devices iPhone, Android, Java, PHP, Ruby it have me some overview of how to make the Facebook API clean and simple. My orginal SDK was written based on Android SDK. Soon Facebook announced their official C# SDK, so I changed my APIs to match those of the official Facebook SDK instead of using the Android’s one for easy migration.

Originally I had written the API’s using raw .NET API’s but soon realized it would consume a lot of time if I wanted to port it to Silverlight or Window Phone 7. Restsharp came to rescue (If you have been consuming any restful web services, I highly recommend to use this library). At the moment it supports only Windows Application (Winforms/ WPF / Console Application) and Websites (both asp.net webforms and asp.net mvc). Silverlight and Windows Phone 7 support coming soon.

var fb = new Facebook("access_token");
var user = fb.Get<User>("/me");
var jsonUser = fb.Get("/me");

Basically you create an instance of Facebook object passing the access token. The you make request by either calling Get, Post or Delete methods. Notice the similarity with the original Facebook C# SDK (almost 95% compatible). Rather than returning JSONObject it returns plain JSON string. Incase you want to convert to a .net object just use the generic version of it. Any Facebook API exceptions will be converted to native .NET exception FacebookException automatically and will throw that exception.

During my search, I also found out that most people are having problem getting access token from Facebook. So I have also created helper methods for retrieving the access token. You can see those in WinForms, ASP.NET website and ASP.NET mvc samples. API’s are the same for all these platforms you want to write, so converting it to website or winforms wouldn’t be a problem at all.

Other thing I noticed was that whenever I need to make a call to Facebook, I always need to refer to the official Facebook API documentation. So, in order to save your time, I have collected some extensions methods to ease the development. So now instead of coding like

var profileUrl = fb.Get("/me/picture");

you could

var profileUrl = fb.GetMyProfilePictureUrl();

Lots of other methods are there to make it easy like fb.AmIAdminOfPage(“pageId”), fb.GetFeeds(), fb.GetMyPages() and so on.

Bonus:

I have also create some providers to link with membership provider. You can find implementation for Sql Server, SQLite and MySql. If you are using MVC then you can make use of predefined filters, such as [FacebookAuthorize].I have also heavily commented the samples.

Go and grab the source at http://github.com/prabirshrestha/FacebookSharp and start building your own Facebook App.

Feedbacks are most welcome.

Most of us use Exceptional Handling mechanism to prevent our programs from crashing and then debug the program by understanding the message thrown.

Traditional way to use would be to use try..catch..finally block to handle the exceptions thrown using throw. How do you throw exceptions? There are basically two ways to throw exception.

throw new Exception();

Or simply,

throw;

Most of us would be using the first method to throw. But sometimes, it might not contain enough information that is required to solve our problems (bug). In that case, the second method would be more useful.

Below is an example of the c# code that would help to distinguish between the two types of errors.

There are two methods defined in the Program class under ConsoleApplication1 namespace. (I’m assuming the file named a.txt doesn’t exist in c drive)

The first method uses throw ex;

 

private void LoadFile()
{
    try
    {
        using (FileStream fs = new FileStream("c:\\a.txt", FileMode.Open, FileAccess.Read))
        {
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

 

The second method uses only throw; (You can enter this only in the catch block).

 

private void LoadFile2()
{
    try
    {
        using (FileStream fs = new FileStream("c:\\a.txt", FileMode.Open, FileAccess.Read))
        {
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}

 

The program is as follows:

using System;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{

    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();

            try
            {
                p.LoadFile();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            Console.WriteLine();

            try
            {
                p.LoadFile2();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);

            }
        }

        private void LoadFile()
        {
            // code omitied.
        }


        private void LoadFile2()
        {
            // code omited.
        }
    }
}

When you run the program you will get the following output.

image

The error message printed to the console is as follows:

   at ConsoleApplication1.Program.LoadFile() in D:\Prabir\Documents\Visual Studi
o 2008\ConsoleApplication1\ConsoleApplication1\Program.cs:line 47
   at ConsoleApplication1.Program.Main(String[] args) in D:\Prabir\Documents\Vis
ual Studio 2008\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I
nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o
ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at ConsoleApplication1.Program.LoadFile2() in D:\Prabir\Documents\Visual Stud
io 2008\ConsoleApplication1\ConsoleApplication1\Program.cs:line 62
   at ConsoleApplication1.Program.Main(String[] args) in D:\Prabir\Documents\Vis
ual Studio 2008\ConsoleApplication1\ConsoleApplication1\Program.cs:line 28
Press any key to continue . . .

 

 

As you might have noticed the second information is in more details. This allows you to know your stack trace in more details.

So how is it different?

In the first method, the stack trace is initialized at throw ex statement. The second method rethrows the exception meaning that the previous stack trace is kept along with more information where they occurred.

ThrowRethrowExample_CSCode.zip (538.00 bytes)

For those of you who have not know about Microsoft’s solution to the N-Tier system, you should hurry up and learn more about it. Its already been months old with two public releases (Preview versions).

Microsoft calls it .NET RIA services. What the hell is it and how is it different from traditional 2-tier and 3-tier systems?

Microsoft .NET RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. The RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.

Untitled

I have posted some links below to help get familiarize with .NET RIA services.

Installing July 2009 preview: Download the installer from here. (Prerequisites: Visual Studio 2008SP1 or Visual Web Developer SP1 and Silverlight 3.0 Runtime,SDK and Tools. You are required to uninstall March / May 2009 Preview before installing the newer version.

More information/tutorials on it can be found at

  1. http://code.msdn.microsoft.com/RiaServices
  2. http://blogs.msdn.com/brada/archive/2009/03/19/what-is-net-ria-services.aspx
  3. http://silverlight.net/forums/t/108916.aspx
  4. http://blogs.microsoft.co.il/blogs/bursteg/archive/2009/04/04/build-a-simple-application-with-net-ria-services-silverlight-3.aspx
  5. http://www.silverlightshow.net/items/Creating-applications-with-.NET-RIA-Service-Part-1-Introduction.aspx
  6. http://blogs.microsoft.co.il/blogs/bursteg/archive/tags/.Net+RIA+Services/default.aspx