Prabir's Blog

where the tech matters...

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

Using jqGrid with ASP.NET Web Forms - Part II

December 06
by prabir 6. December 2009 19:43

This article is continuation of my previous article.

To start of with, we first need to create an asmx web service in JSON format. If you are not sure of how to use JSON in asmx web services, I would suggest you to read my previous articles - JSON in Classical Web Services - ASMX and Consuming ASP.NET Web Services using JQuery.

Lets create a web service method called GetListOfPersons. Remember to decorate it with ScriptMethod Attribute as our means of data communication will be in JSON format. In the following example JsonHelper.GetPersons() is responsible for retrieving the list of persons. You can have a appropriate data access logic out there.

[WebMethod]
[ScriptMethod]
public string GetListOfPersons()
{
    List<Person> persons = JsonHelper.GetPersons();
    return Newtonsoft.Json.JsonConvert.SerializeObject(
        new PagedList(persons, persons.Count, 1, persons.Count));
}

Then we create a new instance of PagedList object that we defined in the previous post. Here’s one of the constructor that we will be using in case you have forgotten.

public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize);

For simplicity we will not be including features such as paging and sorting for now. (I will include it in later posts.) So, here the rows will be the list of persons retrieved, totalRecords will be the number of persons in the list hence persons.Count, pageIndex will just be simple as 1 as all data will be displayed on the same page number 1. pageSize will be the totalRecords as we don’t want to having paging enabled for now.

Now that the instance of PageList has been created. We need to serialize the object into JSON format which can be recognized easily by jqGrid. To achieve this we make use of Newtonsoft.JSON library by calling the SerializeObject method as shown above.

Now that we are done with the web service, we need to start coding the user interface in HTML and JavaScript.

Create a HTML table along with an ID. This table will be rendered as jqGrid when previewed in the browser.

 

<table id="table" cellpadding="0" cellspacing="0">
</table>

 

Include appropriate css style sheets and javascript files required for jqGrid to function. You will need the JQuery UI,  and multiselect also. Multiselect JQuery plugin can be obtained from http://quasipartikel.at/multiselect.

 

<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-1.3.2.min.js") %>"></script>
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/redmond/jquery-ui-1.7.2.custom.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.jqgrid.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.multiselect.css") %>" />
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-ui-1.7.2.custom.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/i18n/grid.locale-en.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/ui.multiselect.js") %>"></script>

 

Let me write the code first and then explain later on. So it would be easier for you guys to copy paste and learn.

 

<script type="text/javascript">
    $(function () {
        $("#table").jqGrid({
            datatype: function (pdata) { getData(pdata); },
            height: 250,
            colNames: ['ID', 'First Name', 'Last Name'],
            colModel: [
           		{ name: 'ID', width: 60, sortable: false },
           		{ name: 'FirstName', width: 200, sortable: false },
           		{ name: 'LastName', width: 200, sortable: false }
           	],
            imgpath: '<%= ResolveClientUrl("~/styles/redmon/images") %>',
            caption: "Sample JSON data retrieved from ASMX web services"
        });
    });
    function getData(pData) {
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: '<%= ResolveClientUrl("~/WebService.asmx/GetListOfPersons") %>',
            data: '{}',
            dataType: "json",
            success: function (data, textStatus) {
                if (textStatus == "success")
                    ReceivedClientData(JSON.parse(getMain(data)).rows);
            },
            error: function (data, textStatus) {
                alert('An error has occured retrieving data!');
            }
        });
    }
    function ReceivedClientData(data) {
        var thegrid = $("#table");
        thegrid.clearGridData();
        for (var i = 0; i < data.length; i++)
            thegrid.addRowData(i + 1, data[i]);
    }
    function getMain(dObj) {
        if (dObj.hasOwnProperty('d'))
            return dObj.d;
        else
            return dObj;
    }
</script>

 

jQuery ready function initializes the jqGrid. The data type we have chosen is a custom function with a parameter called pdata. pdata is a short of ParameterData. You can name it what ever you feel comfortable with. It then calls the function called getData. ColName is an array of string containing the column header. ColModal contains more information on how to render data.

Note: The name in ColModal is not the same as ColName but rather its same as that of the list of objects, which was passed as enumerable rows when creating PageList.

Function getData is responsible for doing an AJAX request to the webservice. If success it calls another function called ReceivedClientData. RetrieveClientData function is responsible for appending the data to the grid.

As the data is Ajax request and our response is in string, we need to parse the JSON string to JSON object using json2.js. (We will not be using eval due to security reasons though it is possible.)

GetMain function is used to trip of the “d” property, which is generated by web services if using new versions of ASP.NET for security reasons.

jqGridAspNetWebForms.zip (617.09 kb) [Downloads: 752]

jquery.jqGrid-3.6.zip (274.12 kb) [Downloads: 733]
jquery-ui-1.7.2.custom.zip (745.92 kb) [Downloads: 347]

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

Tags: , , , ,

ASP.NET | JQuery

Using jqGrid with ASP.NET Web Forms - Part I

November 14
by prabir 14. November 2009 14:55

(As this article grew up to be quite long then I expected, I have broken up this post into different Parts.)

When I first started to use jqGrid few months back, I couldn’t find good tutorials on using jqGrid with ASP.NET webforms. Any search on ASP.NET and jqGrid would lead to ASP.NET MVC tutorial. So, I thought of writing this article to help you guys.

I will be using jqGrid version 3.6 (the codes presented here will most probably work with the earlier versions too – You can download the latest version of jqGrid from http://www.trirand.com/blog or version 3.6 at the end of this article).

We will be using JSON as means of data communication which will be provided by asmx web services. If you don’t know how to use JSON in asmx web services, I would suggest you to read my previous articles - JSON in Classical Web Services - ASMX and Consuming ASP.NET Web Services using JQuery. (Similar concepts can also be applied to WCF RESTful web services.)

How does jqGrid understand our JSON format?

Answering the above question is vital for getting things done right. So lets start with understanding JSON format used by jqGrid.

{
    "page":"1",
    "total":4,
    "records":"10",
    "rows":[
        {"id":"1","cell":["Prabir","Shrestha"]},
        {"id":"2","cell":["Bill","Gates"]},
        {"id":"3","cell":["Steve","Ballmer"]}
    ]
}

Page stands for the current page index. Total represents the total number of pages available and records for the total number records in the entire data list including those not shown in the rows.

Let’s have a closer look at rows. It contains 2 fields, id and cell. The cell contains the main data which needs to be rendered. Here again we have two fields. Try guessing what those fields are.

The first field represents First Name and second field represents Last Name. It is basically an array of string. If others are consuming your web services it would be very difficult for them to actually guess the meaning of these fields. To overcome this difficulty in understanding, lets take an alternative approach. We would then have the result in the following manner.

{
    "page":"1",
    "total":4,
    "records":"10",
    "rows":[
        {id:1,FirstName:"Prabir",LastName:"Shrestha"},
        {id:1,FirstName:"Bill",LastName:"Gates"},
        {id:1,FirstName:"Steve",LastName:"Ballmer"},
    ]
}

The above example is more descriptive and easier to understand. But now another problem arises. How do I convert to that JSON format?

To work with this we create a helper class called PagedList as follows.

using System;
using System.Collections;

public class PagedList
{
    IEnumerable _rows;
    int _totalRecords;
    int _pageIndex;
    int _pageSize;
    object _userData;

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize, object userData)
    {
        _rows = rows;
        _totalRecords = totalRecords;
        _pageIndex = pageIndex;
        _pageSize = pageSize;
        _userData = userData;
    }

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize)
        : this(rows, totalRecords, pageIndex, pageSize, null)
    {
    }

    public int total { get { return (int)Math.Ceiling((decimal)_totalRecords / (decimal)_pageSize); } }

    public int page { get { return _pageIndex; } }

    public int records { get { return _totalRecords; } }

    public IEnumerable rows { get { return _rows; } }

    public object userData { get { return _userData; } }

    public override string ToString()
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(this);
    }
}

Notice that I have included all the fields required by jqGrid. And all these also violates standard C# naming standards. This is to make it easy (Javascript is case sensitive) for us to serialize the object to JSON string understandable by  jqGrid by using the help of Newtonsoft JSON library. Total is also calculated automatically for us.

The rows is basically IEnumerable, which means we can also assign List<T> to it. Which makes our work easier. And since we have overridden the ToString method, converting the object to JSON string representation is far lot easier.

Then how do I put all the things together?

For example lets assume the Person class is declared as below.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and let us also assume that there is a method called GetPersons which returns us a List of Person (List<Person>).

Now to create the PagedList, we simply call the constructor of the PagedList.

PagedList pagedList = new PagedList(GetPersons(), 10, 1, 3);

It will then create a new instance of PagedList and assign the GetPersons List<Person> to rows, 10 to records, 1 to page index and 3 to pageSize.

There is no default constructor for PagedList and it is also an immutable object, which means if you need to change anything you will need to create a new instance of it again. The reason I did this was because, I always used to get confused between total, page and records. So I came up with a solution that I would always use constructor and the parameters in these constructors would be name is such a way that it would not confuse me, so I landed up naming them as pageIndex, pageSize and so on. The other way around would be to use the get and set for all the properties and use the xml documentation features using /// <summary> to prevent the confusion.

This concludes the Part I for Using jqGrid with ASP.NET web forms. In part II, I will be going through on how to actually display it in jqGrid. Stay tuned.

jquery.jqGrid-3.6.zip (274.12 kb) [Downloads: 733]

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

Tags: , , ,

ASP.NET | JQuery

Fiddler and Visual Studio Web Server - Cassini

October 26
by prabir 26. October 2009 00:41

If you have been tried using Fiddler in localhost of Visual Studio inbuilt Web Server called Cassini, you mite have noticed that you will receive a HTTP 502 error. Saying [Fiddler] Connection to localhost failed.

To solve this you might try adding period (.) after localhost as shown below.

image

For some machines it seems to work but some it doesn’t. In case in yours it doesn’t work try changing localhost to 127.0.0.1 and then adding period (.) after it.

image

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

Tags:

ASP.NET

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

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

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

Tags:

ASP.NET | C#

Retrieve ASP.NET Profile from App_Code, asmx Web Services

September 19
by prabir 19. September 2009 19:55

Its most very likely that you will be using the Membership, Roles and Profile providers provided by the .NET framework. It has been well designed and is very easy to use.

When you are in the .aspx.cs (basically the class that inherits from System.Web.UI.Page) you can easily access Profile class and get the profile for a particular user by using the following syntax.

ProfileCommon profile=Profile.GetUser("username");

But if you are creating some huge enterprise level applications, you will soon arrive to a problem where you can no longer the access the Profile. This happens if you want to call your profile from .cs files App_Code or library files (.dll) including webservices such as .asmx.

This problem can be solved by accessing the ProfileBase class in System.Web.Profile namespace.

ProfileCommon profile = (ProfileCommon)ProfileBase.Create("username", true);

Even though the method called is Create, it doesn’t create a new Profile for the user. If the profile already exists it retrieves it. Second parameter indicates whether the user is authenticated or anonymous. true if the user is authenticated else false to indicate anonymous.

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

Tags:

ASP.NET

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