Showing posts with label dot net. Show all posts
Showing posts with label dot net. Show all posts

Generic Function to convert string to Enum

private T GetEnumFromString<T>(string value)
  {
     try
        {
           T t;
           t = (T)Enum.Parse(typeof(T), value);
           return t;
        }
     catch (Exception E)
        {
           return (T)((object)0);
        }
   }

Factory Design pattern

Factory design pattern provides you an interface creating a single object, but let subclass decide which class to instantiate. This pattern is used most frequently when we are having common functionality with different methods for different objects.

In that scenario, we will create an interface with defining common functionality which will be implemented by the classes. A class will be defined which will be used to identify which class to be instantiated for the object.

For example, We have to create reading utility and we are having 3 different kind of files 1st is pdf, 2nd is doc and 3rd is txt file. On all the files we have to perform open operation but way to open the file will be different. In this case we will create an Interface will contain OpenFile Operation. There will be classes for each file type and the classes will be implementing the factory interface(Example is given in C# Code Example.

C# Code Example:

"if" condition inside Select Clause of LINQ Query.

In LINQ you can't use "if" statement directly in select clause, but you can achieve this by using ternary operator.

Consider you are querying an Array of object & the object internally contains another object. We have to select some field from inner object. But it may be chance that for some cases inner object is null. So to prevent your query from throwing "Object Reference not set to instance of object exception.", you need to check for null object in select clause.

Code:

class Periods
        {
            public int StartYear;
            public int EndYear;
        }



class student
        {
            public int RollNo;
            public string name;
            public DateTime DOB;
            public Periods coursePeriod;
        }



//There is an array of student object which internally contains Periods object.

student[] arrStudents= new student[100];

// You have to fetch list of students and time period spend in college
//code to fill arrStudents Array.
//output object
class studentCousePeriod
        {
            public int Rollno;
            public int StartYear;
            public int EndYear;
        }

LINQ :

C# Null-Coalescing Operator (??)

C# has an operator called Null-Coalescing Operator(??), this operator takes two operands. If left hand side operand is not null then it returns left hand side operand else it returns right hand side operands. It is very effective to assign default value to a variable.

This variable can be used with reference type as well as nullable value types. A sample code for the use of this operator is written below:

ComboBox in WPF DataGrid's Column Header

Here, In this article, we are going to discuss, how can we add framework elements in WPF Datagrid's column header. We will add combo box in  the header. To add Combobox in the Header of DataGrid we use [GridColumn].Header tag. In the tag we can add any element directly.

<tools:DataGridTextColumn.Header>
     <ComboBox x:Name='txtCbo75P' ItemsSource='{StaticResource StringArrayResource}' SelectedIndex='0'></ComboBox>
</tools:DataGridTextColumn.Header>

Now suppose we have to create Grid as below:

In this case for the forth column rather than giving header text directly, we shall use above code

XAML

Create Nested headers in WPF DataGrid

In WPF many times we may require to render a data grid which contains multilevel headers, for example we  have columns FirstName, LastName, Address1, Address2, City, State. Now we have to render a grid in which we have these columns these columns will have group name above the column header. It means there will be another level of header above these. In our case FirstName and LastName will be under Name, and Address1, Address2, City and State Columns will be under the Address.

Sample snapshot is displayed below.


XAML:

WPF StringFormat example in Binding



In this small article we will see how we can use StringFormat when we use Binding.
In the example we have use one Date Picker and one TextBlock. The TextBlock isbound with the SelectedDate property of the DatePicker.And we have used StringFormat property to modify the text shown in TextBlock.

Sample Code:

Where Clause with LINQ to Hashtable / Dictionaries

In this article, we will discuss How can we use where clause in LINQ to Object(Hastable / Dictionaries). Many time  while working with the Dictionaries or Hashtables, we may require to find out the values from them which satisfies some specific criteria. In that case we used to write iterations and then find the values which satisfies the criteria. Maybe writing the loop is a easy task for the beginners, but writing code for checking the values and performing the operations are so boring and tedious task.For the checking the values   for specific criteria we need to declare intermediate variables etc. But by using LINQ, this can be done so easily with few lines of code even without using iterations.

LINQ: Join operations on Hashtables / Dictionaries

In this example we will discuss, how to perform Join operation on dictionaries / hash tables. 
Consider 2 Dictionaries, one dictionary contains Roll No (Int) as key and a Structure (marks) (which contains marks of student) as value. Another dictionary contains Roll No(Int) as key and Name of Student (String) as value. Now we have to find name of students and corresponding marks of the students. 

So in this case we will perform Join on the key of both dictionaries and will have enumerable collection of KeyValue pairs (key will be name of student and value will have marks details) in the query result.

     var QueryResult = from mrks in stuResult.AsEnumerable<KeyValuePair<int, marks>>()
                       join pd in stuPDetails.AsEnumerable<KeyValuePair<int, string>>()
                       on mrks.Key equals pd.Key
                       select new KeyValuePair<String, marks>(pd.Value, mrks.Value);

Above mentioned LINQ query will perform join operation on the key values of the dictionaries. Finally selects the new KeyValue pairs having String(Name of Student) as key, marks(Marks details of the student) as value.

Example of JOIN on Dictionaries

C# Sending Information / data from Child to Parent class using events and delgates

In the previous post C# Notify Parent From Child using events and delegates , we were just notifying the parent class about some processing happening in the child class.

 But we were not sending any information or data to parent class about what processing is happening in child class. We have taken the same example taken in C# Notify Parent From Child using events and delegates and modified a bit so that we can send information to parent about the processing happening in Child class.
Previously, in Parent we were getting information that some key is pressed in Child Class. Now we will send the information that which key is pressed in Child class.

We have modified the delegate to be method with parameters. Now the signature of the event handler will also change. Also we have defined a custom class "CustomEventArgs" which has one public property i.e Key, which has the information about the pressed key.

Now whenever Child class raises an event, it will create and instance of CustomEventArgs and send it to all the event listeners. So all the event listeners, in our case the Parent class, will get the information about which key is pressed.

Source Code:


Introduction to LINQ

Language INtegrated Query (LINQ) was introduced very 1st with the .Net framework 3.5. it bridges the gap between the world of objects and world of data.
LINQ extends the language by so called query expressions, which looks like a SQL Statement, by which we can extract and process data from array, Enumerable collection of classes, XML documents, MS SQL Tables, third party data sources etc.

List and Details of Query Operators/Keywords of LINQ

1. from: from keyword is used to mention the datasource on which the LINQ is applied..

2. where: The where operator/clause is similar to the where clause in the SQL. It is used to provide the conditions which is to be satisfied. 

3. select:  select operator is used to perform the projection on the collection to select the elements from the collection.

C# Notify Parent From Child using events and delegates

While creating an application, we often come across scenarios where we have parent child relationship between objects.

When we want to pass some information from parent to child, it is very simple as we have the reference of the child object in the parent and we pass the information using message passing technique, where we call some public method of child and achieve the desired result.

But many times while creating applications, we find some requirement where we need to notify the parent class that some processing has happened in child class. Based on that we need to do something in parent class. Notifying parent from child is not direct way as child do not hold reference of parent.
Note : We can always pass parent's reference to child but it is not the conventional way and can cause issues while maintaining the application. So this is not recommended.
So, we can achieve this using delegates. We can create and event in child using delegate. Parent will listen to this event. Whenever some processing happens in child, child can raise event and whoever is listening to this event will get notified that some processing has happened in child.

Sample Code:

events in C#

An event allows a class or resource to notify the other classes or resource, when something required event occurs. The resource that raises the events is knows as publisher and the resource that handles the event is known as subscriber. In C# visual application we handle events like button clicked, combo box selection changed events etc. Similarly, we can raise our custom events when requires.

Overview of events

  • Publisher determines when to raise event, and subscriber determines how to handle the event.
  • An event can have multiple subscribers, and subscriber can handle multiple events.
  • An event that has no subscriber is never raised.
  • Events are typically used for user actions.
  • When an event has multiple subscriber than event handlers are invoked synchronously.
  •  Events are actually based on the EventHandler delegates.

Example of Events

delegates in C#

A delegate is a type that references a method. Once a delegate is bound to a method, it behaves like method. It can be used like other methods.


public delegate void valueEntered(string value);

Any method that matches the delegate's signature including return type, parameters etc, can be assigned to the delegate.

delegate's Overview

  • It is like a function pointer in C++.
  • It allows methods to be passed as parameters
  • It can be used as callback method.
  • In this method's signature need not to be exactly same as delegate's.
                     For Example:
                                public class type1 { }
                    public class type2 : type1 { }
                    public delegate type1 delegateEx();
                    class Program
                       {
                          static void Main(string[] args)
                           {
                             delegateEx de = new delegateEx(MethodType1);
                             delegateEx de1 = new delegateEx(MethodType2);
                           }
                          public static type1 MethodType1() { return new type1(); }
                          public static type2 MethodType2() { return new type2(); }
                        }
                   
          type1 and type2 are 2 different classes but type2 inherits type1 so It is allowed in delegates.
  • C# 2.0 introduces concept of Anonymous method which allows programmer to pass code block as parameter in method.

delegate's Example

WPF How to use Resource Dictionary in C#



To know what is Resource Dictionary,example of Resource dictionary, how we can add Resource Dictionary and how we can use it from XAML visit here:

Now there may be a case where we need to access a resource dictionary that we have defined in our project, from C# code.
If we have already merged our resource dictionary in XAML, it is easy to access the inner resources using thecontrol.FindResource("<<ResourceKey>>"); method.
 But, if we haven’t merged the resources in XAML and we still need to use the resource dictionary, we have options to use it directly inC# code. 
We have modified the example given here WPF How to use Resource Dictionary in XAML. where we were using ResourceDictionary from XAML.
Below is the XAML and code snippet:
XAML Code:
<UserControl x:Class="WPF_Sample_Project_Test.ResourceDictionaryExample"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
        <Button x:Name="btnRound"  />
    </Grid> 
</UserControl>
C# Code:

WPF How to use Resource Dictionary in XAML



In this article, we will learn how we can use merge a resource dictionary in WPF XAML.


As we all know, that WPF applications supports rich media and graphics support, styles and templates should be managed in such a way that they can be reused. Styles can be defined in the same XAML file or all the styles and templates which are reusable across different screens can be accumulated in a Resource Dictionary File. 


What is Resource Dictionary?


In Resource Dictionary, one can write reusable styles, DataTemplates, ControlTemplates. One can also define custom definitions for Brush, Color, Background etc.

Each of these custom defined style or template is called as resource and a unique key must be given to each resource.


Steps to add Resource Dictionary

C# : How to read a text file


This is a very basic example where we explain how can we read text files from C#.
We will show three examples:

Example 1:
We will read all the text from a file and store it in a string variable.

For this we will be using C# inbuilt utility function: System.IO.File.ReadAllText

Method signature:
public static string ReadAllText(string path);


Example 2:
We will read all the text from a file line by line and then store each line as an element in a string array.
For this we will be using C# inbuilt utility function: System.IO.File.ReadAllLines

Method signature:
public static string[] ReadAllLines(string path);

We have developed a console application to showcase the feature.The source code for reading file is displayed below:

class Program
    {
        static void Main()
        {
           

            // Read the file as one string.
            string text = System.IO.File.ReadAllText(@"C:\Example1.txt");

            // Display the file contents to the console. Variable text is a string.
            System.Console.WriteLine("*****************EXAMPLE 1*********************");
            System.Console.WriteLine("Contents of Example1.txt = {0} \n \n", text);

Convert structure to bytes and writing it to a file

Many time we may require to write the data of structure in file in the form of bytes. So consider the structure written below:


[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
        struct student
        {
            [MarshalAs(UnmanagedType.LPWStr,SizeConst=10)]
            public string Name;
            [MarshalAs(UnmanagedType.I4)]
            public int RollNo;
            [MarshalAs(UnmanagedType.I4)]
            public int Marks;
        }

Many I am considering that you know How to convert structure into IntPtr (Click here to know how to convert Structure into IntPtr). So I will write that code directly in Example.

Consider ptrStudent, a IntPtr pointer which is pointing to the unmanaged memory which is containing structure in sequential layout.

Code for getting IntPtr of object of student

st: object of student

IntPtr ptrStudent = Marshal.AllocHGlobal(Marshal.SizeOf(st.GetType()));
Marshal.StructureToPtr(st, ptrStudent, true);

Now we have to get byte[] from IntPtr (ptrStudent).

Structure to IntPtr

Sometimes while working with the unmanaged resouces, we need to convert Marshal-able structure into unmanaged memory and gets its pointer and pass the structure's integer pointer(IntPtr) to unmanaged api.

[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
        struct student
        {
            [MarshalAs(UnmanagedType.LPWStr,SizeConst=10)]
            public string Name;
            [MarshalAs(UnmanagedType.I4)]
            public int RollNo;
            [MarshalAs(UnmanagedType.I4)]
            public int Marks;
        }

To convert structure to Integer pointer we need to use NameSpace: System.Runtime.InteropServices.

Consider the declaration of structure as

            student st = new student();             
            st.Name = "Akash Soni";             
            st.RollNo = 483;             
            st.Marks = 807;


Create object for IntPtr class and allocates memory from the unmanaged memory of specific bytes (which is equals to the size of structure


IntPtr ptrStudent = Marshal.AllocHGlobal(Marshal.SizeOf(st.GetType()));
Now create the unmanaged copy of Structure object 'st' in the unmanaged memory.
Marshal.StructureToPtr(st, ptrStudent, true);

Sample code


introduction to Unmanaged Structure in C#.

In dotnet we are working with managed resources as well as unmanaged resources. Surprisingly, use of unmanaged resources are much more than the managed resources. Memory management, garbage collectors are already available with the dotnet, so its not the problem for the developer. While working with the unmanaged apis we may require to access unmanaged memory by structures.

Suppose we have unmanaged binary developed in C++, which is containing a structure declared as below

typedef struct
{
  char[20]  Name;
  long RollNo;
  long Marks;
}student;

and there is a publicly exposed method which takes Integer pointer (IntPtr) as a parameter. In that case to store the returned value we need to create structures with special attributes StructLayout, which makes it of fixed length and Marshalable.
Unmanaged Structure in c# similar to above structure is as written below