Showing posts with label C#. Show all posts
Showing posts with label C#. 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);
        }
   }

Deferred Execution in LINQ

Deferred Execution of Query

  class Sample
    {
      public int i;
      public String str;
    }

  static void Main(string[] args)
    {
      List lst = new List();
      lst.Add(new Sample() { i = 1, str = "String1" });
      lst.Add(new Sample() { i = 2, str = "String2" });
      lst.Add(new Sample() { i = 3, str = "String3" });
      lst.Add(new Sample() { i = 4, str = "String4" });
      int a = 1;
      IEnumerable lStr = (from l in lst
                          where l.i == a
                          select l);  //It will just store query in lStr variable.
     }

When we write any LINQ query as mentioned, it doesn't get executed immediately. It actually stores  query in the variable and every time we use/enumerate the variable it executes the query and use the result. It is called deferred execution.

    Sample s = lStr.First();  ///Query will be executed here
    Console.WriteLine(s.str);

So that whenever filter variable(a) changes prior to the use of object(lStr), output will automatically changes.

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:

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:

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

List of Frequently asked Interview Questions for C#.Net

1) What is .net framework?

2) What is abstract class?

3) What is Interface?

4) How does abstract class differ from Interface?

5) What is monitor object?

6) What will happen if any UI element is being updated by background thread in winform based multi-threaded application?

7) What are delegates?

8) Difference between DataReader and DataAdapter?

9) What is Garbage collector?

10) How does garbage collector work?

11) What is different between private and sealed class?

12) What is use of finally block?

13) How can you implement Singleton Design Pattern in C# code?