Category Archives: C#

QuickBytes: Decimal to Indian Numeric formatting

image

Recently I came across the need to format Decimal as Currency, but force it down to Indian/Vedic/South Asian numeric formatting (thousands, lacs, crores etc.) instead of the standard Arabic/Metric system (thousands, hundred thousands, million, billion etc.).

The answer was easily found in this StackOverflow thread. The code snippet is reproduced here:

string fare = “123000.0000”;
decimal parsed = decimal.Parse(fare,
CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo(“hi-IN”);
string text = string.Format(hindi, “{0:c}”, parsed);

The above code gives us the following string

₹ 1,23,000.00

However, the next requirement was to keep the decimals and formatting but remove the Currency symbol. Another quick search gave us this little gem from Jon Skeet on StackOverflow. Essentially he extracted the NumberFormatInfo from the CultureInfo and reset the Currency Symbol to an empty string. Then use the NumberFormatInfo instance to format the decimal value. So the above code can be modified as follows:

string fare = “123000.0000”;
decimal parsed = decimal.Parse(fare,
    CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo(“hi-IN”);
NumberFormatInfo hindiNFO =
    (NumberFormatInfo)hindi.NumberFormat.Clone();
hindiNFO.CurrencySymbol = string.Empty;

string text = string.Format(hindiNFO, “{0:c}”, parsed);

This gives us the following string. It’s difficult to see here but there is a leading space that you might want to trim if you need to.

1,23,000.00

A Sample Application

I thought it would be a fun project to write some code that gives you the above code for any Culture Code you want, so I setup a basic ASP.NET project and deployed it for free on the AzureWebsites. You can see it in action here – Currency Formatter on Azure WebSites

  • I spun up Visual Studio 2013 and setup a default MVC project.
  • Next I updated KnockoutJS to the latest version

PM> update-package KnockoutJS

  • Added an Entity to encapsulate the culture information. I referred to this list on MSDN as my source.

public class IsoCultureInfo
{
    public int Id { get; set; }
    public string LanguageCultureName { get; set; }
    public string DisplayName { get; set; }
    public string CultureCode { get; set; }
    public string ISO639xValue { get; set; }
}

  • Scaffolded up an EntityFramwork controller: CultureInfoController
  • Added two methods to the CultureInfoController that return JsonResults
  • The first one simply returns the entire list of IsoCultureInfo objects in the DB

public JsonResult List()
{
    return Json(db.IsoCultureInfoes.ToList(), JsonRequestBehavior.AllowGet);
}

  • The second one formats the predefined text based on the incoming Culture Name and returns the formatted text as a JSON object.

public JsonResult FormattedText(string id)
{
     try
     {
         string fare = "123000.0000";
         decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
         CultureInfo cultureInfo = new CultureInfo(id);
         NumberFormatInfo cultureNFO = (NumberFormatInfo)
cultureInfo.NumberFormat.Clone();
         //cultureNFO.CurrencySymbol = string.Empty;
         string text = string.Format(cultureNFO, "{0:c}", parsed);
         return Json(new { formattedCurrency = text });
      }
      catch (Exception ex)
      {
          return Json(new { formattedCurrency = "N/A" });
      }
}

  • Both these methods are invoked from the Index HTML. The UI is databound to a Knockout ViewModel. This is defined in the script formatCurrency.js

/// <reference path="_references.js" />

var isoCultureInfo = {
    LanguageCultureName : ko.observable(“”)
};

var viewModel = {
    dataList: ko.observableArray([]),
    formattedString: ko.observable(“Test”),
    selectedCulture: ko.observable(isoCultureInfo)
};

$(document).ready(function () {
    $.ajax(“/CultureInfo/List”,
        {
            type: “GET”,
            contentType: “text/json”
        }).done(function (data) {
            viewModel.dataList = ko.mapping.fromJS(data);
            ko.applyBindings(viewModel);

            viewModel.selectedCulture.subscribe(function(newValue){
                if (newValue.LanguageCultureName() != ”) {
                    var data = { “id”: newValue.LanguageCultureName() };
                    $.ajax(“/CultureInfo/FormattedText”,
                        {
                            type: “POST”,
                            contentType: “application/json”,
                            data: JSON.stringify(data)
                        }).done(function (data) {
                            viewModel.formattedString(data.formattedCurrency);
                        }).error(function (args) {
                            alert(“”);
                        });;
                };
            });
        }).error(function () {

        });
});

  • Finally I updated the Index.cshtml of the Home Controller to show the dropdown with the list of culture info.

        Select Culture: <select id="cultureOptions"
                                class="form-control"
                                data-bind="options: dataList(), optionsText: 'LanguageCultureName', value: selectedCulture, optionsCaption: 'Choose...'"></select>

  • Added a <ul> to show all the property values of the selected Culture

<ul>
    <li>Language Culture Name: <b><span data-bind="text: LanguageCultureName"></span></b></li>
    <li>Display Name: <b><span data-bind="text: DisplayName"></span></b></li>
    <li>Culture Code: <b><span data-bind="text: CultureCode"></span></b></li>
    <li>ISO 639x Value: <b><span data-bind="text: ISO639xValue"></span></b></li>
</ul>

  • Next we have a <pre> section which contains the code that changes as per the selected Culture.

<pre>
string fare = “123000.0000”;
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo cultureInfo = new CultureInfo(<b><span id=”currentCulture” data-bind=”text: LanguageCultureName”></span></b>);
NumberFormatInfo cultureNFO = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
// If you don’t want the CurrencySymbol, uncomment the following line
// cultureNFO.CurrencySymbol = string.Empty;
string text = string.Format(cultureNFO, “{0:c}”, parsed);
</pre>

  • Finally we have a span to show the formatted string returned after we have selected the Culture Info

Formatted String: <b><span data-bind="text: $parent.formattedString"></span></b>

Conclusion

The code snippet changes as you select the Culture Info in the dropdown and you can copy paste it directly. I deployed it on a free Azure Website, how? That’s for another day Smile.

Tagged , ,

Entity Framework and MS Web Stack of Love – First Steps

Things they didn’t show you at MIX keynotes Winking smile

Okay, so you saw the MIX keynotes and were really really impressed with what MVC, EF 4.1 Code First and Scaffolding could do for you and excitedly sat down to try and get your old lumbering enterprise app transformed using the Web Stack of Love. Couple of steps in and you start stumbling around. Visual Studio throws errors, things stop working and you are scratching your head as to where you went wrong! Well happened to me and I got lucky in finding the solutions quickly with help from the community. Here are the details.

Model First or Database First with EF 4.1

As mentioned above the first thing I tried to do was get my old lumbering enterprise app moved to the new MVC platform. Now when you have an enterprise platform you can’t throw it away with the accumulated data of last 5 years. So the easiest way is to go Database first, reverse engineer the database to generate your data model. Below are the steps you would follow

  • Create an ASP.NET MVC Web Application using the new project template
  • Create a generic Class library project
  • Add ADO.NET Entity Data Model file (edmx) to the class library
  • Generate model from DB Connection by connecting to the database. So far so good, no issues.
  • Now you add reference to your database project to the web project, copy the connection string over from the class library’s app.config to web app’s web.config, and build it. Everything builds fine.
  • You right click on the Controller folder and select Add Controller and the MVC tooling wizard comes up. You select your root entity name and ask it to generate the controller, Visual Studio whirrs for a while and bam! Error!

    —————————
    Microsoft Visual Studio
    —————————
    Unable to retrieve metadata for ‘Your.Data.Entity’. The type ‘Your.Data.Entity’ was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
    —————————
    OK  
    —————————

  • So what did you miss. Well EF is all code first so the old style generation of Entities (EF < v4) fail to work. If you read the last line of the error ‘… and does not inherit from EntityObject’ it gives you a hint.
  • What now? Manually edit everything? That would defeat the whole purpose of O-R mapping right? Well solution was provided by Julie Lerman (MS MVP) in her blog here. I’ll summarize here.
  • Go back to EDMX file and open the EDMX designer.
  • Right click and select ‘Add Code Generation Item’.
  • From the ‘Add New Wizard’ select ADO.NET DBContext Generator. You’ll see it gives a Model1.tt (t4 template) name. Change the name if you want to and select Add.

image

  • You will see under in the class library a node gets added with the t4 template. When you expand the node you have the C# (or VB) classes for your entities.
  • Now build and re-try scaffolding the Controller and things will go through smoothly.

Taming the SQL Compact 4.0 for Model First Development

Here is another workaround for people who want to do Model First Development. Since SQL Compact 4.0 was released out of band from Visual Studio and .NET 4.0 releases, somewhere in the tooling chain something broke. As a result, when you try to add a new Connection using Generate Database Wizard you don’t see SQL Compact 4.0. You see up to 3.5 only. So how do you get 4.0 goodness?

Refer to the selected answer from this stackoverflow.com thread

The answer is pretty to the point so I won’t repeat it here.

Trouble with Modernizer.js  (ver 1.7.x only on VMs)

If you run your dev environment on a VM (like VM Ware on Mac), IE9 disables hardware rendering and the modernizer.js that ships by default keeps throwing exception ‘Microsoft JScript runtime error: Unexpected call to method or property access’. This happens for every page and become very irritating quickly.
Solution is to go to www.modernizer.com and download their latest library (2.0.6 at the time of writing this). Remove the 1.7.x reference from your web application and add 2.0.x version. Voila!

 

That’s about it for now. I’ll put down more of my experiences as I go forward with my EF adventures. When I started this article we had only 4.1 now we have 4.2 CTP out Smile. Fast! Very Fast!

Tagged , , , , , , , , , , , ,

How to make ASP.NET GridView emit proper tags

I know I know, ASP.NET WebForms is a passe and MVC is the king of the ring, but if you, like me, still have to work with legacy WebForm components then more often than not you’ll need to use the GridView control. When using GridView control if you want to use jQuery and jQuery plugins to jazz up your grid, you’ll hit a wall because the GridView control emit straight <td> <tr> instead of the more ‘compliant’ <thead> <tr> <th> and <tbody> <tr> <td>

As a result most jQuery plugin’s don’t work. I was despairing at this thought when I came across this article on www.dotnetcurry.com

The article demonstrates tips and tricks with GridView, but it had the hidden gem of how to get the GridView to render <thead> tags. Recipe is simple, handle the GridView’s PreRender event and put the following code in

if (myGridView.Rows.Count > 0)
{
 myGridView.UseAccessibleHeader = true;
 myGridView.HeaderRow.TableSection = TableRowSection.TableHeader;
}

With this done, the whole wide world of jQuery goodness opens up. In the following example I use the DataTables plug-in to add a nifty search functionality and frozen header and vertical scrolling.

Example

We will create a new ASP.NET web application and use the DataTables jQuery plugin to jazz up our grid view control.

Step 1 – Getting Started

Fire up Visual Studio (whichever version you have) and create a new ASP.NET Web Application

image

Step 2 – Finding a Data Source (ignore this and Step 3 if you already have a data source handy)

In Solution Explorer, right click on App_Data folder and select Add Existing Item. I have SQL Server compact edition installed which installs the NorthwindDB.sdf file in the following folder location

C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Samples\Northwind.sdf

If you don’t have Compact Edition 4.0 you can download it from here

Step 3 – Connecting to Northwind database

Bring up Server Explorer and double click on Northwind.sdf to connect to it. Change the header to something like “Products From Northwind Database” and remove the other default paragraphs.

Step 4 – Add the GridView

Double click on Default.aspx to open the designer. Switch to Split or Design mode and Drag and Drop the GridView control

Step 5 – Do the magic to render proper table tags

Change the Name of the gridview to jqDemoGridView. Add a PreRender event handler and place the above code in the event handler to ensure the GridView emits proper table tags in HTML.

Step 6 – Get the scripts

a. If you are using derivatives of Visual Studio 2010 your project should come with jQuery included by default under the Scripts folder. I got version 1.4.1 with my project. You can get the latest version from here and place it in your Scripts folder.

b. Next we will get the DataTables plugin scripts from here (~8Mb).
Download the zip file and extract it. Open Windows Explorer and navigate to the extracted folder. There should be three folders from the zip, examples, extras and media.

c. From the media folder select the images and js folder and press Ctrl+C to copy them
Go to Visual Studio, select the Scripts folder in Solution Explorer and press Ctrl+V to add the folders.

d. From the media\css folder select all the css files and paste it in Solution View’s Styles folder.

e. From the examples\example_support\themes\smoothness folder copy the jquery-ui-1.8.4.custom.css and the images folder. Paste is under Sytles folder

f. Exclude the jquery.dataTables.js, jquery.js and jquery.dataTables.min.js.gz files. The rest of the files are enough. (the .min.js version is minified meaning it doesn’t have any kind of whitespaces and reduced in size as much as possible. It’s not at all readable so if you want to go through the js to understand it, use the non-minified version) Your solution explorer should looks something like the following.

image

Step 7 – Connect to Data Source

I will connect to the above data using the Entity Data Source. You can select your own data connection mechanism. Basically the idea is to get the GridView populated with enough data that requires a vertical scrollbar. If you are using SQL CE 4.0 like me follow along.

a. Right Click on Solution Explorer and Select Add New Item. Select Data from the Installed Templates and ADO.Net Entity Data Model. Name it NorthwindModel.edmx

image

b. Select the default ‘Generate from Database’ and click Next.

image

c. If Northwind.sdf connection was open it will select it by default and the next screen should look something like the following.

image

d. The Wizard will connect to the DB and load up the schema. Select all the tables and click Finish.

image

e. Save solution and do a ‘Build All’.

Step 7 – Tie the GridView to the data source

a. In the designer click on the GridView smart tag and bring up the Choose Data Source Dialog

image

b. Click Ok to bring up the Configure ObjectContext wizard. It should select the NorthwindEntites connection it created while building the data source by default. If you named it differently in Step 6.c. select the name that you gave it. The DefaultContainerName will come up automatically once you select the Named Connection. Click Next.

image

c. Select the EntitySetName (table) that you want to show. I’ve selected the Products table and opted to show all the columns. You can pick and choose. As of now we are not doing any Inserts/Updates or Deletes, keep them unchecked. Click Finish

image

If you run your application at this point you will see the grid populated with data from the products table. Just for kicks right click on the browser to bring up source, you will see the <thread><tr><th> rendering for the table in the final HTML. So far so good.

Step 8 – Bring in the jQuery Goodies

Here comes the fun part now. Let’s tie up our grid with jQuery and datatables goodness.

a. Open Site.Master and drag and drop the demo_table_jui.css from the Scripts\css folder on to the header area

b. Open the Default.aspx and in the BodyContent area, drop the jQuery script file and the jquery.dataTables.min.js file.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/js/jquery.dataTables.min.js" type="text/javascript"></script>

c. Add the following script to apply the plugin to the GridView

<script type="text/javascript" charset="utf-8">
 $(document).ready(function ()
 {
   $('#<%= jqDemoGridView.ClientID %>').dataTable({
           "bJQueryUI": true,
           "bPaginate": false,
           "bLengthChange": false,
           "bFilter": true,
           "bSort": true,
           "bAutoWidth": false,
           "sScrollY": 300,
           "sScrollX": "100%",
           "sScrollXInner": "110%"
      });
 });
</script>

The dataTable method is taking an object as a parameter. The object is defined in JSON. Let’s look at each parameter and try to get what it is
i. bJqueryUI : A boolean parameter indicating if JqueryUI should be used to beautify the grid. We set it to true
ii. bPaginate: A boolean parameter indicating if pagination should be enabled. We set it to false to force vertical scrollbars
iii. bLengthChange: A boolean parameter (not sure what it does, it’s set to false in our code).
iv. bFilter: A boolean parameter indicating if Filtering should be enabled. We set it to true.
v. bSort: A boolean parameter indicating if Sorting should be enabled. We set it to true.
vi. bAutoWidth: A boolean parameter indicating if datatables should try to set the width of the columns. We set it to false
vii. sScrollY: A integer parameter indicating the fixed height of the table. Scrolling is enabled after rows of data exceed this height.
viii. sScrollX and sScrollXInner: Parameters that help enable horizontal scrolling.

For a complete reference to possible parameters refer to DataTables’ excellent documentation on their site. A quick reference guide is available here
Clean up the Default.aspx by removing the default messages and run the application.

Lo and behold!

image

Step 9 – Playing around with the ‘jQuerified Grid’

a. Type in Anton in the search text box and see the grid filter data down to 2 rows of data showing Chef Anton

b. Click on any of the headers and watch the grid get sorted without any postback (entirely on the client side)

c. Scroll horizontally and vertically and see how the headers remain aligned.

In Conclusion

We started off with the small goal of figuring out how to emit thead for a GridView control and ended up applying a jQuery plugin to add rich client side functionality thanks to the proper rendering of thead and tbody tags. This opens up a vast playground for jQuery enabled ASP.NET sites with interactive GridView. Notice we haven’t used Microsoft’s Ajax Control Tool Kit anywhere. Though I have used DataTables and jquery and Ajax Control Toolkit all in the same page and they do work together. But that’s another story. I am trying to make a clean break from ACT and do things in jQuery only. Hopefully sometime soon, I’ll be able to demonstrate use of more jQuery plugins with more functionality like Edit/Update/Delete from the grid view control.

The entire source code including the Northwind.sdf file is uploaded here (hosted on SkyDrive – 714KB download size).

This code uses DataTables.net which is released under GPL v2. Please respect open source licensing model. Whatever little I have written is made available As Is.

Have fun coding!

Tagged , , , , , , , , ,
%d bloggers like this: