Mohammad M. Ramezanpour It's all about my life...

Creating multi-language websites – managing dates

I am currently work on a project which has many DateTime fields in its database that needs to be shown to the end-user; but, in a correct format. Unfortunately, most websites, which I have visited lately, didn’t manage date formats. For instance, if the website’s current language is Persian, the date format should be different. Persians are using Shamsi calendar notwithstanding the fact that Gregorian calendar is used by many other countries including England and United States. So, if the user changed the website’s language to another, which has special calendar (Like Persian), date formats also have to be changed.

There are several ways to manage this issue; but, here is my opinion:

Scenario

I have a website which supports two languages: English and Persian. When the user changed the website’s language to Persian, all dates in that website have to be changed to Shamsi; also, if the user switched back to English, dates must be shown in Gregorian format.

Note: My database stores all dates in datetime fields; so, if you want to use this solution in your own applications, you have to do the same thing. I say this because I have seen some developers who are storing dates in integer data types or some others who store Persian dates instead of standards dates in their databases.

The solution

Since extension methods were introduced by Microsoft, I have used them in nearly all of my projects to achieve different kinds of approaches. I just love them because they give me ability to extend .NET APIs and classes in just the way I want. As a result, I preferred using them in this solution too.

The first thing you need is a method for converting Gregorian dates to Persian. As you know, this would be a very simple method:

private static string ConvertToPersian(DateTime dt) {
var pc = new PersianCalendar();
return string.Format("{0}/{1}/{2}", pc.GetYear(dt), pc.GetMonth(dt).ToString("00"), pc.GetDayOfMonth(dt).ToString("00")); }

Then, you need to create an extension method for DateTime object. I will name it “Localized” because what this method does, is converting the specified date to the correct format according to the website’s language:

public static string Localized(this DateTime dt) {
var currentCulture = Thread.CurrentThread.CurrentCulture;
if (currentCulture.Name.Equals("fa-IR", StringComparison.OrdinalIgnoreCase)) { return ConvertToPersian(dt); } else { return dt.ToShortDateString(); } }

As you can see in the above code, the website’s current culture has been retrieved from System.Threading.Thread.CurrentThread.CurrentCulture property; consequently, as the above code, you can get the website’s current language and return the correct format of date.

After the implementation of this extension method in an application, the “Localized” method can be accessed in all DateTime objects. The following example demonstrates the use of this method:

static void Main(string[] args) {
Console.WriteLine("English date: {0}", DateTime.Now.Localized());
// Changing system language to persian. var culture = new CultureInfo("fa-IR"); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; Console.WriteLine("Persian date: {0}", DateTime.Now.Localized()); Console.ReadLine(); }

And the result would be something like this:

LocalizedMethodSample

 

Hope it helps.

How to create a dynamic object in C# to manage QueryStrings

One of the most important features in C# 4 is Dynamic types that enable you to create dynamic objects. The following is the definition of dynamic types from MSDN:

Visual C# 2010 introduces a new type, dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. However, if the code is not valid, errors are caught at run time.

Unfortunately, after about 2 years from Visual Studio 2010 and C# 4 release, most of C# developers don’t know how to use this feature! This is sad because I think dynamic types are one of the most useful features introduced in C# 4. In this post I’m going to show you a very simple use-case of Dynamic types:

As you know, getting a QueryString parameter is very easy in .NET. You can simply use Requst.QueryString[“{ParameterKey}”] to get the value of a QueryString parameter. By calling Request.QueryString, .NET looks for a QueryString item and returns the value of it if the key is available; otherwise, it’ll return null string.

With C#’s Dynamic feature, you create a class to access the QueryString parameter like the following:

QueryString.{ParameterKey};

To achieve this, you need to create a new QueryString class; and this class must inherit System.Dynamic.DynamicObject class. DynamicObject class is an abstract class and all of the objects with Dynamic functionality must inherit this class.

DynamicObject class has some methods that you can override in order get, set and delete Dynamic values. In this example I’m going to use “TryGetMember” method to get the value of a QueryString parameter.

TryGetMember method provides the implementation for operations that get member values. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as getting a value for a property.

TryGetMember method has two parameters. The first one is “binder” and the second is “result”. The following is definition of each parameter by MSDN.

Binder:

Binder parameter provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the DynamicObject class, binder.Name returns "SampleProperty".

Result:

Result parameter provides the result of the get operation. For example, if the method is called for a property, you can assign the property value to result.

So everything is very simple now! You can get a QueryString parameter using a Dynamic object. The following is the implementation:

public class DynamicQueryString : DynamicObject {
public override bool TryGetMember(GetMemberBinder binder, out object result) {
var queryValue = string.Empty;
queryValue = 
HttpContext.Current.Request.QueryString[binder.Name];
result = string.IsNullOrEmpty(queryValue) ? string.Empty : queryValue;return true;
}
}

Now your Dynamic class is ready to use. You can use this class in a variety of ways but here’s what I prefer:

public class MyPage : System.Web.UI.Page {
public dynamic QueryString {
get { return new DynamicQueryString(); }
}
}

All of my pages in my ASP.NET Web Forms application are inherited to this class so I easily can use my dynamic property. Below showing a page that inherits MyPage class and gets the QueryString parameter ID using dynamic types:

public class Default : MyPage {
protected void Page_Load(object sender, EventArgs e) {
Response.Write(this.QueryString.ID);
}
}

Hope it helps.

Quick post: How to access an action in different areas in ASP.NET MVC

17. May 2012 00:10 by Mohammad Mahdi Ramezanpour in ASP.NET MVC

Sometimes I like to post about something, but that thing is very simple and can be described in one or two paragraphs. Previously, I preferred not to post these kinds of things as a blog post but recently, I decided to post almost anything in my blog no matter how many characters they are. So here you go!

When developing an ASP.NET MVC 3 application, you may want to partition your application into different areas for any kinds of reasons:

The MVC pattern separates the model (data) logic of an application from its presentation logic and business logic. In ASP.NET MVC, this logical separation is also implemented physically in the project structure, where controllers and views are kept in folders that use naming conventions to define relationships. This structure supports the needs of most Web applications.

However, some applications can have a large number of controllers, and each controller can be associated with several views. For these types of applications, the default ASP.NET MVC project structure can become unwieldy.

To accommodate large projects, ASP.NET MVC lets you partition Web applications into smaller units that are referred to as areas. Areas provide a way to separate a large MVC Web application into smaller functional groupings. An area is effectively an MVC structure inside an application. An application could contain several MVC structures (areas).

For more about MVC areas, check this out: http://msdn.microsoft.com/en-us/library/ee671793.aspx

When want to develop a web application using MVC, you probably need to access actions/partial views from different areas. For example: You need to have an ActionLink to access the login action in Admin area. In order to do so, you simply need to add a RouteAttribute to your ActionLink as following:

@Html.Action("LoginStatus", "Users", new { area = "Admin" })

If you want to access root area, all you need to do is to set the area name to String.Empty:

@Html.Action("LoginStatus", "Users", new { area = "" })

Hope it helps.