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

Organizing Javascript codes from a C# perspective using object oriented concepts

July 18
by prabir 18. July 2010 16:49

This is a follow up article on Organizing Javascript codes from a C# perspective using namespaces. If you haven’t read the previous article I strongly recommend it do so.

In this article I will discuss on how to structure the Javascript codes using Object Oriented Programming (OOP) concepts which you are highly familiar with in C#.

Lets start first by writing a C# class. (These naming conventions are not of C# standards and never try to write one in this way. Its been written only as an example to map with Javascript codes for convenience.)

namespace A.B
{
    using System;

    public class Test
    {
        public Test()
        {
            Console.WriteLine("constructor");
        }

        private string private_property = "private_property (field)";
        private void private_method()
        {
            Console.WriteLine("private method");
        }

        public string public_property = "public_property (field)";
        public void public_method()
        {
            Console.WriteLine("public_method");
        }

        public static string static_property = "public static property";
        public static void static_method()
        {
            Console.WriteLine("public static_method");
        }
    }
}

First of all we need to wrap code in the namespace block A.B.

if (!A) var A = {};
if (!A.B) A.B = {}; // careful here, var is not present here, only in the first one

Please refer to the my tutorial on  Organizing Javascript codes from a C# perspective using namespaces which describes in more details.

Then we create the class same as in C#. 

A.B.Test = function () {
};

This looks similar to a function. Well it is a function. So in order to instantiate the object of this class you call the function.

var t = A.B.Test();

Now that we are able to create the class, lets create public and private properties and methods.

A.B.Test = function () {
    // ctor
    alert('constructor');

    var _private_var = 'private var';

    private_method = function () {
        alert('private method');
    }

    alert('or can even write ctor anywhere');

    return {
        public_property: "public_property",

        public_method: function () {
            alert("public_method");
        }
    };
};
A.B.Test.public_static_property = 'public static property';
A.B.Test.public_static_method = function () {
    alert('public static method');
};

And here’s are the tests. 

var t = A.B.Test();
alert(t.public_property);
t.public_method();
if (typeof (t._private_var) != 'undefined')
    alert('can access private var, test failed');
else
    alert('cannot access private var, test passed');
try {
    t.private_method();
    alert('can access private method, test failed');
} catch (e) {
    alert('cannot access private method, test passed');
}
alert(A.B.Test.public_static_property);
A.B.Test.public_static_method();

So next time you write Javascript, try implementing these OOP concepts. It will really help you out in organizing your codes.

jsoop.zip (727.00 bytes) [Downloads: 54]

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

Tags: ,

Javascript | snippets

Organizing Javascript codes from a C# perspective using namespaces

July 15
by prabir 15. July 2010 18:23

Recently I had been writing a lot of Javascript codes and was very unhappy about the code organization and the architect of my source code. Having lots of functions all jumbled up with UI logic and business logic was getting me no where. I decided to stop all my coding and search for a better way to organize my javascript codes.

I saw some solutions by using 3rd party javascript libraries such as YUI and Microsoft Ajax Client library to name a few. It did provide a great way to solve my problems, but what if I wanted to distribute my Javascript codes as an SDK for other devs to build upon (like the Facebook Javascript SDK). They would have to reference it, and even learn how to use YUI or MSAjax libraries. I wanted simpler solution less bulky solution.

Then after searching around, I found out a lot of ways to do it. I have broken up this tutorial into various parts which I will be posting soon. The first one is using the concepts of namespaces as you would do in C#.

Lets say I want to create a SDK called MySDK. I would want to have it under the company’s name like CompanyName.MySDK.

In C# you would do it as …

namespace Prabir.Shrestha
{
   public MyClass
   {
   }
}

 Equivalent code for Javascript would be as follows:

var Prabir = Prabir || {};
Prabir.Shrestha = Prabir.Shrestha || {};
Prabir.Shrestha.MyClass = function(){
};

Lets examine the first line in details. var Prabir tells us to create a Javascript variable called Prabir. The right hand side tells to assign Prabir (rhs) to Prabir (lhs) and if Prabir(rhs) is not defined create a new object and assign it to Prabir (lhs) – counfusing isn’t it. Well just remember it as a sort of C# null coalescing operator (??). The next line does the similar thing. It is very important to check if the object already exists as you might have another SDK under the same namespace, and if you create a new one it would override the old variable, so only the last referenced SDK would be available.

Note: Put var only in the root namespace lines and not in others.

So now you could create public functions using the following code.

var Prabir = Prabir || {};
Prabir.Shrestha = Prabir.Shrestha || {};
Prabir.Shrestha.MySDK = function(){
     return {
          public_method : function() {
               alert('I am a public method');
          }
     };
};

To call the public method you would need to create an instance of the object as you would do in C# and call the function.

var mySdk = new Prabir.Shrestha.MySDK();
mySdk.public_method();

Congrats. That’s the first way to organize your Javascript using namespaces as in C#.

To make it more easy, I actually landed up creating a new Javascript library to make managing namespace easier. You can find this library at http://github.com/prabirshrestha/js-namespace

/*!
 * js-namespace Javascript Library v1.0
 *
 * http://www.prabir.me
 * http://github.com/prabirshrestha/js-namespace
 *
 */
NS = {
	register: function(ns,container){
		var root = container || window;
		var nsParts = ns.split('.');
		var length = nsParts.length;
		for(var i = 0; i < length; ++i)
			root = root[nsParts[i]] = root[nsParts[i]] || {};
		return root;
	},
	exists: function(ns,container){
		var root = container || window;
		var nsParts = ns.split('.');
		var length = nsParts.length;
		for(var i = 0; i < length; ++i){
			if(!root[nsParts[i]])
				return false;
			root = root[nsParts[i]];
		}
		return true;
	}
};
// alias
NS.r = NS.register;
NS.e = NS.exists;

To create a namespace you would call the register method.

NS.register('Prabir.Shrestha');

and to check if the namespace exists call the exists function. Instead of using NS.register and NS.exists you could also use the shorthand NS.r and NS.e respectively.

The uncompressed file is 900 bytes and the minimized gziped file is around 368 bytes.

Next tutorial is about Object Oriented Programming in Javascript. So stay tuned.

js-namespace-samples.zip (1.92 kb) [Downloads: 54]

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

Tags: ,

Javascript | snippets

Migrating Existing BlogEngine.Net Comments to Disqus

May 17
by prabir 17. May 2010 13:55

If you have been moderating a blog or writing your own, you must have experienced a lot of spammers invading your blog with comments. To solve it you might have disabled comments after a particular day, installed some extensions (plugins) to help you moderate your comments or even out-sourced you commenting system. Well, in my case I had decided to out-source it and choose Disqus as my commenting system. I was pretty lucky that I choose Disqus commenting system as BlogEngine.Net now officially allows to choose between either its own commenting system or Disqus commenting system, making it more easier for me to upgrade to newer versions as it wouldn’t require me to hack the BlogEngine.Net source code to inject some Disqus related codes.

One of the down side was that my blog already had some comments posted using the BlogEngine.Net. I didn’t want my old comments to be hidden (lost) and yet I wanted to choose some commenting system that would help me manage comments more easily. I decided to go with Disqus Comments after researching with its competitors.

I landed up disabling the BlogEngine.Net add new comments but still putting the old comments. Any new comments would had to be entered using the newly installed Disqus Comments as show below.

sample1 This was a temporary hack to use Disqus as the core commenting system. Later on with version 1.6.0.5 of BlogEngine.Net they officially supported Disqus Commenting system and would allow us to choose between the BlogEngine’s one or Disqus. Then I thought of migrating all my comments to Disqus as this would help me upgrade my blog more easily.

To solve this, I started searching for options to migrate existing comments to Disqus. They had official support for importing Intense Debate comments. I then created an extension for exporting BlogEngine.Net’s comments to Intense Debate comments xml format. But it was taking too long to import and finally gave me errors after importing. Tried it many times but was having no success. Finally I landed up writing a C# API to communicate with Disqus. The source code is open sourced and can be downloaded here (I’m using git version control system. please checkout to dev branch to see the codes). I decided to name it Disqus#.

Enough of the history. Lets start migrating.

First of you will need to download the BlogEngine.Net extension which allows you to export your blog engine.net comments at the end of the post. (Note: nested comments are not supported. This extension was created in hurry and is based on only my requirements.)

There are two things you will need to upload to your website. The extension it self called CommentsExporter.cs to App_Code\Extensions folder and the web-GUI front-end for exporting comments to User controls\ExportComments.aspx.*

You will then need to login as the Blog moderator (administrator) and go to the extensions tab of the control panel.

image

Then select Edit link in the settings column of the CommentExporter. You will land up with the following page.

image

You can then click Export Comments button and choose Disqus Comments as the format. (Nested comments are not supported.) Map Authorized Users was basically created for exporting to Intense Debate (which I had chosen as my first export format, unfortunately it didn’t turn out well). This feature can still be used for Disqus Comments format. For example, in some of my comments I had written the author name as prabir or prabirshrestha. When I wanted to migrate I wanted to make them both as the same user – prabirshrestha. This was achieved by typing prabir:prabirshrestha; color(:) separates the key and value while semi-color(;) allows you to write more mappings. This is case sensitive too. You can write multiple values by entering prabir:prabirshrestha;Prabir:prabirshrestha; After you are done click the export button and save the exported comments. (The exported format is same as when you export comments from the Disqus website.)

Included with the download (below) there is a GUI frontend (Prabir.DisqusUploader) which looks similar as below.

image

Click browse and locate the file you just exported (saved) from the BlogEngine.Net website. You will need to then enter the User Api Key at the bottom left. If you don’t know your Disqus User Api Key, login to disqus and navigate to this link http://disqus.com/api/get_my_key/ Copy paste the User Api Key from the browser and click Get Websites button. Choose the appropriate website and click Upload to Disqus button. Once you are done with uploading a MessageBox is shows saying - “Your comments have been uploaded to Disqus.”

Here’s the sample of uploaded Disqus Comments.

sample3

Then I finally upgraded my BlogEngine.Net to the latest version which supports Disqus Comments. The old comments were also removed. Finally I landed up as …

image

Note: There is a small issue when uploading the comments to Disqus, it tends to truncate the comments if you have a single or double quote in the comments (‘ “) or have a semi-colon in the comments (;). I had to manually edit the truncated comments. If you want to fix it you can also download the source code. (Now that I am done migrating, most probably I wouldn’t have to be touching the source code, but if any one wants to contribute it back I would be more than happy.) Please use it at your own risk.

 DisqusUploaderWithBlogEngineExtensions.zip (778.56 kb) [Downloads: 111]

 DisqusUploader-Src.zip (4.02 mb) [Downloads: 124]

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

Tags: ,

BlogEngine.NET

Dependency Injection (DI) – Hello World with Ninject

May 07
by prabir 7. May 2010 11:54

“Stop writing monolithic applications that make you feel like you have to move mountains to make the simplest of changes. Ninject helps you use the technique of dependency injection to break your applications into loosely-coupled, highly-cohesive components, and then glue them back together in a flexible manner.” - www.ninject.org

Wait. First tell me what on earth is Dependency Injection or DI in short?

Dependency injection (DI) in object-oriented computer programming is a technique for supplying an external dependency (i.e. a reference) to a software component - that is, indicating to a part of a program which other parts it can use. (source: Wikipedia)

In short “loose coupling”.

I am going to start with explaining a simple scenario where we could use the DI pattern. I will be using Ninject to write dependency injections. If you want to try other frameworks, Scott Hanselman has a great list of them for .net here.

Let’s say we need to create a software called XDoc which is a word text editor. And we will implement a part of it which is able to write to different mediums – console (stdout), file, pdf file, doc file and so on…

To solve the above problem, we would first define a interface or abstract class.

namespace Prabir.NinjectSample.Provider
{
    public interface IWriter
    {
        void Write(string str);
        void Write(int i);
    }
}

For simplicity, I will just add those 2 methods. I prefer to put in under the namespace Provider but that’s all up to you.

Now, lets create the implementation of it. In this tutorial we will create two. One to write in console and one to show in message box (not really a text editor).

using System;
using Prabir.NinjectSample.Provider;

namespace Prabir.NinjectSamples.Providers.ConsoleWriter
{
    public class ConsoleWriter : IWriter
    {
        public void Write(string str)
        {
            Console.Write(str);
        }

        public void Write(int i)
        {
            Console.Write(i);
        }
    }
}

Implementation is done just in the plain old style. Nothing new.

using System.Windows.Forms;
using Prabir.NinjectSample.Provider;

namespace Prabir.NinjectSample.Providers.MessageBoxWriter
{
    public class MessageBoxWriter : IWriter
    {
        public void Write(string str)
        {
            MessageBox.Show(str);
        }

        public void Write(int i)
        {
            MessageBox.Show(i.ToString());
        }
    }
}

Then we create a class that holds the instance of the Writer – either ConsoleWriter or MessageBoxWriter.

using Ninject;

namespace Prabir.NinjectSample.Provider
{
    public class XDoc
    {
        private IWriter _writer;
        public IWriter Writer { get { return _writer; } }

        [Inject]
        public XDoc(IWriter writer)
        {
            _writer = writer;
        }
    }
}

Notice something new, I use a [Inject] attribute to tell Ninject to inject something (something will be described later on). This is known as constructor injection. Other types of injections also exists – property injection and method injection.

Many DI frameworks use xml mapping to inject which become quite cumbersome over time. Ninject allows us to solve this problem by creating a module. This class needs to implement INinjectModule. For simplicity, we could also inherit from NinjectModule class.

using Ninject.Modules;
using Prabir.NinjectSample.Provider;
using Prabir.NinjectSamples.Providers.ConsoleWriter;
using Prabir.NinjectSample.Providers.MessageBoxWriter;

namespace Prabir.NinjectSample.ConsoleApplication
{
    public class XDocModule : NinjectModule
    {

        public override void Load()
        {
            Bind<IWriter>().To<ConsoleWriter>();
            Bind<XDoc>().ToSelf().InSingletonScope();
        }

    }
}

Load method is overridden and is the place where magic happens. The above code tell the application that whenever you see IWriter inject ConsoleWriter. Then tell XDoc that service is self-bound and that it should be instantiated only once and has to be reused for other subsequent requests.

Finally in the main program we create a Kernel using the XDocModule we defined.

using Ninject;
using Prabir.NinjectSample.Provider;

namespace Prabir.NinjectSample.ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel(new XDocModule());

            XDoc doc = kernel.Get<XDoc>();

            doc.Writer.Write("Hello from www.prabir.me ");
            doc.Writer.Write(2);
        }
    }
}

Since XDoc was bound as singleton Get<XDoc>() function will return the same instance if called more than once. Then we can call the Writer.Write method to write to console as we defined it in our Module. Incase we want to show a message box rather than console, we would only need to change the Module to

Bind<IWriter>().To<MessageBoxWriter>();

Prabir.NinjectSample.zip (398.25 kb) [Downloads: 109]

[In addition to blogging, I am also now using Twitter for sharing ideas. Follow me at: twitter.com/prabirshrestha]

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

Tags: ,

ASP.NET | snippets

Create a Windows 7 Federated Search Connector for your Blog

December 20
by prabir 20. December 2009 08:28

The driving force that landed me to create this blog that you are reading now, has mainly been that I wanted to contribute back to the society, “the internet society” from where I have learned so much. And the other one was to also put as a reference from the future. There are many times when I actually need to refer to my own blog.

For instance, I often need to redirect HTTP to HTTPS. (You can find this article at http://blog.prabir.me/post/HTTP-redirection-to-HTTPS.aspx). But opening blog.prabir.me and then typing redirect in the search box would quite lose my time. So I landed up creating a Windows 7 Federated Search Connector – a cool new Windows 7 feature.

When I search for redirect keyword in my blog using the Window 7 connector I would get the following result.

image

 

How does the magic happen. Well first the search results show up as RSS feeds using the open search URL conventions. And luckily BlogEngine.NET already supports it out of the box. Try this url http://blog.prabir.me/syndication.axd?q=redirect

It already contains the page called syndication.axd where we can pass you search query using the q querystring.

To do that we define a Windows 7 Search Connector file ending with .osdx extension. It is a normal text file. So you can edit it using your favorite text editor.

<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  <ShortName>Prabir's Blog - www.prabir.me</ShortName>
  <Description>Prabir's Blog - where the tech matters</Description>
  <Language></Language>
  <Url type="application/rss+xml" template="http://blog.prabir.me/syndication.axd?q={searchTerms}"/>
</OpenSearchDescription>

Notice the URL, we pass the search query in querystring q as {searchTerms}, that is how Windows 7 uses it.

Once you save it to .osdx file, double click it and you will asked if you want to add it. Click add then you are all set.

But the fun doesn’t end here. In the search results when you double click, it will open the article in Web Browser. And if you have the preview pane, it will show up in the Window Explorer Search Window it self as shown below.

image

prabirDOTme-Windows7FederatedSearchConnector.zip (371.00 bytes) [Downloads: 236]

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

Tags: ,

BlogEngine.NET | Windows

Parsing JSON in JavaScript

October 24
by prabir 24. October 2009 11:53

There are times when your web services are not returned as pure JSON objects but rather the string representations of JSON. So we will have to parse JSON string to JSON object.

Let us consider we have the following class and a WebMethod as follows.

public class Person
{
    public string FirstName;
    public string LastName;
}
[WebMethod]
[ScriptMethod]
public string GetSamplePerson() {
    Person p = new Person();
    p.FirstName = "Prabir";
    p.LastName = "Shrestha";
    return Newtonsoft.Json.JsonConvert.SerializeObject(p); ;
}

 

I’m using a 3rd party open source JSON serializer which can be found at http://json.codeplex.com.

Under .NET 2.0 we would get the following result.

"{\"FirstName\":\"Prabir\",\"LastName\":\"Shrestha\"}"

Under .NET 3.5 we would get the following result.

{"d":"{\"FirstName\":\"Prabir\",\"LastName\":\"Shrestha\"}"}

Noticed any difference? The “d” is added in the .NET 3.5. This is due to security reasons (for more details please see here). It is also a breaking change from .NET 2.0 to .NET 3.5.

But before we go to the complex one, lets start with the easier version, .NET 2.0. As you have noticed .NET 2.0 gives a full plain string enclosed in double quotes.

So when we consume in the client side, we will need to convert the JSON text to the JSON object.

Before we begin let us assume we already have these variables which comes from the webservices as follows.

var net20ResultFromWebService = "{\"FirstName\":\"Prabir\",\"LastName\":\"Shrestha\"}";
var net35ResultFromWebService = { "d": "{\"FirstName\":\"Prabir\",\"LastName\":\"Shrestha\"}" };

We could use the browser’s inbuilt JavaScript function called eval.

var net20JsonObjectUsingEval = eval('(' + net20ResultFromWebService + ')');

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. We will then be using json2.js, which can be found at http://www.json.org/js.html or can also be downloaded at the end of this post.

We could obtain the same result by using calling JSON.parse method which is in json2.js.

var net20JsonObjectUsingJson2 = JSON.parse(net20ResultFromWebService);

Now lets go to the .NET 3.5 version where d is added automatically. The result returned in .NET 3.5 is not totally a string. It is actually a JSON object. But the value of d is a string. So inorder to select the value and then convert it to the object we need to retrieve the value of d. This can be easily done by the following code.

var valueOfD = net35ResultFromWebService.d;

Then we parse the value of d by calling JSON.parse method.

var net35JsonObjectUsingJson2 = JSON.parse(valueOfD);

Now that it is done. But what if you are consuming others webservices, and all of a sudden they plan to upgrade to .NET 3.5 or higher and all of your websites doesn’t work. To avoid this lets create a generic version to parse.

function getMain(dObj) {
    if (dObj.hasOwnProperty('d'))
        return dObj.d;
    else
        return dObj;
}

The above code checks if it has a property called d. If it does have it return the value of d, else returns the object itself.

So now we call the above method instead.

var net20DHacked = JSON.parse(getMain(net20ResultFromWebService));
var net35DHacked = JSON.parse(getMain(net35ResultFromWebService));

That is it for converting Json text to Json Object. If you want to do the opposite from Json Object to Json text, just call the method JSON.stringify in json2.js.

Note: .NET 4.0 also adds ‘d’ property.

JsonParsing.zip (7.70 kb) [Downloads: 255]

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

Tags:

ASP.NET

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: 351]

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

Tags:

ASP.NET | C#

ScrewTurn Wiki Google Sitemap Generator [Update-2]

October 05
by prabir 5. October 2009 22:55

On September 30th, 2009 version 3.0 (RTW) of ScrewTurn Wiki was released to the web. It caused my previous ScrewTurn Wiki Google Sitemap generator to break down due to breaking changes in the API for ScrewTurn Wiki Engine.

One of the users commented that it was not working with version 3.0. He also gave the bug fix (thanks to Гносис, for the info as well as fix). I have also modified the Гносис fix it to show only the discussion pages in the sitemap if it contains at least one discussion or more as suggested and implemented by one of the users (Rurisoft) in the previous version as described in http://blog.prabir.me/post/Screwturn-Google-Sitemap-GeneratorUpdate.aspx .

So I have uploaded the version that contains the fix and works smoothly with ScrewTurn Wiki Version 3.0.0.333 (RTW). Following is the instruction on how to install the plugin if you are new.

Usage:

  1. First download my screwturn wiki google sitemap generator (at the end of this post).

  2. Copy the sitemap.aspx to you wiki’s root folder.

  3. Navigate to /sitemap.aspx, to check whether it works.

For the original post please look at http://blog.prabir.me/post/Screwturn-Wiki-Google-Sitemap-Generator.aspx

A live example can be seen at http://projects.prabir.me/compiler/wiki/sitemap.xml

ScrewTurn Wiki Google Sitemap Generator For v3 (RTW).zip (1.54 kb) [Downloads: 175]

In case you guys still haven’t upgraded to the newer version here is the Sitemap Generator for older versions.

ScrewTurn Wiki Google Sitemap Generator For v3 (RC1).zip (1.51 kb) [Downloads: 254]
ScrewTurn Wiki Google Sitemap Generator For v2.zip (1.06 kb) [Downloads: 203]

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

Tags: , ,