TechBubbles

Calculating the size of the File in C#

Introduction

This code snippet explains how to calculate the size of the file and display in a label control. For example I am taking PDF file to find the size. It Displays the size of the file in Bytes, Kilobytes and Megabytes.

 

//Calculate size of the PDF file
       if (PdfFilePath.EndsWith("pdf"))
       {
           FileInfo info = new FileInfo(PdfFilePath);
           long fileSize = info.Length;
           string strFileSize = FormatFileSize(fileSize);
           lblFileSize.Text = strFileSize;
        }

Read more

3 comments

Lambda Expressions in C# 3.0

Lambda expressions is one of the features introduced in the C# 3.0. Lambda expressions help you to ease the burden of writing verbose Anonymous Methods.

I will explain the where to use the Anonymous methods first then we see the example on lambda expressions

Anonymous Methods

Anonymous Methods is the feature in C# 2.0. The idea behind writing the anonymous methods is to write methods inline to the code with out declaring a formal named method. Normally they used for small methods that don’t require any reuse.

Example:

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find(IsKalyan);

   }

   public static bool IsKalyan(string name)

  {

      return name.Equals(“Kalyan”);

  }

}

You can declare a anonymous method as follows

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find(delegate (string name )

                                            {

                                                return name.Equals(“Kalyan”);

                                             }   );

   }

}

Advantage: It saves some typing and puts the method closer to where it is being used which helps with maintenance

Lambda Expressions

Lambda Expressions makes the thing even more easier by allowing you to write avoid anonymous method and statement block.

class TestProgram

{

   static void Main( string[] args )

   {

      List<string> names = new List<string>();

      names.Add(“Kalyan”);

      names.Add(“Suresh”);

      names.Add(“Naveen”);

      string strResult = names.Find( name => name.Equals(“Kalyan”));

}

We can also effectively use the Lambda Expressions with LINQ and i will explain the feature in forth coming articles.

No comments

Extension Methods Feature in C# 3.0

It is one of the new feature introduced in C# 3.0 “As the name implies, extension methods extend existing .NET types with new methods.”

Here i am going to extend the String type to write an extension method.

Example Adding a IsValidEmailAddress method onto an instance of string class:

namespace Extensions

{

class TestProgram

{

     static  void  Main(string[] args)

     {

          string strEmployeeEmail  = “kalyan@techbubbles.com”;

          if (strEmployeeEmail.IsValidEmail() ) // IsValidEmail is extension method

{

 //Do something 

           }

     }

}

 

public static class Extensions

{

   public static bool

     IsValidEmail( this string s )

     {

       // Do something 

       return;

     }

}// this key word in front of the parameter makes this an extension method

}

The extension methods should be static methods in a static class with in same  namespace as shown above. The this keyword in front of the parameter makes an extension method.

2 comments

Object and Collection Initializers Feature in C# 3.0

C# 3.0 introduced the another interesting feature Object and Collection initialization expressions.

Object Intialization  Expressions allows you to initialize an object without invoking the constructor and setting its properties.

If you take Employee Class as an Example:

public class Employee {
private int iEmpId;
private string strFirstName;
private string strLastName;

public int ID{
get{
return iEmpId;
}
}

public string FirstName {
get {
return strFirstName;
}
set {
strFirstName= value;
}
}

public string LastName {
get {
return strLastName;
}
set {
strLastName = value;
}
}

 public Employee() {}
}

We can use Object Intialization Expressions in C#3.0 Features  to create a Employee as follows:

Employee objEmployee  = new Employee {ID=007, FirstName = “Kalyan” LastName = “Bandarupalli” }

Now observe the above code we have neither  invoked the constructor nor set the any properties directly. The code above is equivalent to the following code:

 

Employee objEmployee = new Employee();

objEmployee.ID = 007;

objEmployee.FirstName = “Kalyan”;

objEmployee.LastName = “Bandarupalli”;

We can use Collection Intialization Expressions in C#3.0 Features  to create a list of Employees as follows:

 

List<Employee> listofEmployees  = new List<Employee>

{  {objEmployee.ID = 007,  objEmployee.FirstName = "Kalyan”},

     {objEmployee.ID = 007,  objEmployee.FirstName = "Suresh”},

    {objEmployee.ID = 007,  objEmployee.FirstName = "Naveen”}

  };

The advantage of using this feature is that it saves your time for creating a lot of constructors or initializing the individual property.                    

2 comments

Automatically Implemented Properties Feature in C# 3.0

Introduction of Automatic Properties in C# 3.0 make property declaration more concise. It saves some of your time in typing a lot of code.

Example:

class Employee
{
public string FirstName { get; set; }
}

Benefit of using Automatic Properties

We have been creating properties in so many projects and notice that we are writing so many lines of code just for creating a simple property.

Example: Employee class that does not use Automatic Properties

public class Employee {
private int iEmpId;
private string strFirstName;
private string strLastName;

public int ID{
get{
return iEmpId;
}
}

public string FirstName {
get {
return strFirstName;
}
set {
strFirstName= value;
}
}

public string LastName {
get {
return strLastName;
}
set {
strLastName = value;
}
}
}

In order to create a simple property, we are coding extra four or five lines code. So, if we have 100 properties in different entity classes, we have to  type too much of code just for creating properties.

If you convert above Employee class with Automatic properties it look like

class Employee
{
public int ID{ get; private set; } // read-only
public string FirstName { get; set; }
public int LastName { get; set; }
}

Note: This is my first article to explain the C# 3.0 tutorial series. 

Conclusion

It is one of C# 3.0 Language feature and nothing new except it helps you to improve your productivity.

2 comments

Test driven development using C#

This post explains how TDD can be implemented in C# using NUNIT.

You can read the Introduction TDD to get an idea on TDD.

Nunit is a open source framework to for .NET which helps you to automate the unit testing. Nunit can downloaded from the Nunit site. current version is 2.5.

Nunit provides two utilities for running the automated tests

  • nunit-gui.exe – GUI tool
  • nunit-console.exe – Command line tool

Using Nunit in Visual studio .NET Project

To implement the TDD we need to write

  1. Test cases
  2. program that is having test cases to run against it

Behavior of the Person C# class that we are going to write test cases

The Behavior can be described as follows

  • A Person has properties age,full name and cash balance.
  • When instantiating a person we should able to provide a first name, last name and age.
  • The person full name property should return first name and last name with a space in-between.
  • When you are creating person object cash balance should be 20000.
  • The cash balance should be reduced by the amount he with draws.

From the Above behavior we can formulate a number of test cases example

  • If we create a person with first and last name of “Kalyan” and “Bandarupalli” , and age 27, the person’s full name should not be ” Kalyan Hero”.
  • The person full name should be “Kalyan Bandarupalli”.
  • The person’s age should be 27.
  • Before withdrawing money the person’s cash balance should be 20000.
  • After withdrawing 10000 cash, the person’s cash balance should be 10000.

We can implement the above test case in code[C#] using Nunit. To create a test case in your application create a class having the [TextFixture] attribute.

This class will contain test to test the methods,operations and values in    Person   class.

Read more

No comments

Factory method Designpattern using C#

The factory method pattern is a creational design pattern used in software development to encapsulate the process of creating the objects.

Concerns:

  • Which object needs to be created.
  • Managing the life time of the object.
  • Managing the build-up and tear down concerns of the object.

Definition:

“Define an interface for creating an object, but let subclasses decide which class to instantiate”

 

C# Implementation of Factory method

            abstract class Factory
              {
              public abstract Product GetProduct(); //Factory Method Declaration
              }

——————————————————————————————-        

           class concreteFactoryforProcuct1 : Factory
              {
              public override Product GetProduct() //Factory Method Implementation
                       {
                           return new Product1();
                       }
               }

——————————————————————————————–           

           class concreteFactoryforProcuct2 : Factory
              {
              public override Product GetProduct() //Factory Method Implementation
                     {
                          return new Product2();
                     }
              }

——————————————————————————————–

            interface Product
                {
                 void GetDetails();
                }

              class Product1 : Product
               {
                public void GetDetails()
                {
                  Console.WriteLine("Product1 Details are Called");
                }
               }
              class Product2 : Product
              {
                public void GetDetails()
                {
                 Console.WriteLine("Product2 Details are called");
                }
              }

——————————————————————————————–

        protected void Page_Load(object sender, EventArgs e)
        {

            Factory[] objFactories = new Factory[2];
            objFactories[0] = new concreteFactoryforProcuct1();
            objFactories[1] = new concreteFactoryforProcuct2();
            foreach (Factory objFactory in objFactories)
            {
                Product objProduct = objFactory.GetProduct();
                objProduct.GetDetails();
            }
        }

——————————————————————————————–

4 comments

C# 3.0 features

The following features are introduced in the C# 3.0

Visual studio C# 2008

1. Lambda Expressions.

2. Extension Methods.

3. LINQ Query Expressions.

4. Anonymous Types.

5. Expression Trees.

6. Partial Methods.

7. Auto-Implemented Properties.

8. Object and Collection Intializers.

1 comment

C# 2.0 features

The following features are introduced in the C# 2.0

[Visual studio C# 2005 ]

1. Generics.

2. Anonymous Methods.

3. Iterators.

4. Partial Types.

5. Nullable Types.

6. Delegate Inference.

7. Covariance  and  Contravariance.

8. Friend  Assemblies.

9. #  Pragma  warning.

10. Captured Variables.

No comments