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

SQL for localization and Globalization – no more resx

June 19
by prabir 19. June 2010 17:54

If you have created a website supporting various languages, you must have realized how painful it is to maintain those resx files spread across different folders. I liked the concept of how easy it was to support localization or globalization in ASP.NET websites but was just not happy enough with the resx files. Wouldn’t database be a better place to store those language translations?

In order to achieve this, we have to write a custom resource provider for ASP.NET that access database rather than resx files.

As most of you might be using this concept in lot of your projects, I have created it as an open source project rather than a normal blog post with its associated download files.

Please refer to this walkthrough on using SQLite as your resource provider.

For more info you can also refer to the official documentation.

Official project website :
http://github.com/helpersdotnet/Helpers.Net.Resource

You can also download the binaries, source code and documentation at: 
http://github.com/helpersdotnet/Helpers.Net.Resource/downloads

I created only for SQLite, but you can easily port it to any other database. I would be glad if you could contribute your ports to other databases.

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

Tags: ,

ASP.NET | C# | snippets

Hidden C# feature - string.Format Width

April 13
by prabir 13. April 2010 20:50

If you had written console applications before, you most probably would have spent quite an amount of time formatting the output with Console.Write(“some string”). Its pretty cumbersome to type “\t” or add couple of space “   “ in order to neatly present the output.

Well you don’t need to worry much with C#. It has a method called Format which easily allows to change the format of the string. A HelloWorld example for string.Format would be:

string.Format("Hello {0}", "Prabir");

That’s something most of you already know. But there is more cool feature than to just add a number inside the curly braces - {no}.

One could even add a comma and another number – minimum width to it.

string.Format("Price: {0,5}",price);

The above code would right align the price with width of 5. (If you want to left align you could use a negative number.)

Console.WriteLine("Product: {0,-7} Price: {1,5}", product1, price1);
Console.WriteLine("Product: {0,-7} Price: {1,5}", product2, price2);

The above sample would produce the following output. Notice the negative (-) sign for Product? Its left aligned, while the price is positive signed and is right aligned.

image

string.Format-width.zip (11.30 kb) [Downloads: 127]

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

Tags:

C#

JSON in Classical Web Services ASMX

October 23
by prabir 23. October 2009 22:31

Most of the websites we see these days have great user experience by providing asynchronous postbacks and means of data transport has been JSON. Even though most of us have already migrated to new versions of .NET, there are still some people using the older versions. This post is about supporting JSON in Classical Web Services (.asmx).

Add a new ASMX web service file as usual. Then decorate your class with [System.Web.Script.Services.ScriptService] attribute as shown below.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class JsonWebService : System.Web.Services.WebService
{
    // code omitted for brevity
}

Then decorate your methods with [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] attribute.

[WebMethod]
    [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    public string HelloWorldInJson()
    {
        // code omitted for brevity
    }

We will then return a JSON string. To make it easy we will be using a 3rd party open source JSON serializer/deserializer which can be found at http://json.codeplex.com

Let’s make a helper method to make it easier to convert an object to JSON string.

public class JsonHelper
{
    /// <summary>
    /// Convert Object to Json String
    /// </summary>
    /// <param name="obj">The object to convert</param>
    /// <returns>Json representation of the Object in string</returns>
    public static string ToJson(object obj)
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
    }
}

Then you call the JsonHelper.ToJson() method to serialize the object to json as follows.

 

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string HelloWorldInJson()
{
    return JsonHelper.ToJson("Hello World in Json");
}

You can also convert your own objects (classes) to string by calling the Helper method easily.

The other alternative i.e. without using the Newtonsoft.Json could also be done. Instead of returning string one could return the Object itself. For instance let’s assume we have the class Person as below.

public class Person
{
    public string Name;
    public Gender Gender;

    public List<string> Hobbies;
}

public enum Gender
{
    Male,
    Female
}

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string ReturnComplexObject()
{
    return JsonHelper.ToJson(JsonHelper.CreateSamplePerson());
}

And let us also assume that we have a method called JsonHelper.CreateSamplePerson() which return a new instance of the Person class. We could then write it as below. Notice the return type is Person instead of string.

 

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public Person ReturnComplexObjectRaw()
{
    return JsonHelper.CreateSamplePerson();
}

 

We would get the following result for the ReturnComplexObject() where the return type is string. Notice that it is not fully JSON as it contains mixture of XML. this is because the content-type is not set to application/json.

image

When the content-type is set to application/json the following result is obtained.

image

It now gives a JSON string.

Now for the ReturnComplexObjectRaw() which returns the Person the following result would be obtained. (The object is converted automatically to JSON.)

image

What is the difference of returning converted JSON string using the Newtonsoft Json and or the autoserializer returning the Person Object?

  1. First of all as you can see the autoserializer from done by .NET adds one more field called __type. This isn’t much of a problem though. __type is added only if the Object is complex. For simple types such as string, it is not added.
  2. Secondly the result returned by .NET autoserializer returns JSON object while from Newtonsoft it return a JSON string which needs to be converted to JSON object manually (more of this in the coming posts). That is why you can see a lot of \” in the result by Newtonsoft. Its actually an escape sequence character for the string.

OK. But which method to choose then?

Well, that is quite a tough question. But from my experience I have choosen to use Newtonsoft  by serialize the object and returning it as a string rather than using the concrete object. This was due to the fact that, some of my classes doesn’t contain a constructor without any parameters (default constructor) such as below.

 

public class Student
{
    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    public string LastName
    {
        get { return _lastName; }
    }

    public Student(string firstName, string lastName)
    {
        _firstName = firstName;
        _lastName = lastName;
    }
}

 

It doesn’t have a constructor. Then if I return Student in my Web Service it would throw me the yellow screen of death. Where as using the Newtonsoft serialization it would work great. The another reason is that in WCF to serialize an object to JSON using DataContract it needs both get and set properties, but the LastName in Student class doesn’t have set property. This would not include LastName in the serialize JSON string which was not what I wanted. So the safer way for me was to use Newtonsoft.JSON.

These preferences are from my own perspectives. If you find that it is not good to use Newtonsoft over .NET default serialization or have a better one, please feel free to leave a comment.

In the later posts I will explaining how to consume these JSON webservices using Jquery. If you want to learn how to consume these services using JQuery, you can read it at http://blog.prabir.me/post/Consuming-ASPNET-Web-Services-using-JQuery.aspx.

AsmxJson.zip (761.21 kb) [Downloads: 348]

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

Tags:

ASP.NET | C#

The hidden C# Operator - ??

May 20
by prabir 20. May 2009 15:03

How many times have you actually written your program to check if an object is null or not. Well! It isn’t difficult at all. Let me introduce you to one of those hidden operator. Dot you know what it looks like ?? Well the answer is in the question it self. ?? is our new operator.

?? is referred to as null coalescing operator. Its main task is to assign a default value to an object if it is null.

Let’s start with an example:

string text = "hello world!" ; 
string test = text ?? "this is not the value";

The outcome of the above code will result in test = “hello world!” because text is not null.

string text = null; 
string test = text ?? "this was null";

The value of test = “this was null”. Since text is null, it will assign the default value after ?? operator. It works with any objects not just string.

For more information check out MSDN library at http://msdn.microsoft.com/en-us/library/ms173224.aspx.

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

Tags: ,

C#

LLVM# – Native C# Compiler

May 19
by prabir 19. May 2009 22:49

Right now I’m quite busy working on with my senior project called LLVM# compiler. Its main objective is to be able to write the code in C# and execute the code as a native C or C++ application by converting the C# code to LLVM (Low Level Virtual Machine). This project will tend to remove the dependency of C# from the .net framework, the mono runtime or the portable.net runtime engine. The project is being discussed at the moment but if you want to have a look at what’s happening, please do check the official website of LLVM# compiler at http://projects.prabir.me/compiler.

For more info on LLVM click here.

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

Tags: , ,

C#