Wednesday, April 9, 2014

Why and when should I make a class 'static'? What is the purpose of 'static' keyword on classes? With real time example

What is a static class?

It is a class which cannot be inherited and its members can be accessed directly without instantiating it.

There are two features of a static class, one is we can not create an instance of static class and second is a static class must contain only static members, Then what is the benefit to create a static class, the benefit of making static class, we do not need to make any instance of this class ,all members can be accessible with its own name.
Is it enough to clear your question? I think No!!
Because the same answer you will get from anywhere and we are still not able to clear what is static class.
Real time answer:
Assume we are working payroll project which provides all the employee details related to salary and leaves etc, Also have an admin who can check the details of all employee. It’s a big project and has lots of modules like:

Ø  Employee Details
Ø  Employee Salary Details
Ø  Employee Attendance Details
Ø  Admin module

In such kind of project apart from having many functions/properties and classes, you may need to have calculator to calculate the  the employee salary, Example- you may need the average salary , To create that calculator class you can use static class that would not be related to any other object of your other modules. We use these classes to invoke the functions with parameters or without parameters and then they return the output only, do not relate to other object of your projects.

Hope this will help.


Tuesday, April 8, 2014

A procedure to filter data on multiple conditions with several parameters.

This proc takes 6 parameters, all parameters allow for null values, it will returns the result whether you pass null or any parameter.

  • If you pass one parameter and rest of null then it will filter on single parameter.
  • If you pass 2 parameters and rest of null then it will filter result on 2 parameters.
  • If you pass all parameters then it will filter result on all parameters.
  • If you do not pass any parameter then It will returns all the records from the table.



create  proc [dbo].[usp_GetData]
@name varchar(100)= NULL ,
@sector varchar(50)= NULL ,
@pocket varchar(50) =NULL ,
@plot varchar(50)= NULL  ,
@locality varchar(50) =NULL,
@department varchar(50) =null
as

 Select * from m_Details where
 ((v_RegName like '%'+@name+'%' or @name is  null) and (v_Department=@department or @department is  null))
 and ((n_sector =@sector or @sector is null) and (v_Department=@department or @department is  null))
 AND ((v_pocket=@pocket or @pocket is null) and (v_Department=@department or @department is  null))
 AND ((n_plotNo=@plot or @plot is  null) and (v_Department=@department or @department is  null))
 AND ((v_locality =@locality or @locality is null) and (v_Department=@department or @department is  null))

Monday, April 7, 2014

How to Select, insert, update and delete data in LINQ?

Simply Open your web project go to solution explorer right click on your project add new Item and select Linq to Sql Classes and click add.

Notice that DataClasses1.dbml class has been added to your project, Click on this class.
Now, Open Server Explorer and expend your database and drag a table on DataClasses1.dbml.

Sql Table:

create table m_EduDetails
(
course_id int identity(1,1) primary key,
Degree nvarchar(50) not null,
Descrption nvarchar(255),
modified_date date

)

Now follow up this design and c# code.


<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Button ID="btnselect" runat="server" onclick="btnselect_Click"
            Text="Select" />
        <asp:Button ID="btnInsert" runat="server" onclick="btnInsert_Click"
            Text="Insert" />
        <asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
            Text="Update" />
        <asp:Button ID="btnDelete" runat="server" Text="Delete" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
   
    </div>
    </form>
</body>

 protected void btnselect_Click(object sender, EventArgs e)
        {
            DataClasses1DataContext db = new DataClasses1DataContext();
            var details = from p in db.m_EduDetails
                          select p;

            GridView1.DataSource=details;
            GridView1.DataBind();
        }


  protected void btnInsert_Click(object sender, EventArgs e)
        {
            DataClasses1DataContext db = new DataClasses1DataContext();
         
            m_EduDetails obj = new m_EduDetails();
            obj.course_id = 1;
            obj.Degree="btech";
            obj.Description= "4 year degree";
            obj.modifiedDate = DateTime.Now;
            db.m_EduDetailss.InsertOnSubmit(obj);
            db.SubmitChanges();


        }


 protected void btnUpdate_Click(object sender, EventArgs e)
        {
            DataClasses1DataContext OdContext = new DataClasses1DataContext();
         
            m_EduDetails objD = OdContext.m_EduDetailss.Single(m_EduDetails=> m_EduDetails.course_id == 1);
         
            objD.Description= "Update description";
         
            OdContext.SubmitChanges();

        }


protected void btnDelete_Click(object sender, EventArgs e)
        {
            DataClasses1DataContext OdContext = new DataClasses1DataContext();
         
            m_EduDetails objD = OdContext.m_EduDetailss.Single(m_EduDetails=> m_EduDetails.course_id == 1);
            OdContext .m_EduDetailss.DeleteOnSubmit(objD);
         
            OdContext.SubmitChanges();

        }


Saturday, April 5, 2014

Generic in c#

Generics are introduced in C# 2.0. Basically generics allow you to write a class or method that can work on any data type. Generic classes are extensively used by collection classes available in System.Collections.Generic namespace

Example. 

Class program
{
static void Swap<T> (ref T lhs, ref T rhs)
{
//code here
}
Main()
{
swap<int>(ref a, ref b); // Note- you can declare the type when you create instance or call the method
}
}

Create table with primary key in sql server.


CREATE TABLE Customer
(
Id INT NOT NULL PRIMARY KEY, -- id column with primary key
FirstName VARCHAR(100),
LastName VARCHAR(100),
City VARCHAR(50)
)

How to download a file from physical drive in asp.net?

void getexcel()
{
        try
        {
            Context.Response.Buffer = false;
            FileStream file = null;
            byte[] mybuff = new byte[1024];
            long count;
//Specify the drive letter where your files are saved and append the file name according your requirement 
            file = File.OpenRead("L:\\" + Session["dept"].ToString() + "\\" + Session["FileName"].ToString());
            if (file != null)
            {
                while ((count = file.Read(mybuff, 0, mybuff.Length)) > 0)
                {
                    Response.ContentType = "application/pdf";
                    Response.BinaryWrite(mybuff);
                }
            }
            else
            {
                Response.Write("File not found.");
            }
        }
        catch (Exception ex)
        {
            lblmsg.Text = ex.Message;
        }
}

How to import data from Excel to SQL SERVER by code?

  void ImporttoDatatable()
    {
        try
        {
            if (FlUploadcsv.HasFile)
            {
                string FileName = FlUploadcsv.FileName;

                string ext = Path.GetExtension(FlUploadcsv.FileName).ToLower();
                int filesize = FlUploadcsv.PostedFile.ContentLength;

                if (ext == ".xls" || ext == ".xlsx")
                {
                    if (filesize < 52428800)
                    {
                     

                            string path = string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
                           FlUploadcsv.PostedFile.SaveAs(path);
                            OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");

                            OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
                            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command);
                            OleDbcon.Open();
                            // Create DbDataReader to Data Worksheet
                            DbDataReader dr = command.ExecuteReader();

                            // Bulk Copy to SQL Server
                            using (SqlBulkCopy bulkInsert = new SqlBulkCopy(constr))
                            {
                                bulkInsert.DestinationTableName = "m_Details";
                             
                                bulkInsert.WriteToServer(dr);
                                lblmsg1.Text = "Data updated successfully.";
                                dr.Close();
                                bulkInsert.Close();
                                OleDbcon.Close();
                             
                             
                             
                             
                            }
                     
                    }
                    else
                    {
                        lblmsg1.Text="File size cannot be greater than 2 MB";
                    }
                }
                else
                {
                    lblmsg1.Text = "Please select a Excel file only.";
                }
            }
            else
            {
                lblmsg1.Text = "Please select a file";
            }
             
            }
     
        catch (Exception ex)
        {
            lblmsg1.Text = ex.Message;
       
        }
    }