C#


Create class runtime in C#

 static void Main() 
    { 
        TestExpression("2+1-(3*2)+8/2"); 
        TestExpression("1*2*3*4*5*6"); 
        TestExpression("Invalid expression"); 
    } 
    static void TestExpression(string expression) 
    { 
        try 
        { 
            int result = EvaluateExpression(expression); 
            Console.WriteLine("'" + expression + "' = " + result); 
        } 
        catch (Exception) 
        { 
            Console.WriteLine("Expression is invalid: '" + expression + "'"); 
        } 
    } 
    public static int EvaluateExpression(string expression) 
    { 
        string code = string.Format  // Note: Use "{{" to denote a single "{" 
        ( 
            "public static class Func{{ public static int func(){{ return {0};}}}}", 
            expression 
        ); 
        CompilerResults compilerResults = CompileScript(code); 
        if (compilerResults.Errors.HasErrors) 
        { 
            throw new InvalidOperationException("Expression has a syntax error."); 
        } 
        Assembly assembly = compilerResults.CompiledAssembly; 
        MethodInfo method = assembly.GetType("Func").GetMethod("func"); 
        return (int)method.Invoke(null, null); 
    } 
    public static CompilerResults CompileScript(string source) 
    { 
        CompilerParameters parms = new CompilerParameters(); 
        parms.GenerateExecutable = false
        parms.GenerateInMemory = true
        parms.IncludeDebugInformation = false
        CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp"); 
        return compiler.CompileAssemblyFromSource(parms, source); 
    } 

Custom Event Handling and Delegates :

Referance : Click here 
For More Visit : http://www.codeproject.com/Articles/12043/Using-Events-and-Delegates-in-C






  • Events and delegates are two concepts that very often work together. 
    When something happens on a windows form (like a click, dblclick, changin some text, selecting an item in a combobox, moving mouse, pressing a key and so on) an event is raised and if you have declared a delegate there is a function that is called to respond to that event. 

    For example you could want to advice the user that the name he inserted in the textbox is too long. 
    You add a delegate to the textBox1 objext like this: 

    this.textBox1.TextChanged += new System.EventHandler(this.HandleChanging); 


    then declare the HandleChanging method like this: 

    private void HandleChanging(object sender, System.EventArgs e) { 
            // method body here 
            } 

    The concept is: you do an action, an event is raised, and the delegate (if present) calls the proper function to operate on the object that raised the event. 

    Now, as you probably would know, every object like controls, forms, and so on, has some standard events. 
    You can add delegates on almost every object for mouse clicks for instance, or Control.Text property changin, making a list here would mean write 200 pages... 

    But what if you have just created a custom class (for instance a class that inherits from Control) and you want to add to this class a custom property, and also you want that when this property is changed, an event is raised and a delegate is called to launch the proper function to respond to the event? 

    I mean: I create my Car class and I put inside a tank property. 
    I want that when tank goes below 5 liters a Change event is raised and advice me that we're going out of fuel. 
    Let's do this! 

    Ok we need 3 classes: 
    - the Car class 
    - the CarArgs class (for the delegate) 
    - the Testing class 

    Let's begin with the CarArgs class: 
    Here's the code: 

    // custom attributes 
    public class CarArgs : System.EventArgs { 
             
        private string message; 

        public CarArgs(string m) { 
            this.message=m; 
        } 

        public string Message() { 
            return message; 
        } 
    } 

    This class will serve in the declaration of the function we need to call when the event is raised. 
    It's very simple, a message property, set in the constructor, and a Message() method to retrieve it. Note the inheritance from System.EventArgs. 

    Now the Car class; here's the code: 

    // custom object 
    public class Car { 
        private int tank; 

        // delegate declaration 
        public delegate void ChangingHandler (object sender, CarArgs ca); 

        // event declaration 
        public event ChangingHandler Change; 
             
        public Car(int n) { 
            this.tank=n; 
        } 

        public void SetTank(int p) { 
            this.tank=p; 
            // call the event 
            if (p<5) { 
                CarArgs ca=new CarArgs("Tank is below 5, tank value is : "+this.tank); 
                Change(this,ca); 
            } 
        } 

        public string GetTank() { 
            return this.tank.ToString(); 
        } 
    } 

    This is a little bit more difficult to read. 
    There is our tank property, then you can see the declaration of a custom delegate ChanginHandler. This is what we have to call when the Change event is raised. 
    The event declaration follows the delegate's one. Basically we tell the compiler that we want to apply that delegate to that event. 
    Notice the SetTank() method. If tank goes below 5 litres it raises the event. First it creates CarArgs and then it calls the event Change() passing a pointer to itself (the object) and the CarArgs just created. 

    The idea is this: I have created a buttom on a form and when I press it, a car object is being created and tested. 

    Here's the code: 

    private void button1_Click(object sender, System.EventArgs e) { 
            Car car=new Car(50); 
            car.Change+=new Car.ChangingHandler(car_Change); 
             
            // doesn't raise event 
            car.SetTank(40); 
             
            // doesn't raise event 
            car.SetTank(20); 
             
            // raise an event 
            car.SetTank(4); 
        } 

    private void car_Change(object sender, CarArgs ca) { 
            MessageBox.Show(ca.Message()); 
        }

    Very simple: Create the object, associate a delegate to the Change event, provoke the event (the third SetTank() call will provoke the event). You'll see a MessageBox showing and telling you that you're going out of fuel. Just to make sure you have understood let's resume a bit. 

    First you must create your custom EventArgs. Create a class that inherits from System.EventArgs and put there all the informations you need when the custom event is raised. Create an object, declare a delegate and an event inside the class and create a method that calls the event. In the testing application, add the delegate to the event, write a function to be called when the event is raised. 

  • ---------------------------------------------------------------------------------------------------------------------------

    How to make a C# class usable in a foreach statement :

    Use of IEnumerable and IEnumerator interface : 

    Referance : Click here

    IEnumerator interface

    The IEnumerator interface provides iterative capability for a collection that is internal to a class. IEnumerator requires that you implement three methods:
    • The MoveNext method, which increments the collection index by 1 and returns a bool that indicates whether the end of the collection has been reached.
    • The Reset method, which resets the collection index to its initial value of -1. This invalidates the enumerator.
    • The Current method, which returns the current object at [position].

     

      public bool MoveNext()
          {
             position++;
             return (position < carlist.Length);
          }
    
          public void Reset()
          {position = 0;}
    
          public object Current
          {
             get { return carlist[position];}
          }

     

    IEnumerable interface

    The IEnumerable interface provides support for the foreach iteration. IEnumerable requires that you implement theGetEnumerator method.

     public IEnumerator GetEnumerator()
          {
             return (IEnumerator)this;
          }

     

    When to use which interface

    Initially, you may find it confusing to use these interfaces. The IEnumerator interface provides iteration over a collection-type object in a class. The IEnumerable interface permits enumeration by using a foreach loop. However, the GetEmuneratormethod of the IEnumerable interface returns an IEnumerator interface. Therefore, to implement IEnumerable, you must also implement IEnumerator. If you do not implement IEnumerator, you cannot cast the return value from the GetEnumeratormethod of IEnumerable to the IEnumerator interface.

    In summary, the use of IEnumerable requires that the class implement IEnumerator. If you want to provide support forforeach, implement both interfaces.

    Step by step example

    The following example demonstrates how to use these interfaces. In this example, the IEnumerator and the IEnumerableinterfaces are used in a class named cars. The cars class has an internal array of car objects. Client applications can enumerate through this internal array by using a foreach construct because of the implementation of these two interfaces.
    1. Follow these steps to create a new Console Application project in Visual C#:
      1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
      2. On the File menu, point to New, and then click Project.
      3. Click Visual C# Projectsunder Project Types, and then click Console Application under Templates.

        Note In Visual Studio 2005, click Visual C# under Project Types.
      4. In the Name box, type ConsoleEnum.
    2. Rename Class1.cs to host.cs, and then replace the code in host.cs with the following code:

      using System;
      
      namespace ConsoleEnum
      {
        class host
        {
          [STAThread]
          static void Main(string[] args)
          {
            cars C = new cars();
            Console.WriteLine("\nInternal Collection (Unsorted - IEnumerable,Enumerator)\n");
            foreach(car c in C)
            Console.WriteLine(c.Make + "\t\t" + c.Year);
       
            Console.ReadLine();
          }
        }
      }
    3. On the Project menu, click Add Class, and then type car in the Name box.
    4. Replace the code in car.cs with the following code:

      using System;
      using System.Collections;
      namespace ConsoleEnum
      {
         
        public class car 
        {
          private int year;
          private string make;
              
          public car(string Make,int Year)
          {
            make=Make;
            year=Year;
          }
          public int Year
          {
            get  {return year;}
            set {year=value;}
          }
          public string Make
          {
            get {return make;}
            set {make=value;}
          }
        }//end class
      }//end namespace
    5. On the Project menu, click Add Class to add another class to the project, and then type cars in the Name box.
    6. Replace the code in cars.cs with the following code:

      using System;
      using System.Collections;
      namespace ConsoleEnum
      {
         public class cars : IEnumerator,IEnumerable
         {
            private car[] carlist;
            int position = -1;
      
            //Create internal array in constructor.
            public cars()
            {
               carlist= new car[6]
            {
               new car("Ford",1992),
               new car("Fiat",1988),
               new car("Buick",1932),
               new car("Ford",1932),
               new car("Dodge",1999),
               new car("Honda",1977)
            };
            }
      
            //IEnumerator and IEnumerable require these methods.
            public IEnumerator GetEnumerator()
            {
               return (IEnumerator)this;
            }
      
            //IEnumerator
            public bool MoveNext()
            {
               position++;
               return (position < carlist.Length);
            }
      
            //IEnumerable
            public void Reset()
            {position = 0;}
      
            //IEnumerable
            public object Current
            {
               get { return carlist[position];}
            }
         }      
      }
    7. Run the project. Notice that the following output appears in the Console window:
      Ford            1992
      Fiat            1988
      Buick           1932
      Ford            1932
      Dodge           1999
      Honda           1977

    Best practices

    The example in this article is kept as simple as possible to better explain the use of these interfaces. To make the code more robust and to make sure that the code uses the current best practice guidelines, modify the code as follows:
    • Implement IEnumerator in a nested class so that you can create multiple enumerators.
    • Provide exception handling for the Current method of IEnumerator. If the contents of the collection change, the reset method is called. As a result, the current enumerator is invalidated, and you receive an IndexOutOfRangeException exception. Other circumstances may also cause this exception. Therefore, implement a Try...Catch block to catch this exception and to raise an InvalidOperationException exception.

    using System;
    using System.Collections;
    namespace ConsoleEnum
    {
      public class cars : IEnumerable
      {
        private car[] carlist;
    
        //Create internal array in constructor.
        public cars()
        {
          carlist= new car[6]
        {
          new car("Ford",1992),
          new car("Fiat",1988),
          new car("Buick",1932),
          new car("Ford",1932),
          new car("Dodge",1999),
          new car("Honda",1977)
        };
        }
    
            //private enumerator class
            private class  MyEnumerator:IEnumerator
            {
              public car[] carlist;
              int position = -1;
    
            //constructor
            public MyEnumerator(car[] list)
            {
              carlist=list;
            }
            private IEnumerator getEnumerator()
            {
              return (IEnumerator)this;
            }
        
        
            //IEnumerator
            public bool MoveNext()
            {
              position++;
              return (position < carlist.Length);
            }
    
            //IEnumerator
            public void Reset()
            {position = -1;}
    
            //IEnumerator
            public object Current
            {
              get 
              { 
                try 
                {
                  return carlist[position];
                }
          
                catch (IndexOutOfRangeException)
                {
                  throw new InvalidOperationException();
                }
              }
            }
          }  //end nested class
        public IEnumerator GetEnumerator()
        {
          return new MyEnumerator(carlist);
        }
      }
    }


      Yield in C# :

       public static IEnumerable Table(int num,int count)
        {
            for (int a = 1; a <= count; a++)
            {
                yield return a * num;
            }
        }

       foreach(int i in Table(5,10))
            {
            //do needfull
            }

                                                        Generic :

    Reference : Click Here

     

    Generics in C# is a new innovative feature through which classes and methods in C# may be designed in such a way that the rules of a type are not followed until it is declared.Using generics, a class template may be declared that may follow any type as required at
    runtime. The class behavior is later governed by the type that we pass to the class. Once the type is passed, the class behaves depending on the type passed to this
    generic class.

    Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of run time casts or boxing operations
    ex.

    public class GenericList<T>
    {
        void Add(T input) { }
    }
    class TestGenericList
    {
        private class ExampleClass { }
        static void Main()
        {
            // Declare a list of type int
            GenericList<int> list1 = new GenericList<int>();

            // Declare a list of type string
            GenericList<string> list2 = new GenericList<string>();

            // Declare a list of type ExampleClass
            GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
        }
    }


    The most common use of generics is to create collection classes.
    The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.

    Ex.

    public class GenericList<T>
    {
        // The nested class is also generic on T
        private class Node
        {
            // T used in non-generic constructor
            public Node(T t)
            {
                next = null;
                data = t;
            }

            private Node next;
            public Node Next
            {
                get { return next; }
                set { next = value; }
            }
           
            // T as private member data type
            private T data;

            // T as return type of property
            public T Data 
            {
                get { return data; }
                set { data = value; }
            }
        }

        private Node head;
       
        // constructor
        public GenericList()
        {
            head = null;
        }

        // T as method parameter type:
        public void AddHead(T t)
        {
            Node n = new Node(t);
            n.Next = head;
            head = n;
        }

        public IEnumerator<T> GetEnumerator()
        {
            Node current = head;

            while (current != null)
            {
                yield return current.Data;
                current = current.Next;
            }
        }
    }


    class TestGenericList
    {
        static void Main()
        {
            // int is the type argument
            GenericList<int> list = new GenericList<int>();

            for (int x = 0; x < 10; x++)
            {
                list.AddHead(x);
            }

            foreach (int i in list)
            {
                System.Console.Write(i + " ");
            }
            System.Console.WriteLine("\nDone");
        }
    }

    Benefits :

    Generics provide the solution to a limitation in earlier versions of the common language runtime and the C# language in which generalization is accomplished by casting types to and from the universal base type Object. By creating a generic class, you can create a collection that is type-safe at compile-time.

    The limitations of using non-generic collection classes can be demonstrated by writing a short program that makes use of the ArrayList collection class from the .NET Framework base class library. ArrayList is a highly convenient collection class that can be used without modification to store any reference or value type.

    System.Collections.ArrayList list1 = new System.Collections.ArrayList();
    list1.Add(3);
    list1.Add(105);

    System.Collections.ArrayList list2 = new System.Collections.ArrayList();
    list2.Add("It is raining in Redmond.");
    list2.Add("It is snowing in the mountains.");

    But this convenience comes at a cost. Any reference or value type that is added to an ArrayList is implicitly upcast to Object. If the items are value types, they must be boxed when added to the list, and unboxed when they are retrieved. Both the casting and the boxing and unboxing operations degrade performance; the effect of boxing and unboxing can be quite significant in scenarios where you must iterate over large collections.

    The other limitation is lack of compile-time type checking; since an ArrayList casts everything to Object, there is no way at compile-time to prevent client code from doing something like this:

    System.Collections.ArrayList list = new System.Collections.ArrayList();
    // Add an integer to the list.
    list.Add(3);
    // Add a string to the list. This will compile, but may cause an error later.
    list.Add("It is raining in Redmond.");

    int t = 0;
    // This causes an InvalidCastException to be returned.
    foreach (int x in list)
    {
        t += x;
    }

    Generic Type Parameters:

    In a generic type or method definition, a type parameters is a placeholder for a specific type that a client specifies when they instantiate a variable of the generic type. A generic class, such as GenericList<T> , cannot be used as-is because it is not really a type; it is more like a blueprint for a type. To use GenericList<T>, client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. The type argument for this particular class can be any type recognized by the compiler. Any number of constructed type instances can be created, each one using a different type argument,

    Constraints on Type Parameters :

    When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code attempts to instantiate your class with a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified using the where contextual keyword.

    If you want to examine an item in a generic list to determine whether it is valid or to compare it to some other item, the compiler must have some guarantee that the operator or method it needs to call will be supported by any type argument that might be specified by client code. This guarantee is obtained by applying one or more constraints to your generic class definition. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called within the generic class

    Ex:

    public class Employee
    {
        private string name;
        private int id;

        public Employee(string s, int i)
        {
            name = s;
            id = i;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public int ID
        {
            get { return id; }
            set { id = value; }
        }
    }

    public class GenericList<T> where T : Employee
    {
        private class Node
        {
            private Node next;
            private T data;

            public Node(T t)
            {
                next = null;
                data = t;
            }

            public Node Next
            {
                get { return next; }
                set { next = value; }
            }

            public T Data
            {
                get { return data; }
                set { data = value; }
            }
        }

        private Node head;

        public GenericList() //constructor
        {
            head = null;
        }

        public void AddHead(T t)
        {
            Node n = new Node(t);
            n.Next = head;
            head = n;
        }

        public IEnumerator<T> GetEnumerator()
        {
            Node current = head;

            while (current != null)
            {
                yield return current.Data;
                current = current.Next;
            }
        }

        public T FindFirstOccurrence(string s)
        {
            Node current = head;
            T t = null;

            while (current != null)
            {
                //The constraint enables access to the Name property.
                if (current.Data.Name == s)
                {
                    t = current.Data;
                    break;
                }
                else
                {
                    current = current.Next;
                }
            }
            return t;
        }
    }


    Multiple constraints can be applied to the same type parameter, and the constraints themselves can be generic types, as follows:

    class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new()
    {
        // ...
    }

     

     

     

    Method To Create The PDF File From GridView In Asp.net


    protected void ExportToPDF(GridView gvuser, string fileName, bool isLastColVisible, bool isLogo)
            {
                if (gvuser == null)
                    return;
                if (string.IsNullOrEmpty(fileName))
                    fileName = "Bucco.pdf";
                gvuser = PrepareGridViewForExport(gvuser);
                Response.ContentType = "application/pdf";

                Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                HtmlForm frm = new HtmlForm();

                if (!isLastColVisible)
                    gvuser.Columns[gvuser.Columns.Count - 1].Visible = false;

                //gvuser.RowStyle.Height = 20;
                //gvuser.HeaderRow.Style.Add("height", "20px");
                gvuser.GridLines = GridLines.Vertical;
                gvuser.HeaderStyle.BackColor = System.Drawing.Color.Green;
                gvuser.HeaderRow.Style.Add("background", "green");
                gvuser.HeaderRow.Style.Add("font-size", "8px");
                gvuser.Style.Add("text-decoration", "none");
                gvuser.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
                gvuser.Style.Add("font-size", "6px");

                gvuser.Parent.Controls.Add(frm);
                frm.Attributes["runat"] = "server";
                frm.Controls.Add(gvuser);
                frm.RenderControl(hw);
                StringReader sr = new StringReader(sw.ToString());
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();


                if (isLogo)
                {
                    iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(Server.MapPath("~/App_Themes/buco/images/logo.jpg"));
                    pdfDoc.Add(gif);
                }
                pdfDoc.Add(new Paragraph(fileName.Substring(0, fileName.IndexOf('.'))));
                pdfDoc.Add(new Paragraph(" "));

                htmlparser.Parse(sr);
                pdfDoc.Close();
                Response.Write(pdfDoc);
                Response.End();
            }



    Create Generic List From Reader In ASP.net


    Here The Code By Using Which We Can Create a list from reader in C# ASP.net


     public List<T> SelectAll(string constr, string table, object val)
            {
                List<T> list = new List<T>();

                try
                {
                    SqlConnection conn = Tools.GetConnection(constr);
                    IDbCommand command = Tools.GetSelectCommand(table, conn, "id", val);
                    IDataReader reader = command.ExecuteReader();

                    list = Cbo.FillCollection<T>(reader);
                    constr.cloase();
                }
                catch (Exception)
                {

                    throw;
                }

                return list;
            }



     public static List<T> FillCollection<T>(IDataReader dr)
            {
                List<T> objFillCollection = new List<T>();
                T objFillObject;

                while (dr.Read())
                {
                    //  fill business object
                    objFillObject = CreateObject<T>(dr);
                    //  add to collection
                    objFillCollection.Add(objFillObject);
                }

                if (!(dr == null))
                {
                    dr.Close();
                }

                return objFillCollection;

            }



     private static T CreateObject<T>(IDataReader dr)
            {
                Type objType = null;

                T obj = Activator.CreateInstance<T>();

                List<PropertyInfo> properties = Helper.GetPropertyInfo(typeof(T));

                int i;
                for (i = 0; i < dr.FieldCount; i++)
                {
                    string columnName = dr.GetName(i);
                    //now find matching property
                    PropertyInfo propMatch = properties.Find(delegate(PropertyInfo p)
                    {
                        Type t = typeof(T);
                        PropertyInfo pi = t.GetProperty(p.Name);
                        Column[] atrb = pi.GetCustomAttributes(typeof(Column), false) as Column[];
                        if (atrb != null)
                        {
                            if (atrb.Length > 0)
                            {
                                foreach (Column at in atrb)
                                    if (at != null && !string.IsNullOrEmpty(at.Name))
                                    {
                                        return at.Name.ToLower() == columnName.ToLower();
                                    }
                            }
                        }
                       
                       
                        return p.Name.ToLower() == columnName.ToLower();
                       
                    });
                    if (propMatch != null)
                    {
                        //we have found a matching property. fill it in

                        if (Convert.IsDBNull(dr.GetValue(i)))
                        {
                            propMatch.SetValue(obj, Null.GetNull(propMatch), null);
                        }
                        else
                        {
                            try
                            {
                                //  try implicit conversion first
                                propMatch.SetValue(obj, dr.GetValue(i), null);
                            }
                            catch
                            {
                                try
                                {
                                    objType = propMatch.PropertyType;
                                    // need to handle enumeration conversions differently than other base types
                                    if (objType.BaseType.Equals(typeof(System.Enum)))
                                    {
                                        if (Helper.IsNumeric(dr.GetValue(i)))
                                        {
                                            propMatch.SetValue(obj, System.Enum.ToObject(objType, Convert.ToInt32(dr.GetValue(i))), null);
                                        }
                                        else
                                        {
                                            propMatch.SetValue(obj, System.Enum.ToObject(objType, dr.GetValue(i)), null);
                                        }
                                    }
                                    else
                                    {
                                        propMatch.SetValue(obj, Convert.ChangeType(dr.GetValue(i), objType), null);
                                    }
                                }
                                catch
                                {
                                    propMatch.SetValue(obj, Convert.ChangeType(dr.GetValue(i), objType), null);
                                }
                            }

                        }


                    }
                    else
                    {
                        Console.WriteLine("property not found {0}", typeof(T).Name);
                    }
                }

                return obj;
            }

    No comments:

    Post a Comment