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

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

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

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

Tags: ,

Javascript | snippets

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

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

[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