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

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

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

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

Tags: , ,

.NET Framework | ASP.NET

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#