C#

C# Programming Tutorials, C# Help, C# Book Reviews, C# Tips

C# Custom Number Formatting


Very often the inbuilt numerical formatting in C# will be insufficent and you will want to apply the custom formatting for your numbers.

The String.Format method is very flexible and can be used to apply custom formatting rules. The # character informs the Format method how to format the numerical value, for example to forma the number 12000.12 as 12,000.12 use can use the format “#,#.##” as in the below code:

double dbl1 = 12000.12;string outputStr;outputStr = string.Format(“This is a custom formatting example {0:#,#.##} “, dbl1);Response.Write(outputStr);

In this example the , character is used to denote the thousand separator and the ## after the decimal place denotes that a maximum of 2 numbers should appear after the decimal place. Therefore the double 12000.1 would be formatted as 12,000.1, if you wish two decimals places always to be shown (ie 12,100.10 in this case) you should use the ’0′ character after the decimal place:

outputStr = string.Format(“This is a custom formatting example {0:#,#.00} “, 12000.1);

You can also add additional characters before and after the formatting string. Thus to format the value as $ 12,000.12 use the format string “$ #,#.##” , or even “#,#.## US Dollars” would output “12,000.12 US Dollars”.

The % character will multiply the value by 100 and then add % character to the end of the string. Thus for the double value 12 the format string “{0:0.00 %}” will output “1200.00 %”. Note that you can use the # character in place of the 0 character as per the formatting rules above and so “#,#.## %” in this case would output “1,200 %”.

View the original article here



Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 15, 2011 at 3:54 pm

Categories: C#   Tags: Custom, Formatting, Number

Measure Memory Usage of .NET Applications

There are primarily two main methods for measuring the memory usage of a .NET Framework application, using the GC class or using System.Diagnostics


The .NET Framework’s GC class contains many useful memory-related methods, including GetTotalMemory(), which returns the amount of memory the garbage collector believes is allocated to your app. The number not be exact right since some objects may not have been garbage collected yet. This, however does have the advantage of being able to inform you of the amount of memory a certain part of your app uses, as opposed to the entire process:


long memAvailable = GC.GetTotalMemory(false);


Console.WriteLine(“Before allocations: {0:N0}”,


memAvailable);


int allocSizeObj = 40000000;


byte[] bigArrayObj = new byte[allocSizeObj];


memAvailable= GC.GetTotalMemory(false);


Console.WriteLine(“After allocations: {0:N0}”, memAvailable);


The above code will output the following:

Before allocations: 651,064After allocations: 40,690,080

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 26, 2011 at 1:55 pm

Categories: C#   Tags: Applications, Measure, Memory, Usage

Passing Parameters in C#

Methods are one of the primary concepts in C#. You can pass parameters to C# methods. There are basically three primary methods of passing parameters to C# methods:

This is passing parameters with no modifying keywords :

void MyMethod(Student studentObj, int aNumber)
{

aNumber += 5;

studentObj.Name = “Jon”;

}

In the above example MyMethod takes two parameters – a Student object and an Integer. Note the difference between the passing a Value Type (such as an Integer) and a Reference Type (such as any class such as a ‘Student’ object in the above example). Any operations performed on a value type will no be reflected in the original variable whereas operations performed on a reference type are reflected in the original variable. For example, assuming calling the above MyMethod method note the below code (note the comment explanation at the end of the code block):

int myInt = 8;Student aStudent = new Student();aStudent.Name = “Mike”;MyMethod(aStudent, myInt);// myInt value is still 8 since it is a Value Type and immutable// aStudent.Name is now Jon since it is a Reference Type// and the variable aStudent just points to a Student object// on the Managed Heap which is then operated upon by the MyMethod(0 method.

By default all paramteres are passed by value – i.e. only the value of the variable is passed to method and the object itself is not passed. Thus operations within the method can only operate on the value of the parameter it receives and cannot make changes to the original variable (do note that this only applies to Value Types as noted above since Reference Types will have their state changes when they are passed to methods).

Alternatively, parameters can be passed by Reference using the ref keyword and their values will be changed by the method:

void MyMethod(ref int aNumber)
{

aNumber += 5;

}

protected void Page_Load(object sender, EventArgs e)
{

int myInt = 8; M

yMethod(ref myInt); //myInt is now 13

}
In the above code the aNumber parameter in MyMethod now has the ref keyword, note that the ref keyword is always required when calling the method. The integer which is passed to the method now has its value changed by the method.

The out keyword has a similar impact to the ref keyword as the parameters that are passed to it can have their values changed. The primary difference is that when using the out keyword the objects do not need to be initialized. In the above example of passing by reference there would be a compile-time error if the integer had simply been declared by not initialized with a value as below:

int myInt;

If the ref keyword was replaced with the out keyword this issue would be resolved:

void MyMethod(out int aNumber)

{

aNumber = 3;

aNumber += 5;

}

protected void Page_Load(object sender, EventArgs e)
{

int myInt; MyMethod(out myInt); //myInt is now 8

}

Note that the integer is now initialized with a value in the method body.

You might wonder what is the point of the out keyword. It can be very useful in situations where you want a method to perform several operations and return multiple values. In this circumstance you can simply declare multiple variables and pass them to void method to have their values assigned.

In this article, you have learned how to pass parameters in C# in various ways.

Read the original article

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 11, 2011 at 1:04 am

Categories: C#   Tags: Passing Parameters in C#

How to Format Numerical Data in C#

You will be required to make use of numerical data while programming with C#. This article examines how to format numerical data in C#.

C# ships with several inbuilt formatting specifies which can be used to quickly format a number, for example the ‘c’ specifier will format the number as a currency:

double dbl1 = 7777777.7777777;
outputStr = string.Format(“This is the currency format {0:c}”, dbl1);

This will output the numerical value as a currency based on the user’s current currency setting. In my case this will output:

This is the currency format $10,000,000.00

Note firstly that String.Format is a static method – ie you can not use it from an instance of a string object so the below code will generate a compile error:

string outputStr;outputStr.Format(“This is the currency format {0:c}”, dbl1);

You must always use it at the class level (ie String.Format)

Below are the inbuilt formatting specifiers:
c – Currency
d – Decimal
e – Exponential notation
f – Fixed point formatting
n – Numerical formatting (with commas)
x – Hexidecimal

The below code shows an implementation of the n formatting speficier:

double dbl1 = 7777777.7777777;

string outputStr;

outputStr = string.Format(“This is the numerical format {0:n}”, dbl1);

Response.Write(outputStr);

Note that there will be compile errors if you attempt to format a double using the decimal format. Also, note that hexidecimal expects an integer type.

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 9, 2011 at 7:16 pm

Categories: C#   Tags: Format Numerical Data in C#, Formatting, Numerical

Introducing C# Strings

Strings are the fundamental concept to be learned in every programming language. Working with strings is a very common task for most C# developers. The .NET Framework offers good variety of tools for working with strings, but care must be taken as there are several gotchas to trip up the beginner.

The first thing to note about strings in .NET is that they are Reference Types. Reference types are live on the managed heap in .NET and so they are managed by the .NET Garbage Collector and unlike Value types they are not automatically destroyed when they are out of scope.

Strings can be easily instantiated using the below syntax:

string s1;

Note that there is no default value for a string, thus you need to assign a value to the string before attempting to access it:

string s1;

Literal1.Text = s1; //Will give run-time error string

s2 = “”; //This is as close as you can get to assigning nothing to a string;

Literal1.Text = s2;

There are numerous inbuilt methods in the .NET framework for dealing with strings. Namely:

Note that strings are immutable and thus the original string can never be changed. Therefore if you need to alter the string you will need to re-assign it a new string value:

string s1 = “all lower case”;s1.ToUpper() ; //s1 is unchanged

Literal1.Text = s1; //outputs ‘all lower case’ since s1 is unchangedstring s2 = “all lower case”;s2 = s2.ToUpper() ; //s2 is now re-assigned the new uppercase stringLiteral2.Text = s2; //outputs ‘ALL LOWER CASE’

For more on string immutability see Strings are Immutable.

C# offers a convenient method for concatenating a string using ‘+’ :

string s1 = “New”;

string s2 = “Delhi”;

Literal1.Text = s1 + s2;

Whilst this method is convenient it is not efficient for performing a large number of concatenations (since strings are immutable and are refenece types created on the managed heap each concatenation results in the creation of an extra string which is not automatically destroyed and stays in memory until the Garbage Collector destroys it).

To get around this limitation the .NET Framework provides the StringBuilder class which can efficiently concatenate strings using its Append() method:

StringBuilder sb = new StringBuilder();

sb.Append(“New”);

sb.Append(“Delhi”);

Literal1.Text = sb.ToString();

This is by way of demonstration since there would not be any memory saving from concatentating two strings (in fact this can consume more memory since the StringBuilder consumes memory). In general concatenating more than four strings is normally when a StringBuilder should be used.

In common with other C-based languages, C# strings may contain escape characters which qualify how the string should be output.
Escape characters begin with a backslash followed by a specific character.

Below are listed the various escape characters and their output:

\’ Inserts a single quote
\” Inserts a double quote
\\ Inserts a backslash
\a Triggers a system alert
\n Inserts a new line (on Windows systems)
\r Inserts a carriage return
\t Inserts a horizontal tab

To preserve a string exactly as it is exactly as it was added simply add the @ character at the start of the string.

For example:

string outputStr = “This site is named \’C# Help\’ “;Response.Write(outputStr);

This outputs

This site is named ‘C# Help’

To output the string verbatim add the @ character at the start of the string.

string outputStr = @”This site is named \’C# Help\’ “;Response.Write(outputStr);

This outputs

This site is named \’C# Help\’

Note that this will also preserve white space:

string outputStr = @”This is a brokenup string”;

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 8, 2011 at 7:47 am

Categories: C#   Tags: c# strings, Strings

Retrieve a list of current processes running on system c#

Retrieve a list of current processes running on system c#
You can use the Process.GetProcesses static method to retrieve a list of current processes.
To retrieve a specific process by ID, call Process.GetProcessById. To retrieve a list of processes with a specific name, call Process.GetProcessesByName. To retrieve the current process, call Process.GetCurrentProcess.  read more

eggheadcafe.com C# .NET FAQs

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - November 22, 2010 at 11:52 pm

Categories: C#   Tags: current, list, processes, Retrieve, running, system

A Basic Tour To Dynamic Keyword

With the advent of C#4.0, we have a new friend… Dynamic.


It references objects which happens to or not to exist at runtime. Put in different term, it allows late binding.


Let us start with a very basic example


Example 1: Simple Addition

dynamic dynVar = 10;dynVar += 10;Console.WriteLine(dynVar);

Output is: 20


Example 2: Simple Concatenation

dynVar += ” Hello”;Console.WriteLine(dynVar);

Output is: 10 Hello


But consider this

var varVariable = 10;varVariable += ” Hello”;

This will yield a compile time error


Cannot implicitly convert type ‘string’ to ‘int’


However the below works

object obj = 10;obj += “Hello”;Console.WriteLine(obj);

Reason: It is a specific type inferred from context and does not change type like dynamic does


Example 3:


Consider the below

dynamic dynClass = new MyClass(){ IntProperty = 1 , StringProperty = “A string property” , , StringField = “A string filed” , , DecimalField = 10d};

And

var varClass = new MyClass(){ IntProperty = 1 , StringProperty = “A string property” , StringField = “A string filed” , DecimalField = 10d};

TestCase1 : Display Valid Property value

Console.WriteLine(dynClass.IntProperty); //Using dynamic objectConsole.WriteLine(varClass.IntProperty); //using var object

Worked with a charm with the output being 1 for each case.


TestCase2 : Display InValid Property value

Console.WriteLine(dynClass.InvalidProperty); //Using dynamic object

Compiled fine


Runtime Error: ‘DynamicExample.MyClass’ does not contain a definition for ‘InvalidProperty’

Console.WriteLine(varClass.InvalidProperty); //using var object

Complie time error DynamicExample.MyClass’ does not contain a definition for ‘InvalidProperty’ and no extension method ‘InvalidProperty’ accepting a first argument of type ‘DynamicExample.MyClass’ could be found (are you missing a using directive or an assembly reference?)


TestCase3 : Display Valid Function Call

Console.WriteLine(dynClass.ValidMethod()); //Using dynamic objectConsole.WriteLine(varClass.ValidMethod()); //using var object

As expected, worked fine with the output being Hello


TestCase4 : Display InValid Function Call

Console.WriteLine(dynClass.InvalidMethod()); //Using dynamic object

Runtime error ‘DynamicExample.MyClass’ does not contain a definition for ‘InvalidMethod’

Console.WriteLine(varClass.InvalidMethod()); //using var object

Compile time error as expected ‘DynamicExample.MyClass’ does not contain a definition for ‘InvalidMethod’ and no extension method ‘InvalidMethod’ accepting a first argument of type ‘DynamicExample.MyClass’ could be found (are you missing a using directive or an assembly reference?)


Example 4: Runtime invocation


Consider the below two cases


Case 1

//Case 1: Using reflection to invoke membervar type = typeof(DynamicExample.MyClass);var res1 = type.InvokeMember( “Add” , BindingFlags.InvokeMethod , null , Activator.CreateInstance(type) , new object[] { 10, 20 });Console.WriteLine(“Addition of two number using reflection= ” + res1);

Case 2

//Case 2: Using Dynamic to invoke member dynamic res2 = ((dynamic)Activator.CreateInstance(typeof(DynamicExample.MyClass))).Add(10, 20); Console.WriteLine(“Addition of two number using dynamic= ” + res2);

The output being same in both the cases.


Example 5: Calling Iron Python Function From C# 4.0


Here I will give a short demo as how to call a method written in IronPython 2.6 and making a dynamic invocation to the method from C# environment.


Step 1: Download the latest version of Iron Python from Code Plex


Step 2: Install the software.


Step 3: For this demo I am using “first.py” python file located inside the Tutorial Folder


The file has two methods


a) Add


b) Factorial.


For this demo purpose, let us only invoke the Add method that performs addition of two numbers being supplied as parameters to the method.


Step 4: I am using a console application for the demo purpose. The very first thing we need to do is to add the dlls as shown under


Step 5: The function invocation happens in just three steps as shown below


The very first line

var ironPythonRuntime = Python.CreateRuntime();

loads the Iron Python libraries along with the DLR code needed to execute the python script.


Second line

dynamic loadIPython = ironPythonRuntime.UseFile(“first.py”);

loads the python script into memory. The significance of the dynamic variable(loadIPython) here is being the fact that Python calls are resolve at runtime.


The last line i.e.

Console.WriteLine(string.Format(“Addition result from IronPython method for {0} and {1} is {2}”, 100,200, loadIPython.add(100, 200)) );

Is simply to invoke the Python method and to display the result.


Step 6: And here is the output


Example 6: Calling Iron Ruby Function From C# 4.0


Here I will give a short demo as how to call a method written in IronRuby 1.1 and making a dynamic invocation to the method from C# environment.


Step 1: Download the latest version of Iron Ruby from Code Plex


Step 2: Install the software.


Step 3: For this demo I am using add.rb Ruby file which has only one Add method that performs addition of two numbers being supplied as parameters to the method.


Step 4: I am using a console application for the demo purpose. The very first thing we need to do is to add the dlls as show below


Step 5: The function invocation happens in just three steps as shown below


The very first line

var ironRubyRuntime = Ruby.CreateRuntime();

loads the Iron Ruby libraries along with the DLR code needed to execute the python script.


Second line

dynamic loadIRuby = ironRubyRuntime.UseFile(@”add.rb”);

loads the Ruby script into memory. The significance of the dynamic variable(loadIRuby) here is being the fact that Ruby calls are resolve at runtime.


The last line i.e.

Console.WriteLine(string.Format(“Addition result from Iron Ruby method for {0} and {1} is {2}”, 100, 200, loadIRuby.add(100, 200)));

Is simply to invoke the Ruby method and to display the result.


Step 6: And here is the output

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

In this short tutorial we have seen how the dynamic keyword helps us in various situations. Having said that, there are some pitfalls of this keyword like runtime checking and henceforth breaks the hallmark of C#’s strong type checking. Hope this tutorial has shed some idea on how, where to use dynamic and also how to invoke IronPython and IronRuby methods from C# 4.0.


Comments on the topic are highly appreciated for the improvement of the topic.


Thanks for reading the article.


View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - October 29, 2010 at 2:59 am

Categories: C#   Tags: Basic, Dynamic, Keyword

Monitoring a MySQL Server Process

This article is an example of monitoring a process. It will look for a running process and can start and stop the process, too.

If you are using MySQL 5 as a database server, you already know that there are no icons that show whether the server is running or not. You can look at the task manager, but perhaps you want to shutdown the server because the development session is over and the server uses so much memory (about 50 MB). If you installed the server as a service, you can stop the service, but you must have administrator privileges. If MySQL is not run as a service, you can execute a program to start and stop the server and this article contains the code to easily do that.


To use this code, you need the MySQL server software that can be downloaded from www.mysql.com[^], but in reality, any software will do. This just an example.


The program works by monitoring the existence of a running process that you can check with the Windows Task Manager.


As shown in the figure, the MySQL server process is named mysqld.exe. To monitor the process, this code is executed periodically with a Timer event as follows:

private void timer1_Tick(object sender, EventArgs e){ Process[] server = Process.GetProcessesByName(“mysqld”); if (server.Length != 0) { bool stat = true; //check if current status same as previous. this prevent notification always shown if (serverStat != stat) { OnRaiseServerEvent(new serverEventArgs(true)); //raise server event serverStat = stat; } } else { bool stat = false ; //check if current status same as previous. this prevent notification always shown if (serverStat != stat) { OnRaiseServerEvent(new serverEventArgs(false)); //raise server event serverStat = stat; //update global status } }}

Starting the server is easy; just execute mysqld.exe and it’s done. Unfortunately you can’t simply stop the process to shutdown the server. Well, it could be done, but an internal error might occur inside the server. To stop the server, you should instead execute: mysqladmin.exe –user=root shutdown.


To start the server:

FileInfo fi = new FileInfo(appPath + “\\mysqld.exe”);if (fi.Exists) Process.Start(fi.FullName);else errorProvider1.SetError(txtPath, “this isn’t mysql installation directory”);

Similarly, to stop the server:

FileInfo fi = new FileInfo (appPath + “\\mysqladmin.exe”);if (fi.Exists) Process.Start(fi.FullName, “–user=root shutdown”);else errorProvider1.SetError(txtPath, “this isn’t mysql installation directory”);

This code is useful if you are running MySQL server. You can start and stop the server by clicking a button, rather than by typing from a command prompt. You can also click on a button installed in the system tray as shown in the following image. 


View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - October 26, 2010 at 8:32 pm

Categories: C#   Tags: Monitoring, mysql, Process, Server

WCF by Example – Introduction

This article is the first of a series that discusses how to design and develop a WPF client using WCF for communication and NHibernate for persistence purposes.


Designing enterprise applications requires a comprehensive set of skills. In small and medium projects allocation of time and resources could be not feasible to the extent that is in larger projects, it is at this time where a source for best practices and patterns can become very beneficial. There are plenty articles, books and other materials covering specific aspects but it is almost impossible to find a single place where all the technologies and patterns are used in conjunction providing a comprehensive discussion of the why and how.


The intention of these articles is to provide an example of how a full enterprise application is developed from the early stages to a full functional stage. The articles build on top of each other where new aspects are covered or/and existing functionality is enhanced as a result of aligning the architect to the business non-functional requirements.


It is assumed in the series that Agile practices are followed so the solution’s architect focuses in providing flexible mechanisms for RAD, DDD and TDD methodologies. One key aspect of the architect is the requirement to be able to deploy a full-functional client for business exploration purposes that requires a minimum infrastructure footprint; avoiding databases, deployment to IIS and so on. 


The architect requirements are as follow: 

Rich client using WPF   Client connects to server using WCF services   NHibernate is used for persistence purposes   Client application can be run against in-memory repositories (Exploration Client) Deployment of the exploration client must be kept simple   The application must be easily testable, tests can be run against in-memory or NHibernate repositories  

Other assumptions: 

We have full control over the client and server components We are creating the database from scratch, we are not using some legacy database We are deploying the server components using IIS7 and WAS; we will use TCP/IP We have full design control over the PK in the database tables, we will using unique long fields for all our entities in this project

We are going to start using a very simple business scenario in our series, the focus on the series is the architecture not the business domain. We may extend our domain in the future if we find that we want to explore some more complex architect concepts. 


The business domain is based in a simple list of contacts, it is currently so simple that one single entity is only required: Customer. The solution name is eDirectory. 


The source code can be found at codeplex: WCF by Example  


The latest version can be found at the trunk branch, each chapter is located at its own tag branch. You may want to use the browse function within Codeplex to navigate among the branches. 


The eDirectory application defines three well differentiated application components: the database, server and client. 



Within the client and server the application is structured into layers, in most cases the layers are stacked one beside each other, continuous layers are provided with decoupled mechanisms so different implementations can be used. Some services are available across multiple layers.


As we earlier mentioned, we have full control of the clients and server. So we will not relay on late service discovery, instead the service contracts are available at both sides of the application. This is also true for the DTOs and some common business validation. As a result, a Common assembly is defined that contains components shared by the server and client applications.  


In the server side we find the core components, the business domain declares the business entities and their behavior (action methods). Then services are declared that exposes our domain action methods. The services for persistence and serialisation constraints only expose DTOs between the client and server. As a result, the transformation of entities to DTOs needs to be addressed in a comprehensive manner.  

In order to decouple our business domain from the database, the repository components are responsible for the persistence of our entities. We will define a generic interface between these two layers. Two concrete implementations of the repositories are available: in-memory and NHibernate. 

The transaction manager is our “unit of work” implementation. It is responsible for our business transactions and the handling of business messages (warnings and exceptions).


Finally, but not the least, we have the client components. The client is a WPF application designed using the MVVM pattern. This pattern provides a neat view XAML component with none or very little code behind, the binding capabilities of XAML in conjunction with the ViewModel class leverages how the client renders the DTOs provided by the services layers.


The client decouples the service layers into two main components. The adapter is responsible for the managing of business messages retrieved during the execution of services. The WCF Proxy layer is responsible for the management of WCF services, the design is neat and is a nice way of decoupling the client from the WCF service.


View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - October 6, 2010 at 8:43 pm

Categories: C#   Tags: Example, Introduction

how to make GridView auto partial update like Gmail inbox


The way presented in this article is a way of how to add new rows from database to gridview without refresh of the page . This is useful when a client want to see new rows (eg. new letters) without having to refresh the page. If you wanna see a live demo, please logIn to your Gmail account(load standard Gmail), then send a letter from a different browser to your Gmail address and see that your Gmail Inbox will auto add the new letter’s row to your letters’ gridView

There are a quick way to show new rows : put GridView inside an updatePanel and refresh the updatePanel every 3(or any) seconds, but this way increase page source’s size and page’s load time…….


but , in this article we will learn a way to automatically get new rows automatically every 3(or any) seconds [by javascript timeout] from server[by jQuery get method] and then those new rows to gridView [by jQuery html manipulation]  


You should know :


jQuery html manipulation – you can learn from w3schools.com


jQuery and ajax – you can learn from w3schools.com


Suppose we wanna(want to) have a gridView with ability of auto adding new rows from database to it
we follow the following steps to have a gridView like Gmail Inbox perl gridView !


step 1 :
Add the following Javascript code to the page that contains your gridView


Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 30, 2010 at 8:24 pm

Categories: C#   Tags: gmail, gridview, inbox, partial, update

Next Page »