Friday 5 February 2016

How to convert datatable to xml string in c# ?




Here I wrote a Method by which we can convert a DataTable into XML format. Method ConvertDatatableToXML Receive a parameter of Datatable type and after converting to XMl its return a string.


// By using this method we can convert datatable to xml
public string ConvertDatatableToXML(DataTable dt)
{
MemoryStream str = new MemoryStream();
dt.WriteXml(str, true);
str.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(str);
string xmlstr;
xmlstr = sr.ReadToEnd();
return (xmlstr);

}




Its a very frequently used function in c#. I hope its very useful to readers. Plaese comments your questions and feedback. thank you.

Wednesday 3 February 2016

What is reflection in C#? Give example


Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values and objects to the application.

Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties

Example 1:-

using System;
using System.Reflection;

namespace ConsoleDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Reflection.Assembly info = typeof(System.Int32).Assembly;

            System.Console.WriteLine(info);

            Console.ReadLine();
        }
    }

}


Output:-








Example -2

using System;
using System.Reflection;

namespace ConsoleDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {

            var t = typeof(MyClass);

            foreach (var m in t.GetMethods())
            {
                Console.WriteLine(m.Name);
            }
          

       // Or you can use MemberInfo  object to hold the object of typeof


       //System.Reflection.MemberInfo info = typeof(MyClass);
        // object[] attributes = info.GetCustomAttributes(true);
        // for (int i = 0; i < attributes.Length; i++)
        // {
        //    System.Console.WriteLine(attributes[i]);
        // }


            System.Reflection.Assembly info = typeof(System.Int32).Assembly;

            System.Console.WriteLine(info);

            Console.ReadLine();
        }
    }


    public class MyClass
    {
        public int Add(int x, int y)
        {
            return x + y;
        }

        public int Subtract(int x, int y)
        {
            return x - y;
        }
    }
}



Output:-