Sunday, July 10, 2016

How to create an instance of class dynamically and invoke method?

Normally we create instance of class using new keyword followed by class name. In below example new instance of “TestClass” is created using new keyword.

TestClass test = new TestClass();

But if you want to create an instance of class dynamically from assembly, how you can do it? You can do it using reflection by calling Activator.CreateInstance method. Activator class is part of System namespace. See below example how Activator.CreateInstance method used to create an instance of type.

namespace TestLibrary
{
    public class TestFile
    {
        public void DisplayFileName(string fileName)
        {
            Console.WriteLine("File Name :- {0}", fileName);
        }
    }
}




"TestLibrary" class library project added to console application and created above mentioned "TestFile" class and added reference of "TestLibrary" project to console application.  See below code from console application to dynamically create an instance of "TestFile" class and invoke "DisplayFileName" method.

Code -
public class Program
{
    static void Main(string[] args)
    {
        //Loads Assembly
        Assembly assembly = Assembly.Load("TestLibrary");
        //Gets type which object you wants to create
        Type t = assembly.GetType("TestLibrary.TestFile");
        //creates an instance of given type
        object obj = Activator.CreateInstance(t);
        //parameters for method
        object[] parameters = new object[] {"Binary File"};
        //Invokes method of class
        t.InvokeMember("DisplayFileName", BindingFlags.InvokeMethod, null, obj, parameters);

        Console.ReadLine();
    }
}


Output - 









In above example, an instance of “TestFile” class (of different assembly) is created and invoked “DisplayFileName” method dynamically.

First you need to load “TestLibrary” assembly using Assembly.Load method. You need to add reference of “TestLibrary” assembly in your application. If you want to load other assembly which is not referenced in your project, then you can use Assembly.LoadFile method to load external assembly. After successfully loading assembly, you need to load class using Assembly.Gettype instance method and create instance of that class using Activator.CreateInstance method. Once you get an instance of “TestFile” class, you can invoke “DisplayFileName” method via type InvokeMemeber method. The whole process is done dynamically via Reflection.

After reading this article, I hope you have more understating about how you can create an instance of class and invoke method dynamically via reflection. Please leave your feedback in comments below.

References –

See Also –

Wednesday, July 6, 2016

How to set default value to auto properties in C#?

There are many ways to initialize properties with default value. The most common way to set default value of any property is to set its local variable with default value. See below example.

Code –
public partial class DefaultValueProperties : Window
{
    private int age = 25;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public DefaultValueProperties()
    {
        InitializeComponent();

        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }

}

Output –
Age - 25

But when you are using auto-properties you don’t need to declare local variable for it since it’s internally taken care by CLR. So how to set default value to auto-properties? There is a way, you can set default value to auto-property using DefaultValue attribute. DefaultValue attribute is part of System.ComponentModel namespace. See below example.

Code –
public partial class DefaultValueProperties : Window
{
    //DefaultValue Attribute to set Default Value of Age property
    [DefaultValue(35)]
    public int Age { get; set; }

    //Constructor
    public DefaultValueProperties()
    {
        InitializeComponent();

        //This method sets value for all the properties reading from DefaultValue attribute
        InitializeDefaultProperties(this);
           
        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }

    public static void InitializeDefaultProperties(object obj)
    {
        foreach (PropertyInfo prop in obj.GetType().GetProperties())
        {
            foreach (Attribute attr in prop.GetCustomAttributes(true))
            {
                if (attr is DefaultValueAttribute)
                    prop.SetValue(obj, ((DefaultValueAttribute)attr).Value, null);
            }
        }
    }
}

Output –
Age - 35

As you can see in above example, Age property is decorated with DefaultValue attribute. DefaultValue attribute will not automatically set Property value. You need to manually set its value in constructor using refection. The good part of initializing value of property using Default Value is more consistent with design and less error prone. Since this approach involves reflection, this is not very efficient way to set default value to properties.

With C# 6.0, you can set default value to auto-properties even more better and easiest way. See below code.

Code - 
public partial class DefaultValueProperties : Window
{
    public int Age { get; set; } = 30;

    //Constructor
    public DefaultValueProperties()
    {
        InitializeComponent();

        Console.WriteLine(string.Format("Age - {0}", Age));
        Console.ReadLine();
    }
}

Output –
Age - 30


Hope you liked this article. Your feedback/comments are most welcome. Happy reading. J


References –

See Also –


Saturday, July 2, 2016

Adapter Pattern


Adapter pattern enables application to use classes or interfaces which are not matching its requirement. Adapter pattern falls under structural pattern of GOF (Gang of Four) pattern.

When to use –


Adapter pattern can be used when you want to utilize third party API which is not compatible or mismatching your current implementation. You want to use third party API in your application but your application doesn’t understand the object of third party API in such scenarios, you need to use Adapter pattern to create wrapper class which contains code to utilize third party API. You can also consider to use adapter pattern when you have an existing system and you want to use some features of new application but interfaces are different.

There are so many real world example of adapter pattern but most common is power adapter. India’s power socket and plug is different from America’s power socket and plug. To use any Indian electronic appliances in America, you need an adapter (universal power adapter) which allows India’s plug to fit in America’s power socket. In .net world SQLAdapter, OracleAdapter are good example of adapter pattern.

Major components of Adapter pattern –

  • ITarget – This is an interface which client wants to use to achieve its functionality.
  • Adapter – This class implement ITarget interface and responsible for providing functionality that client wants and communicates with Adaptee class.
  • Adaptee – This class has actual functionality that client wants but its interface is not compatible with client.
  • Client – This class want to achieve functionality that Adaptee class has but via ITarget interface due to incompatible interfaces.

Let’s have a look on below code demonstrating adapter pattern.

Code –

public enum TransactionType
{
    Cash,
    NetBanking,
    CreditCard
}
//ITarget - Target interface
public interface IPayment
{
    void PayAmount(TransactionType type, double amount);
}
//Adapter class - integrates with Adaptee
public class PaymentGatewayAdapter : IPayment
{
    public void PayAmount(TransactionType type, double amount)
    {
        PayPalPaymentGateway payPalGateway = new PayPalPaymentGateway();
        switch (type)
        {
            case TransactionType.Cash:
                payPalGateway.PayCash(amount);
                break;
            case TransactionType.NetBanking:
                payPalGateway.PayViaNetBanking(amount);
                break;
            case TransactionType.CreditCard:
                payPalGateway.PayViaCard(amount);
                break;
            default:
                break;
        }
    }
}

//Adaptee – Third party API
public class PayPalPaymentGateway
{
    public void PayCash(double amount)
    {
        Console.WriteLine("Cash payment successful for amount {0}", amount);
    }
    public void PayViaCard(double amount)
    {
        Console.WriteLine("Card payment successful for amount {0}", amount);
    }
    public void PayViaNetBanking(double amount)
    {
        Console.WriteLine("Net Banking payment successful for amount {0}", amount);
    }
}

//Client
class Program
{
    static void Main(string[] args)
    {
        IPayment paymentGateway = new PaymentGatewayAdapter();
        paymentGateway.PayAmount(TransactionType.NetBanking, 2000);
        Console.ReadLine();
    }
}

Output –



As you can see in above example, PaypalPaymentGateway class is third party API which can directly be used by client to make payments but application has some different implementation and client doesn't want to change it and which is not matching with Third party API. In above example, third party API has different methods for different types of payments. PaymentGatewayAdapter class has adopted third party API differences and returned functionality that client wanted. This example is very simple but actual implementation of Adapter class may be more complex than this based on third party API object and client requirement.

In above example, if PayPal payment gateway renames its ‘PayCash’ method or any other method then client doesn’t need to change anything only change in Adapter class. Similarly, if you decide to use some other payment gateway instead of PayPal you don’t need to change client side implementation just change in Adapter class to integrate with new payment gateway interface.

I hope this article helps you to understand more about Adapter Pattern. Please leave your feedback in comments below.

References –

See Also –



Thursday, June 16, 2016

Data Caching in a WPF


In this article I will explain how you can cache object in memory in WPF application to get better performance.

Cached data will be stored in memory so you will get faster access to that data compare to accessing it from File or Database. So whenever you need to make frequent calls to some database or file, better you cache that data and read from cached object this will improve your application performance via reducing multiple calls to database or file.

Caching mechanism provided by .Net framework 4.0. Caching is available under System.Runtime.Caching namespace and you need to add this namespace in your project references.  

See below example, where multiple calls are being made to database for getting employee details based on employee name.

XAML - 
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="50" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock Text="Name of employee - " HorizontalAlignment="Center"
               VerticalAlignment="Center"
                Grid.Row="0" Grid.Column="0" />
    <TextBox Name="EmpName" VerticalContentAlignment="Center"
             Text="{Binding Path=EmployeeName, Mode=TwoWay}"
                Height="30" Width="150" HorizontalAlignment="Center"
                VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" />
    <Button Name="Search" Content="Search" Click="Search_Click"
            Grid.Row="0" Grid.Column="2" Height="30" Width="150" />
    <ListBox Height="200" Width="200" Name="EmployeeList"
                ItemsSource="{Binding}" Grid.Row="1" Grid.Column="0"
                Grid.ColumnSpan="3" />
</Grid>

Code –
public partial class MainWindow : Window
{
    ObservableCollection<string> Employees = new ObservableCollection<string>();
    public MainWindow()
    {
        InitializeComponent();
    }
    //Search Button event handler
    private void Search_Click(object sender, RoutedEventArgs e)
    {
        Employees = GetEmployeesByName(EmpName.Text);
        this.DataContext = Employees;
    }
    //Make calls to database to get employee details based on given name
    private ObservableCollection<string> GetEmployeesByName(string name)
    {
        ObservableCollection<string> employeeNames = new ObservableCollection<string>();
        string connectionString = "Data Source=MITESH-PC\\SQLEXPRESS;Initial Catalog=TestSQLDB;Integrated Security=SSPI";
        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            string cmd = "select firstname + ' ' + lastname as [EmployeeName] from HR.Employees where firstname like @FirstName";
            SqlCommand command = new SqlCommand(cmd, sqlConnection);
            command.Parameters.Add(new SqlParameter("@FirstName", name));
            sqlConnection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    employeeNames.Add(reader["EmployeeName"].ToString());
                }
            }
            sqlConnection.Close();
        }
        return employeeNames;
    }
}


Output – 



In above example, for each employee search is costing database call. To avoid database call for each employee, we can cache all employee name at once and for each subsequent search we can get it from cached object. This will reduce database call every time we search on employee and increase performance. See below code which implements caching.

Code –
public partial class MainWindow : Window
{
    ObservableCollection<string> Employees = new ObservableCollection<string>();
    //cache object
    ObjectCache cache = MemoryCache.Default;
    public MainWindow()
    {
        InitializeComponent();
        //Gets all employess from database
        Employees = GetAllEmployees();
        //sets employees in cache
        cache.Set("AllEmployees",Employees, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5) });
    }
    //Search Button event handler
    private void Search_Click(object sender, RoutedEventArgs e)
    {
        //Get employeelist from cached object
        ObservableCollection<string> employeeList =  cache["AllEmployees"] as ObservableCollection<string>;
        //if cache is expired or no object available in cache then set cache object again
        if (employeeList == null)
        {
            employeeList = GetAllEmployees();
            cache.Set("AllEmployees", Employees, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5) });
        }
        //search employee name from employee list loaded from cache object
        var selecteEmployees = (from emp in Employees
                                where emp.ToLower().Contains(EmpName.Text.ToLower())
                                select emp).ToList();
        this.DataContext = selecteEmployees;
    }
    //Gets all employess from database
    private ObservableCollection<string> GetAllEmployees()
    {
        ObservableCollection<string> employeeNames = new ObservableCollection<string>();
        string connectionString = "Data Source=MITESH-PC\\SQLEXPRESS;Initial Catalog=TestSQLDB;Integrated Security=SSPI";
        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            string cmd = "select firstname + ' ' + lastname as [EmployeeName] from HR.Employees";
            SqlCommand command = new SqlCommand(cmd, sqlConnection);
            sqlConnection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    employeeNames.Add(reader["EmployeeName"].ToString());
                }
            }
            sqlConnection.Close();
        }
        return employeeNames;
    }
}

Output – 


Output is same as above example, but in this example In-Memory caching is being used. In constructor, I loaded all the employees from database and added to the cache object. When every time user search for employee, search will be perform on in memory object and result will be returned. In this example cache expiry is set to 5 minutes but you can set as per your need. After every 5-minute cache object will get expired and employee list will be null. After cache expired, if you still need cached object then you need to load it again from database or file and add to cache again.

In memory caching is very beneficial and recommended for applications which are making multiple calls to database, file system or others. You can set cache expiry time if you want to delete or update or refresh cache object after certain time. Caching will improve performance and scalability of your application.

Hope this article helps you to understand how to cache data objects in WPF application. Please leave your feedback in comments below.


References –

See Also –