Prabir's Blog

where the tech matters...

Multi Platform Targeting in C# using NOR

August 28
by prabir 28. August 2010 13:00

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. :-)

 

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

.NET Framework | C# | snippets

The Ultimate Facebook SDK for .NET

July 27
by prabir 27. July 2010 19:32

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.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

.NET Framework | C# | open source

Alternative Method of Throwing Exception

August 05
by prabir 5. August 2009 11:44

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) [Downloads: 176]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

.NET Framework | ASP.NET

Microsoft’s way of N-Tier system

July 23
by prabir 23. July 2009 16:05

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

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

.NET Framework | ASP.NET

.NET/E – .net/everywhere

May 25
by prabir 25. May 2009 21:13

For some of you out there who have been working on wpf or silverlight, you must have known the codename of Silverlight – WPF/E. It stood for WPF Everywhere, meaning, WPF could run on any platform or Operating System. Well the same applies to .NET also which I like to refer to it as .Net/E (just kidding). Even this project has similar goals. Its not about other .NET frameworks or engines like mono or portable.net, but rather takes a total different approach to making .NET apps run everywhere.

Unlike those traditional frameworks mentioned earlier, Mainsoft Grasshopper, takes a totally different approach by converting .NET codes to Java bytecode, thus allowing the code to run everywhere the Java runtime is installed. Since Java Runtime is installed in many of our computers, especially non Microsoft OS, our code could run on more platforms and OS without telling the user to install the mono framework. ( you need to provide easy access to the customers). To summarize, it about running your .NET code anywhere Java works. That’s a face to face challenge with Java.

For more details please have a look at it official website here.

You can download the plug-in for visual studio from following links. I’m just providing these links as alternatives.

For Visual Studio 2008 (52.8 mb) [Downloads: 3225]
For Visual Studio 2005 (56.7 mb) [Downloads: 1086]
For Visual Studio 2003 (58.9 mb) [Downloads: 388]

I have also been working on a similar project for my bachelors degree, which I posted on my blog out here. Its about converting C# code to a portable code called LLVM that can be compiled and run in almost all sorts of platforms. For more information please check the official site of my project at http://projects.prabir.me/compiler.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

Visual Studio | .NET Framework