Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts

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 –

Sunday, October 14, 2012

How to get list of System Colors in WPF


You might aware about available System Colors in Windows machine. You might have changed system colors using below window. If you change color and appearance of any item (e.g. color, font, size, font color etc.) it will change appearance and color of all the application available in windows. In short you can change system’s default appearance and color using below dialog.


In this post I will demonstrate how you can get available list of system colors dynamically using WPF application. Let’s have a look on below example.

XAML
<Window x:Class="WpfApplication1.SysColors"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="System Colors" Height="300" Width="300">
<Grid>
<DataGrid Name="grdSysColorList"
          AutoGenerateColumns="False"
          GridLinesVisibility="Vertical">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Color"
                                Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Margin="5">
                        <TextBlock.Background>
                            <SolidColorBrush Color="{Binding Color}" />
                        </TextBlock.Background>
                    </TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Name"
                            Binding="{Binding Name}"
                            Width="200"/>
    </DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

Code
public partial class SysColors : Window
{
public SysColors()
{
    InitializeComponent();
    LoadSystemColors();
}
public void LoadSystemColors()
{
    List<SysColorItem> sysColorList = new List<SysColorItem>();
    Type t = typeof(System.Windows.SystemColors);
    PropertyInfo[] propInfo = t.GetProperties();
    foreach (PropertyInfo p in propInfo)
    {
        if (p.PropertyType == typeof(Color))
        {
            SysColorItem list = new SysColorItem();
            list.Color = (Color)p.GetValue(new Color(),
                BindingFlags.GetProperty, null, null, null);
            list.Name = p.Name;

            sysColorList.Add(list);
        }
        else if (p.PropertyType == typeof(SolidColorBrush))
        {
            SysColorItem list = new SysColorItem();
            list.Color = ((SolidColorBrush)p.GetValue(new SolidColorBrush(),
                BindingFlags.GetProperty, null, null, null)).Color;
            list.Name = p.Name;

            sysColorList.Add(list);
        }
    }
    grdSysColorList.ItemsSource = sysColorList;
}
}

public class SysColorItem
{
public string Name { get; set; }
public Color Color { get; set; }
}
}

Output


In above example you can see DataGrid having two columns Color and Name. Color displays various system colors and name displays its name. I have retrieved this system colors using Reflection. First I have retrieved type of SystemColors and then retrieved all the properties having Color and SolidColorBrush type. In last i have bind that list of SystemColors to DataGrid.


How to apply system colors to WPF controls

In above example we saw how we can retrieve list of system colors dynamically. Now let’s see how you can apply system colors to WPF control.

<Button Background="{x:Static SystemColors.MenuHighlightBrush}"
        Content="Click Me!!!"
        Height="40" Width="150"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">



Above code demonstrates how you can apply MenuHighlightBrush to Button’s background. Similarly you can apply other system colors as well. SystemColors has all the colors defined as Static property so we have used {x:Static} markup to retrieve system color.

As per above example, if your application running and MenuHighlightBrush color is changed in background then your application will not display newly changed color. If you want to do so you can use DynamicResource markup. DynamicResource will update resources dynamically whenever it changed while your application is running. Let’s have a look on below code snippet which used DynamicResource.

<Button Background="{DynamicResource {x:Static SystemColors.MenuHighlightBrushKey}}"
        Content="Click Me!!!"
        Height="40" Width="150"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">
</Button>

In above code I have used DynamicResource markup to display resources dynamically. If MenuHighlightBrushKey changed in background then your application will display newly changed value.

Here one thing to noticed that I have used resource key in second example while in first example I have used brush. The reason behind that is DynamicResource markup uses resource key.

Hope you liked this post. You can checkout below link to know more about System Colors in WPF.
http://blogs.msdn.com/b/wpf/archive/2010/11/30/systemcolors-reference.aspx

See also –