Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Archive for November, 2010

ASP.NET–How to format currency based on user’s browser setting

Posted by Paul on November 11, 2010

Hello All.  In this example I am trying to show how to format currency based on user’s browser setting.

Our aim is to show them the formatted currency like:

Format Language
$1,000.00 United States
1,000.00د.إ.‏ Arabic
R$ 1.000,00 Portugese
1.000,00 TL Turkish

Step 1: Create the ASP.NET Application

Create a new web application and on the default page place a button and label.

On the button click you can add the following code.

protected void Button1_Click(object sender, EventArgs e)

{

    CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(this.Request.UserLanguages[0]);

 

    double value = 1000;

    Label1.Text = value.ToString("C", cultureInfo.NumberFormat);

}

The code collects the user language from Request object and uses the ToString() method to format the value.

That finishes the coding part.. Now you have to see the things working.  For this you have to run the application and test it by changing the browser language.  I will guide you through it.

Step 2: Execute the application

You can execute the application and see the page opened in your browser.

image

Try clicking the button and you can see the number formatted in current language.

Step3: Change Browser Language

In this step we have to change the browser language.

If you are using Internet Explorer choose Internet Options screen.

image

Click the Languages button on the bottom and you can see the following screen.

image

Click the Add button to add a new language.  Select Arabic, move it up using the “Move up” button and click Ok.

image

Now you are ready to test the code in Arabic.

Click the “Change Format” button again and you can see the number format in Arabic.

image

Note: After changing the languages to back in browser you might need to restart it.

Advertisements

Posted in C# | Tagged: , , , | Leave a Comment »

ASP.NET–How to format currency based on user’s browser setting

Posted by Paul on November 11, 2010

Hello All.  In this example I am trying to show how to format currency based on user’s browser setting.

Our aim is to show them the formatted currency like:

Format Language
$1,000.00 United States
1,000.00د.إ.‏ Arabic
R$ 1.000,00 Portugese
1.000,00 TL Turkish

Step 1: Create the ASP.NET Application

Create a new web application and on the default page place a button and label.

On the button click you can add the following code.

protected void Button1_Click(object sender, EventArgs e)

{

    CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(this.Request.UserLanguages[0]);

 

    double value = 1000;

    Label1.Text = value.ToString("C", cultureInfo.NumberFormat);

}

The code collects the user language from Request object and uses the ToString() method to format the value.

That finishes the coding part.. Now you have to see the things working.  For this you have to run the application and test it by changing the browser language.  I will guide you through it.

Step 2: Execute the application

You can execute the application and see the page opened in your browser.

image

Try clicking the button and you can see the number formatted in current language.

Step3: Change Browser Language

In this step we have to change the browser language.

If you are using Internet Explorer choose Internet Options screen.

image

Click the Languages button on the bottom and you can see the following screen.

image

Click the Add button to add a new language.  Select Arabic, move it up using the “Move up” button and click Ok.

image

Now you are ready to test the code in Arabic.

Click the “Change Format” button again and you can see the number format in Arabic.

image

Note: After changing the languages to back in browser you might need to restart it.

Posted in C# | Tagged: , , , | Leave a Comment »

Part 2 of 7 : Installing WCSF

Posted by Paul on November 10, 2010

We can download “Web Client Software Factory – February 2008” from the following link and install it.

http://www.microsoft.com/downloads/en/details.aspx?FamilyId=47755838-049B-4291-AFEA-A379AE28D7B3&displaylang=en

Additional Requirements

WCSF requires following things to be installed.

  • Windows XP/Vista/2003
  • Visual Studio 2008
  • .Net 3.5

Verification

After installation you will be able to see the following new project type.

image

Posted in ASP.NET | Tagged: , , | Leave a Comment »

Part 1: Web Client Software Factory

Posted by Paul on November 10, 2010

Web Client Software Factory (WCSF) is a framework for Web Client creation with proven practices and patterns.  It is built up on ASP.NET.

Advantages of WCSF

  • Model View Presenter (MVP) support
  • Automatic Service Instance Creation resulting in reduced coding and memory overheads
  • Hides Complexity in traditional ASP.NET application
  • More support for Unit Tests
  • Reusability through Modules

Reference

http://msdn.microsoft.com/en-us/library/ff648752.aspx

Posted in ASP.NET, Web Client Software Factory | Tagged: , , | Leave a Comment »

Part 4: WCSF : Adapting to Model View Presenter (MVP) architecture

Posted by Paul on November 9, 2010

One of the cool benefits of WCSF is the support of Model View Presenter (MVP). 

The advantages of MVP are many:

  • Isolation of User Interface management code through Presenter
  • Isolation of Business Logic code through Controller
  • Improved Unit Test support for code

Note: The MVP here also contains a Controller class

Learn by Example

From the previous part, we can try to create a web page having one textbox and button.

On clicking the button the data will be saved to session.  Let us see what are the infrastructure needed for that.

Step 1: Create new Page

Right click on our previous WCSF project and use the context menu “Web Client Factory”> Add Page with Presenter

image

The following wizard will appear:

image

Enter the view name as “MyData” and click Finish.

Right click on the MyData.aspx and make it Default page.

Step 2: Add Data property to IDefaultView

Open the IMyDataView.cs from Shell project and add the following property inside it.

image

As the MVP provides decoupling of user controls from code, we need to create properties for each user interface element.

This could be like Name, Address, HasLicense etc. for user controls like TextBox, RadioButton etc.

For DataGridView we will need to declare properties like IList<Employee> etc.

Step 3: Implement the Data property

Now we need to implement the new Data property inside our aspx page.

First we have to create a textbox in the webpage and connect it to the Data property.

For this place a new textbox and name it txtData.  Place a button too aside.

image

Create the property named Data inside the MyData.aspx page like following.

image

Step 4: Build the solution

If the build succeeds we are in good position.

Posted in ASP.NET, Web Client Software Factory | Tagged: , , | Leave a Comment »

Part 3: WCSF : How to create a new solution?

Posted by Paul on November 9, 2010

This article shows how to create a new web project in Web Client Software Factory.

Step1: Select “Web Client Solution”

Open your Visual Studio and select File>New Project.  Select the Web Client Solution from the category shown in image.

image

Click Ok and you will get the following wizard.

image

Click Finish to end the wizard.

Posted in ASP.NET, Web Client Software Factory | Tagged: , , | Leave a Comment »

TDD :: TypeMock :: Reference

Posted by Paul on November 3, 2010

Test Driven Development (TDD)

TDD confines to be a good agile methodology.  It will give the long term advantage of maintainability to the code that will give confidence while refactoring.  I believe if properly used there is no much time cost incurred in using TDD, because I a big fan of TDD .

Advantages of TDD

Although it might incur some investment to do TDD in the long run it is definitely advantage especially in product development.  If properly written it should cover all the user code in the application thus making sure changes can be carried with confidence and manageable.  In the long run it will save time and effort multiple times and speeds up the productivity.  Thanks to the creators of TDD.

Mocking

Mocking of code is required while implementing TDD.  There are multiple scenarios we encounter for mocking.

  • When a method is calling a User Interface element
  • When a method is calling a Web Service
  • When a method is calling another method in same class
  • When a method is calling another method in different class

I will show some TDD scenarios that many times we encounter.  It is generally true that whenever the method is going out of its boundary we should mock that.

Note: All the tests are based on TypeMock which is a licensed software.  You need to refer to TypeMock.dll and TypeMock.ArrangeActAssert.dll

Example1: Simple TDD

public class User

{

    public bool IsUserLicensed()

    {

        DialogResult result = MessageBox.Show("Have License?", "Prompt", MessageBoxButtons.YesNo);

 

        if (result == DialogResult.Yes)

            return true;

        else

            return false;

    }

}

The Test method with mocking would look like:

[TestMethod()]

public void Test_User_HasLicense()

{

    User target = new User();

    Isolate.WhenCalled(() => MessageBox.Show(string.Empty)).WillReturn(DialogResult.Yes);

 

    bool result = target.HasLicense();

 

    Assert.AreEqual(true, result);

}

Example2: Testing Method which is calling another Private/Public method

In the previous example MessageBox.Show() was the call violating the scope of method IsUserLicensed().  So we mocked it and it was easier as the MessageBox class was accessible from the test method.

But things won’t be the same.  You might be needed to mock private methods too.  In this case we run into a problem like the method would be not accessible outside the class.

There are two ways of solution for this:

1) Create Private Accessor through Visual Studio, specify the method name as it is

2) Pass the method name as string in mocking

We can try with the second way – passing method name as string

public string GetCitizenship() // Public methods

{

    string citizenship = GetCitizenshipFromDb();

 

    return citizenship;

}

 

private string GetCitizenshipFromDb() // Private Method, we have to mock this method

{

    return "USA";

}

The mocking code for the above would look like:

[TestMethod()]

public void GetCitizenshipTest()

{

    User user = new User();

 

    Isolate.NonPublic.WhenCalled(user, "GetCitizenshipFromDb").WillReturn("USA");

 

    string result = user.GetCitizenship();

 

    Assert.AreEqual("USA", result);

}

 Example3: Mocking a property which do not have setter

The source code will look like:

public bool IsGetterOnlyPropertyValid()

{

    return this.IHaveOnlyGetter == "ValidText";

}

 

private string _iHaveOnlyGetter;

 

public string IHaveOnlyGetter

{

    get { return _iHaveOnlyGetter; }

    // set; – No Setter here

}

From the above IsGetterOnlyPropertyValid()we can see that inorder to return true, the property IHaveOnlyGetter should be “ValidText”.  We cannot set the property from the test method as there is no setter for the property.

The solution would be a different style as given below.

[TestMethod()]

public void IsGetterOnlyPropertyValidTest()

{

    User target = new User();

 

    Isolate.WhenCalled(() => target.IHaveOnlyGetter).WillReturn("ValidText");

 

    bool result = target.IsGetterOnlyPropertyValid();

 

    Assert.AreEqual(true, result);

}

Posted in C# | Tagged: , , | Leave a Comment »

Speed of Lambda

Posted by Paul on November 2, 2010

I have tried many Lambda expression evaluations and enjoyed the reduced coding efforts they provide. But really I would like to evaluate the speed benefits that Lambda provides. In this article I am trying to compare the speed difference of Lambda expressions with traditional programming. The results are mind-blowing.

Simple Scenario : Finding Sum

We have a list of ten thousand numbers and finding the sum n times. The loop will be going for n times each time incrementing the list count.  The sum method with Lambda Expression will be:

private decimal GetSum_Lambda()
{
      return list1.Sum(); // Using pre-defined method
}

The core sum method without  Lambda Expression will be:

private decimal GetSum_WithoutLambda()
{
      decimal sum = 0;
      foreach (decimal d in list2)
          sum += d;

      return sum;
}


The output is graphically depicted as following.

image

The red lines in x axis shows the processing time and y axis shows increasing complexity of the test.  Both test complexity are equally distributed.
The above test shows that Lamda expressions for the scenario is almost 50% faster. Not too much you might wonder – I agree. But in the following test you will be seeing some surprising outputs.

Complex Scenario : Finding Distinct and then Sum

Shall we move towards a complex scenario?
Here the list has duplicate numbers. We need to remove the duplicate numbers and calculate the sum. This involves the following steps.
1. Remove the duplicates and create the new list
2. Find the sum from new list
The distinct and sum method with lambda expression looks like:
private decimal GetDistinctSum_Lambda()
{
      return list1.Distinct().Sum();
}

The distinct and sum method without using lambda expression would be:
private decimal GetDistinctSum_WithoutLambda()
{
      // Find Distinct
List<decimal> distinctList = new List<decimal>();
foreach (decimal number in list2)
if (!distinctList.Contains(number))
                  distinctList.Add(number);

// Find Sum
decimal sum = 0;
foreach (decimal d in distinctList)
            sum += d;

return sum;
}


The output is graphically depicted as following.

image

Total Time for Lambda: 1 second
Total Time without Lambda: 11 seconds

From the above picture shows that Lambda expression is multiple times faster than the usual approach, as well it is memory efficient too.

Test Application
In the test application, both the simple and complex scenario can be tested using the combo box.
Click the Start button to start the computations. First the left panel computations are executed and then the right. Hope you can execute it.  Please let me know your suggestions or comments on the article.

You can download the test application from: http://www.c-sharpcorner.com/UploadFile/40e97e/4077/Default.aspx


Note

If we try many examples like this we can identify Lambda is having multiple time performance benefits than traditional programming. So I believe it is worth investing in Functional Programming in C# through Lambda Expressions. Happy Coding.

Posted in Lambda Expressions | Tagged: , , | 1 Comment »