Serving Information Simply

Wednesday, 13 March 2013

Reflection in C#


It is a powerful  way of collecting and manipulate information present in
Application’s assemblies and its metadata. Metadata contain all the Type
Information used by the application.

What is Reflection?

Reflection is the ability to find out information about objects, the
application details (assemblies), its metadata at run-time.

How to use Reflection in our applications?

Namespace :- System.Reflection
The Type class Base for all reflection.

Classes:-

Assembly Class: Assembly Class can be used to get the information and
Manipulate the assembly.

Module Class: Module Class is used for the reflection of the module.
This class is used to get information about parent assembly, classes in the module, all the global methods available in the classes.

ConstructorInfo Class:It is used for the reflection of a constructor, and used to fetch the information about constructor also constructor can be invoked.
Constructor information like name, parameters, access modifiers, and various implementation details (such as abstract or virtual) can be obtained.

MethodInfo Class : It is used to obtain information such as the name, return type, parameters, access modifiers (such as public or private), and implementation details  (such as abstract or virtual) of a any method inside the class, module,  assembly. GetMethods or GetMethod method of a Type are used to on the to obtain the information.

fieldInfo Class
EventInfo Class
PropertyInfo Class
ParameterInfo Class

eg:-private void Form1_Load(object sender, EventArgs e)
        {
            int i = 42;

            System.Type type = i.GetType();
            MessageBox.Show(type.ToString());
            MethodInfo[] t= type.GetMethods();
            MessageBox.Show(t[0].ToString()); 
 
  Assembly x=Assembly.LoadFrom(@"C:\Documents and Settings\abhinav\My Documents\Visual Studio
2008\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\WindowsFormsApplication1.exe");

  MessageBox.Show(x.FullName);
  MessageBox.Show(x.CodeBase);
   MessageBox.Show(x.EntryPoint.Name.ToString());
    MessageBox.Show(x.FullName.ToString());

  Type[] t = x.GetTypes();
   foreach (Type y in t)
          {
              MessageBox.Show(y.ToString());
          }
        Module[] p = x.GetModules();
          foreach (Module z in p)
          {
   MessageBox.Show(z.ToString());
          }

          Type gt = typeof(System.String);
          // Constructors.
          ConstructorInfo[] t9 = gt.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
          foreach (MemberInfo memberInformationDetails in t9)
          {
              MessageBox.Show(memberInformationDetails.ToString());
          } 
        }

================

WindowsFormsApplication1.Form1 x = new WindowsFormsApplication1.Form1();
            Type t=x.GetType();
            MessageBox.Show(t.Assembly.FullName.ToString());
            MessageBox.Show(t.BaseType.Name.ToString());
            MethodInfo[] y=t.GetMethods();
            foreach (MethodInfo MI in y)
            {
                MessageBox.Show(MI.ToString());  
            }
            ConstructorInfo[] p1 = t.GetConstructors();
            foreach (ConstructorInfo CI in p1)
            {
                MessageBox.Show(ppp.ToString());
            }
---------------------------------------------------------------------------------------
 Thank you guys... keep visiting ….:)
If you like this post then please join this site and like it’s Facebook page for getting updates.

Saturday, 2 March 2013

SQL Server Connection Strings In ASP.NET Web Applications for different data providers.


A connection string provides the information that a provider needs to communicate with a particular database. The Connection String includes parameters such as the name of the driver, Server name and Database name , as well as security information such as user name and password.

An ADO.NET Data Provider is a class that can communicate with a specific type of database or data store. Usually Data Providers use a connection string containing a collection of parameters to establish the connection with the database through applications. The .NET Framework provides mainly three data providers, they are

  Microsoft SQL Server
  OLEDB
  ODBC

Here you can see how to make a connection string to the following ADO.NET Data Providers.

with ms-ACCESS 2007

using System.Data.OleDb; 
//2.
    OleDbConnection x; //Create connection
    OleDbCommand y; //to run sql command
    OleDbDataReader z; //To hold data
    private void button1_Click(object sender, EventArgs e)
        {
            //3
            x = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=d:\\database1.accdb");
            x.Open();
            //4   
       y = new OleDbCommand("select * from emp", x);
   //5
      z = y.ExecuteReader();
            //6
            while (z.Read())
            {
                //MessageBox.Show(z["empno"].ToString() + " " + z["ename"].ToString() + " " + z["sal"].ToString());    
                MessageBox.Show(z[0].ToString() + " " + z[1].ToString() + " " + z[2].ToString());    
            }
            //7
            x.Close();
      }

ACCESS --2003

   x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=d:\\database1.mdb");

How to connect with Excel:-

  OleDbConnection x;
  OleDbCommand y;
  OleDbDataReader z;
        private void button1_Click(object sender, EventArgs e)
        {
            x = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=c:\\Book1.xlsx;extended properties=excel 12.0");
            x.Open();

            y = new OleDbCommand("select * from [sheet1$]", x);
            z = y.ExecuteReader();
            while (z.Read())
            {
      MessageBox.Show(z[0].ToString() + " " + z[1].ToString() + " " +     z[2].ToString());    
            }
            x.Close();
        }  
        
How to connect with Oracle

        OleDbConnection x;
        OleDbCommand y;
        OleDbDataReader z;
        private void button1_Click(object sender, EventArgs e)
        {
            x = new OleDbConnection("provider=msdaora;user id=scott;password=tiger");
            x.Open();

            y = new OleDbCommand("select * from emp", x);
            z = y.ExecuteReader();
            while (z.Read())
            {
 
                MessageBox.Show(z[0].ToString() + " " + z[1].ToString() + " " + z[2].ToString());    
            }
            x.Close();
        }

how to make connectvitiy with oracle using Oracleclient:-

..Add reference :- system.data.oracleclient

using System.Data.OracleClient;

        OracleConnection x;
        OracleCommand y;
        OracleDataReader z;
        private void button1_Click(object sender, EventArgs e)
        {
            x = new OracleConnection("user id=scott;password=tiger");
            x.Open();

            y = new OracleCommand("select * from emp", x);
            z = y.ExecuteReader();
            while (z.Read())
            {

                MessageBox.Show(z[0].ToString() + " " + z[1].ToString() + " " + z[2].ToString());
            }
            x.Close();
        }
-----------------------------------------------------------------------------------------

Thank you guys... keep visiting ….:)
If you like this post then please join this site and like it’s Facebook page for getting daily updates..   

Tuesday, 19 February 2013

Showing Uploaded image in grid view in C#.net


In my last article I had explained about how to upload image and audio file in asp.net using C# image and audio file uploading.

In this article I will let you know about how to show uploaded images in grid view control and also I will explain about how to use file upload control in this grid view row editing. For example if a Website user uploaded image save that image in the server path and display in grid view with use image control, after that editing that image using file upload control in grid view edit item template.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> Showing Uploaded image in grid view </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table width="1000" align="center">
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblText" runat="server" Text=""></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    Select File to be upload
                </td>
                <td>
                    <asp:FileUpload ID="fuImage" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    Description of the file
                </td>
                <td>
                    <asp:TextBox ID="txtDesc" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center" class="style1">
                    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick=" btnUpload _Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2" height="250" align="center">
                    <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" AutoGenerateColumns="false"  OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
                        <Columns>
                            <asp:TemplateField HeaderText="File Name">
                                <ItemTemplate>
                                    <asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("fpath")%>' />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:FileUpload ID="FileUpload2" runat="server" />
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Description">
                                <ItemTemplate>
                                    <%#Eval("desc1")%>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtdesc" runat="server" Text='<%#Eval("desc1")%>'></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:CommandField HeaderText="Modify" ShowEditButton="true" EditText="Edit">
                                <ControlStyle Width="50" />
                            </asp:CommandField>
                            <asp:TemplateField HeaderText="Delete">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkDelete" CommandName="Delete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this record?');">Delete</asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Server side Coding

Note: - Here you will use your own connection string name that you have mentioned into web config file.if you do not know how to declare connection string in web.config then go through  my last article image and audio file uploading.

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Abhinav"].ConnectionString);
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    String fname, fpath, desc;
    String spath;
    protected void Page_Load(object sender, EventArgs e)
    {
        lblText.Text = "";
        if (!Page.IsPostBack)
        {
            LoadGrid();
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fuImage.HasFile)
        {
            //Check File is available in Fileupload control and then upload to server path
            fname = FuImage.FileName;
            spath = @"~\Uploaded\" + FuImage.FileName;
            fpath = Server.MapPath("Uploaded");
            fpath = fpath + @"\" + FuImage.FileName;
            desc = TxtDesc.Text;
            if (System.IO.File.Exists(fpath))
            {
                LblText.Text = "File Name already exists!";
                return;
            }
            else
            {
                FuImage.SaveAs(fpath);
            }
            //Store details in the SQL Server table
            StoreDetails();
            TxtDesc.Text = "";
            LoadGrid();
        }
        else
        {
            LblText.Text = "Please select file!";
        }
    }
    void StoreDetails()
    {
        String Insertquery;
        Insertquery = "insert into fileDet(fname,fpath,desc1) values('" + fname + "','" + spath + "','" + desc + "')";
        sqlcon.Open();
        sqlcmd = new SqlCommand(Insertquery, sqlcon);
        sqlcmd.CommandType = CommandType.Text;
        sqlcmd.ExecuteNonQuery();
        sqlcon.Close();
        LoadGrid();
    }
    void LoadGrid()
    {
        sqlcon.Open();
        sqlcmd = new SqlCommand("select * from fileDet", sqlcon);
        da = new SqlDataAdapter(sqlcmd);
        dt.Clear();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        else
        {
            GridView1.DataBind();
        }
        sqlcon.Close();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        LoadGrid();
    }
  protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        LoadGrid();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        String ID;
        ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
        sqlcmd = new SqlCommand("select * from fileDet where ID='" + ID + "'", sqlcon);
        sqlcon.Open();
        da = new SqlDataAdapter(sqlcmd);
        da.Fill(dt);

        if (dt.Rows.Count > 0)
        {
            if (System.IO.File.Exists(Server.MapPath(dt.Rows[0][2].ToString())))
            {
                System.IO.File.Delete(Server.MapPath(dt.Rows[0][2].ToString()));
            }
        }
        sqlcmd = new SqlCommand("delete from fileDet where ID='" + ID + "'", sqlcon);
        sqlcmd.ExecuteNonQuery();
        sqlcon.Close();
        LoadGrid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.RowIndex];
        string ID;

        ID = GridView1.DataKeys[e.RowIndex].Value.ToString();

        FileUpload flname = (FileUpload)row.FindControl("FileUpload2");

        if (flname.HasFile)
        {

            fname = flname.FileName;
            spath = @"~\Uploaded\" + flname.FileName;
            fpath = Server.MapPath("Uploaded");
            fpath = fpath + @"\" + flname.FileName;
            if (System.IO.File.Exists(fpath))
            {
                LblText.Text = "File Name already exists!";
                return;
            }
            else
            {
                flname.SaveAs(fpath);
            }
        }
        else
        {
            LblText.Text = "Please select file!";
        }

        TextBox desc1 = (TextBox)row.FindControl("txtdesc");
        string query;
        query = "update fileDet set fname='" + fname + "',fpath='" + spath + "',desc1='" + desc1.Text + "' where ID='" + ID + "'";
        sqlcon.Open();
        sqlcmd = new SqlCommand(query, sqlcon);
        sqlcmd.CommandType = CommandType.Text;
        sqlcmd.ExecuteNonQuery();
        sqlcon.Close();
        GridView1.EditIndex = -1;
        LoadGrid();
    }
}

Then Implement the code and See the output...Thanks ...Keep Visiting ...:)
If you like this article then Join this Site.