Tuesday, May 27, 2008

Format Number As Currency String [C#.NET]

While developing web/windows applications it is very useful to display human friendly currency values as $1,345.00 instead of 1345. In C#.NET it is simple to convert a number to currency format string using the method string.format and the format item C

string.Format( "{0:C}", 123345);

Here is a fully functional sample code

class Program
{
    static void Main(string[] args)
    {
        int nPrice = 1234;
        string sString;
        //
        sString = string.Format("{0:C}", nPrice);
        //
        Console.WriteLine("Price: " + sString);
        Console.ReadLine();
    }
}

Changing the default currency symbol

If you execute the above sample code you might have seen a different currency symbol in the output other than $. The currency symbol used by string.format method depends on your operating system's regional settings. For instance if you are running the code on a OS configured with Indian regional settings you would have seen the output as Rs. 1,235.00.

If required you can change the currency to be used by String.Format method with the help of NumberFormatInfo class. Here is a sample code that forces string.format to use Pound as currency sign

System.Globalization.NumberFormatInfo nfi;
nfi = new NumberFormatInfo();
nfi.CurrencySymbol = "£";
sString = string.Format(nfi, "{0:C}", 123345);

Saturday, December 01, 2007

Stop Visual Studio.Net Editor Generating Unnecessary WinForm Controls Code[.NET]

Microsoft Visual Studio.NET editor automatically generates code for each and every control which you drag and drop on a WinForm. But we mostly don’t refer to the code of certain controls like labels, panels, group boxes.

It is possible to get rid of auto-generated code for such controls by setting the property GenerateMemberCode value to false.

For example if you have a label control in a WinForm which you don’t refer in the code and you prefer to remove the cluttered code of that label then follow these steps

  1. Select the label control displayed in the WinForm designer
  2. Open properties window
  3. Set GenerateMember property value to false

Wednesday, November 07, 2007

Microsoft.NET Framework 3.5 Types and Namespaces Poster

Microsoft released poster of .NET Framework 3.5 Commonly Used Types and Namespaces. The poster gives an overall idea on all the important namespaces and classes of new .NET Framework 3.5.

If you love .NET Framework, you can keep this images as your desktop background or get a big printout to fix it near your desk.Microsoft .NET Framework 3.5 Common Types and Namespace - Poster

The poster is also available as a PDF file which is more clear. You can download it from here.

Sunday, October 21, 2007

C#.NET : Display TreeView Nodes in Different Colors

It's always fun to customize and draw .NET graphical user control to suite specific needs of our application. In .NET framework 2.0 custom painting of Windows user controls is very easy and even beginners can  master the art of custom painting in couple of days.

Today we would like to explain you how to change the colors of TreeView nodes using a sample C# program. The sample program which we are going to create now displays selected nodes of a TreeView control in Red color. Start following these simple steps

  1. Open Visual Studio.NET 2005 editor and create a new C# Windows project
  2. Open Form1 in designer mode
  3. Drag and drop a TreeView control on the Form1
  4. Add few nodes to the TreeView control(use the property Nodes to add nodes)
  5. Set the property DrawNode of the TreeView control to OwnerDrawText
  6. Add the following code to DrawNode event of the TreeView control and execute the project. That's all you see selected nodes in red color.

private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)

{

   //Paint text of selected node in red color

   if ((e.State & TreeNodeStates.Selected) != 0)

   {

       e.Graphics.DrawString(e.Node.Text,

               e.Node.TreeView.Font,

               Brushes.Red,

               e.Bounds);

 

   }

   //Paint text of other nodes in default color

   else

   {

      e.DrawDefault = true;

   }

}


If you observer the above  DrawNode event code, selected nodes are identified with the criteria (e.State & TreeNodeStates.Selected) != 0 . And the selected node's text is painted in red color by specifying Brushes.Red as third parameter in the e.Graphincs.DrawString method. Now its your time to play with this event and customize painting of nodes. Enjoy programming.

Friday, October 19, 2007

Microsoft.NET Family Welcomes F# To Be As First Class .NET Language

F#, the functional programming language incubated by Microsoft imageResearch is now elevated as 1st class .NET programming language. This brings F# to be hand in hand with .NET framework which allows seamless integration with other .NET programing languages like C#,VB.NET. Also F# will be fully integrated with Visual Studio IDE to provide the development environment which every developer love to work with. 

How is F# Pronounced?

F# is pronounced as F-sharp which is very similar to the way C#(C-Sharp) is pronounced.

What type of language is F#?

F# is a functional programming language which is derived from ML family of languages. Here is the Wikipedia definition for functional programming and ML family of languages

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast with the imperative programming style that emphasizes changes in state.

ML is a general-purpose functional programming language developed by Robin Milner and others in the late 1970s at the University of Edinburgh,[1] whose syntax is inspired by ISWIM. Historically, ML stands for metalanguage as it was conceived to develop proof tactics in the LCF theorem prover (the language of which ML was the metalanguage is pplambda, a combination of the first-order predicate calculus and the simply-typed polymorphic lambda-calculus). It is known for its use of the Hindley-Milner type inference algorithm, which can automatically infer the types of most values without requiring explicit type annotations.

What are the goals of F#?

F# is developed to implement the core features of ML programming on the .NET platform to bring the benefits of .NET and ML-style programming to the scientific, engineering and high performance computing communities.

As a developer what I can expect from F#?

F# is a programming language that provides the much sought-after combination of type safety, performance and scripting, with all the advantages of running on a high-quality, well-supported modern runtime system. F# gives you a combination of

Read more about F# at Microsoft Research

Wednesday, October 17, 2007

Unknown, Yet Powerful Keywords of C#

As a C# developer you would have learned many keywords which you might have used many times. But there are few keywords which are known to very few developers and rarely used by them. I would like to tell you about few such keywords which i came across few days ago.

stackalloc: The keyword stackalloc is used to dynamically allocate memory in the stack. Memory allocated using stackalloc keyword provides very quick access and the memory is released as soon the enclosing function exits.

int * fPtr = stackalloc int[100];

volatile: The keyword volatile is used to declare variables which are accessed and modified by multiple threads. When a variable is declared as volatile, compiler does not subject the code associated with the variable for optimizations that assume access by a single thread.

private volatile int sIntanceCounter;

default: Default keyword is used to assign the default value to a generic paramter when we dont know the type of the generic parameter.

public T GetNext()
{
//T is a generic type
T temp = default(T);
.....
// Generic code;
return temp;
}

Friday, October 05, 2007

Microsoft Opens .NET Framework Code To All The Developers

Microsoft announced that they will open access to source code of Microsoft.NET framework 3.5 base class libraries to all the developers. Developers can download and browse the source code by accepting  Microsoft Reference License agreement.

It is been also announced that the source contains comments(wow..no need to break head to understand a complex logic) and integration with Visual Studio 2008 debugger is very easy. Visual Studio 2008 will support the ability to configure the debugger to dynamically download the Microsoft.NET Framework code from the web server hosted by Microsoft and developers can step through the code while debugging.

It is a great news to all the Microsoft.NET developers as everyone get access to the source code which allows them to

  • Understand the design patterns used to develop base classes
  • Reuse the patterns and best practices of Framework to implement new modules
  • Look deep in to the skin of Microsoft framework to understand how it works
  • Implement deeper debugger integration for the problem associated with framework usage

The list of .NET Framework library for which source code will be available to download

  • System, System.IO
  • System.Collections
  • System.Configuration
  • System.Threading
  • System.Net
  • System.Security
  • System.Runtime
  • System.Text, etc)
  • System.Web
  • System.Windows.Forms
  • System.Data
  • System.Xml
  • System.Windows

C#.NET - Do you think StringBuilder is always the best way to Concatenate Strings? I don't think so!

Almost all the Microsoft C#.NET developers would have been told many times to use StringBuilder to concatenate strings. It is true that using StringBuilder improves performance of string concatenation operations. But it is not always true. There are few situations where StringBuilder perform slower than normal string concatenation operator +.

 

While concatenating 1 – 4 strings dynamically it is preferred to use string concatenation operator

Yes. while concatenating small number(1 to 4) of strings it is preferred to use string concatenation operator instead of StringBuilder.

This sample StringBuilder code took 2098 milliseconds to run on my PC

// Concatenate 3 strings using StringBuilder
for (int nCounter = 0; nCounter <= 9000000; nCounter++)
{            
  StringBuilder sbBuffer = new StringBuilder();
  sbBuffer.Append(nCounter.ToString());
  sbBuffer.Append(nCounter.ToString());
  sbBuffer.Append(nCounter.ToString());
}


The following sample code using + operator took slightly less amount of time 2001 milliseconds




// Concatenate 3 strings using + operator
for (int nCounter = 0; nCounter <= 9000000; nCounter++)
{
    string sBuffer = nCounter.ToString();
    sBuffer = nCounter + nCounter.ToString();
    sBuffer = nCounter + nCounter.ToString();
}


 


While building a string with known literals use + operator instead of StringBuilder


When we need to build to SQL statement or Java Script in C# code we need to concatenate many lines of SQL/Java Script code. While building strings with known literals it is preferred to use + instead of StringBuilder




// Build SQL script block
string sSQLBlock = "SELECT name, "
              + "age, dateofbirth "
              + "FROM Student WITH(NOLOCK)"
              + "WHERE name like 'A%'";

alternately you can even use @ operator




// Build SQL script block
string sSQLBlock = @"SELECT name, 
                    age, dateofbirth 
                     FROM Student WITH(NOLOCK)
                     WHERE name like 'A%'";

Tuesday, October 02, 2007

C# - Where did the name come from?

James Kovacs share his memory lane on how Microsoft C# got the name. It is interesting to know that C# name was inspired by music!. He says...

C# name was musically inspired. It is a C-style language that is a step above C/C++, where sharp (#) means a semi-tone above the note. (Being a musician myself, I think this is awfully fun.) Back when .NET made its debut, an amusing quip from the Linux crowd was to refer to C# as Db (D-flat), which is the same note as C#, but has different connotations. Two MS Research languages also bear musically-related names: Polyphonic C# and F#.

It's nice to read through his entire post where he explains about when .NET framework was started and code names of .NET framework and other components. Read the full article here

Who is James Kovacs?

James Kovacs is an independent architect, developer, trainer, and jack-of-all-trades, specializing in the .NET Framework, security, and enterprise application development. Read more about him...

Wednesday, December 20, 2006

Using SQL Server 2005 Exception Message box in your C# Application


SQL Workbench of SQL Server 2005 has a beautiful user interface. An interesting dialog for most of the developers in that user interface is Exception Message box.When ever an error occurs SQL Work bench shows that error with full information about the exception and a sample dialog box is shown below



If wish to use the same messagebox to show exceptions raised in your .NET application then you are lucky. Microsoft has exposed the message box class ExceptionMessageBox in the dll Microsoft.ExceptionMessageBox. The following is the sample code to demonstrate use of the exception message box

private void Form1_Load(object sender, EventArgs e)
{
try
{
int a, b, c;

//Set values
a = 10;
b = 0;
//Raise error
c = a / b;
}
catch (Exception exp)
{
ExceptionMessageBox objMsgBox;

objMsgBox = new ExceptionMessageBox(exp);
objMsgBox.Show(this);
}
}