Monday, January 19, 2015

Gridview Custom Paging in ASP. Net Using Stored Procedure

In This article I am going to explain about how to Create Custom Paging in Grid\view Control. But Before going in depth let us first all understand the need of custom paging.
Suppose your database contain more than thousand record and you need to display only Ten record per page. In This situation Custom paging is more useful be because you may not want to show 1000-10=990 extra record which reduce the performance and improve the complicity. 

 So create the custom paging first of all create Stored procedure because I will create custom paging through help of Stored Procedure.

 Create PROCEDURE custompaging
 (
       @PageIndex INT,
       @PageSize INT,
       @totalrecord INT OUTPUT
 )
     
AS
BEGIN
      SET NOCOUNT ON
      SELECT ROW_NUMBER() OVER( ORDER BY id ASC)AS RowNumber,id,name, salary INTO #Results FROM emp    
      SELECT @totalrecord = COUNT(*) FROM #Results          
      SELECT * FROM #Results
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1    
      DROP TABLE #Results
END
 
Note: IN above declared procedure I have Used ROW_NUMBER() keyword which give us row numbers of records that you can select from the table.
Now Open a Empty web site and take a Gridview control for display the record of table and one Repeater control at the bottom of Gridview for create the paging.

Default.aspx code

<%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID ="Gridview1" runat ="server" AutoGenerateColumns ="false" >
    <Columns>
    <asp:BoundField HeaderText ="Id" DataField ="rownumber" />
    <asp:BoundField HeaderText ="Name" DataField ="name" />
    <asp:BoundField HeaderText ="Salary" DataField ="salary" />
    </Columns>
    </asp:GridView>
    <asp:Repeater ID ="repeater1" runat ="server" >
    <ItemTemplate >
    <asp:LinkButton ID ="linkbutton1" runat ="server" Text ='<%#Eval("Text") %>' CommandArgument ='<%#Eval("Value") %>' Enabled ='<%#Eval("Enabled") %>' OnClick ="Page_size"></asp:LinkButton>
    </ItemTemplate>
    </asp:Repeater>
    </form>
</body>
</html>
 
Default.aspx.cs Code
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.ShowdetailPageWise(1);
    }
 
    private void ShowdetailPageWise(int pageIndex)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString);
        SqlCommand cmd = new SqlCommand("custompaging", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@pageindex", pageIndex);
        cmd.Parameters.AddWithValue("@pagesize", 3);
        cmd .Parameters .Add ("@totalrecord",SqlDbType.Int,3);
        cmd.Parameters["@totalrecord"].Direction = ParameterDirection.Output;
        con.Open();
        IDataReader dr = cmd.ExecuteReader();
        Gridview1.DataSource = dr;
        Gridview1.DataBind();
        dr.Close();
        con.Close();
        int totalrecord = Convert.ToInt32(cmd.Parameters["@totalrecord"].Value);
        this.pagination(totalrecord, pageIndex);
     }
    public void pagination(int totalrecord, int pageindex)
    {  
        double totalpage = (double)((decimal)totalrecord  /3 );
        int pageCount = (int)Math.Ceiling(totalpage);
        List<ListItem> pages = new List<ListItem>();
        if (pageCount > 0)
        {                          
            pages.Add(new ListItem("First", "1", pageindex > 1));
                   
            for (int i = 1; i <= pageCount; i++)
            {
                pages.Add(new ListItem(i.ToString(), i.ToString(), i != pageindex));
            }         
            pages.Add(new ListItem("Last", pageCount.ToString(), pageindex  < pageCount));
        }
        repeater1.DataSource = pages;
        repeater1.DataBind();
}
    protected void Page_size(object sender, EventArgs e)
    {
       int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
       this.ShowdetailPageWise(pageIndex);
    }
}
 
Note: Above declared code I have used Two Method One for Show the table record in Gridview control and other method is Pagination which is used to create the custom paging at the bottom of Gridview.
 
I have created connection string in Web.config file.
 
  <connectionStrings>
    <add name="Myconnection" connectionString="Data Source=MCNDESKTOP08;Initial Catalog=pulkit;User ID=sa;Password=*********"/>
  </connectionStrings>
 
OutPut

Sunday, January 18, 2015

static in c#

Understanding Static

When you want to define a class member that will be used independently of any object of that class. Normally, a class member must be accessed through an object of its class. But it is possible to crate a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword Static, when a member is declared static, it can be accessed before any objects of its class are created and without reference to any object. You can declare both methods and variables to be static. The most common example of static member is Main(), which is declared static because it must be called by the operating system when your program begins.

Outside the class, to use a static member, you must specify the name of its calls followed by the dot operator.

For example: Timer.count =10;

Here Timer is the name of class and count is static member.

Variable declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead all instead of class share the same static variable. Static variable is initialized before its class is used. If no explicit initializer is specified, it is initialized to Zero for numeric type, null in the case of reference types, or false for variable of type bool. Thus static variable always have a value.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace @static
{
    class staticdemo
    {
        public static int val = 10;
        public static int valdiv()
        {
            return val / 2;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("initial value of static variable is " + staticdemo.val);
            staticdemo.val = 100;
            Console.WriteLine("static variable value after reinitialized " + staticdemo.val);
            Console.WriteLine("after method valdiv() called value " + staticdemo.valdiv());
            Console.Read();
        }
    }
}

Output


Some important point that apply to static method.
A static method does not have a this reference. This is because a static method does not execute relative to any object.

A static method can directly call only other static methods of its class. It cannot directly call an instance method of its class. The reason is that instance methods operate on specific objects, but a static method is not called on an object. Thus, on what object would the instance method operate?

A similar restriction applies to static data. A static method can directly access only other static data defined by its class. It cannot operate on an instance variable of its class because there is no object to operate on.

Note: Above declared point exception also occurs. Which are describing below?

It is important to understand that a static method can call instance methods and access instance variables of its class if it does of that class.

For example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace static_exception
{
    class staticexp
    {
        public int i;
        public void show()
        {
            this.i = 55;
            Console.WriteLine("this is non-static method");
        }
        
        public static int a;
        public static void display(staticexp obj)
        {
            obj.show();// non static called from static method
            obj.i = 200;
            a = 100;
            //this.a = 10; illigal because static method does not have this refernce
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            staticexp obj = new staticexp();
            staticexp .display (obj);
            Console.Read();
        }
    }
}

Output

                                       

                                                                                 
Author- Sayta Prakash

Friday, January 16, 2015

Basic C# OOP Concept Part 1

When our Buddies (Fresher’s) go for Technical Round in Interviews, They always have lotof confusion
About very basic questions which are related with Basic OOPS, Here I am not saying that they don’t know what the answers of these questions are.

Here I am just trying to discuss with you, how we can answer in frequent way or in that way, Interviewer wants to hear.

So Let us start.

Question - What is OOPs?

Oops is a system modeling technique in which a system is design in terms of discrete objects which Incorporates with each other to form entire system.

Let’s discuss with an Example.

A car is a system, if we want to develop this system?

What will we need to develop this?

As we all know, We require – Tires, Engine, Gear ,Seats ,Steering  etc…..
We can treat these parts as object which incorporates with each other to form entire system (Car).

Tires + Engine + Gear + Seats + other parts= Car (System)

Now we are moving towards a very important question which usually ask in plenty of ways like -

 Question – Pillars of OOPs  Or Properties of OOPS Or Features of OOPs

Mainly these are four Pillars of OOPS

1-    Abstraction
2-    Encapsulation
3-    Inheritance
4-    Polymorphism

In this article we will try to understand these properties with help of real world examples or very small examples.

We will discuss on these topics deeply in next article.

1-      Abstraction- In sort we can say that showing only relevant information is called Abstraction. 

 Let’s discuss abstraction with real world example.

Example- Let’s suppose that your father is going to buy a car along with you and your grandfather,So obviously there will be a Salesman at car showroom who will explain to you about the propertiesof car. He will work very smartly like 

1- When he will interact with you then he will talk about the color, pic up of the car means he will explain all these things which suits your style

2-When Same Sales man interacts with your father then he will tell him about EMI of the car.

3-When he will interact with your grandfather then he will tell him about the comfort of the car, how comfortable It is?

So you can feel in this example how Salesman smartly putting the only relevant information in front of every individual.
-------------------------------------------------------------------------------------------------------------
2-Encapsulation: In one line we can say that wrapping the data into single unit is called Encapsulation.

Note - There is one more question which could be raised?

How we can do Encapsulation?

So answer of this question is - we can do encapsulation with the help of Access Specifire.
There are five access  specifier in C#

a-     Private
b-    Public
c-     Protected
d-    Internal
e-    Protected  Internal

We will discuss about these access specifier deeply in our next article.

3-Inheritance: With the help of this property, a class can acquire the features of another class.
Inheritance is confine in Two Terms:

·        Parent Class or Base Class
·        Child Class or Derived Class

Let’s discuss inheritance with real world example.

We can take the example of relation between Computer and Laptop.
Computers invented firstly , we can treat as Parent Class or Base Class, It have some features, after that Laptop invented ,we can treat laptop as Child class , It contain all the basic features of computer(Base Class) along with own extra features.

Types of Inheritance:

1-    Single Inheritance             
2-    Multiple  Inheritance
3-    Multilevel Inheritance
4-    Hierarchy Inheritance
5-    Hybrid Inheritance
We will discuss about these all above Inheritances in our next Article.
-----------------------------------------------------------------------------------------------------------
  4-Polymorphism: Ability to take more than one form is called polymorphism.

Example of Polymorphism:
 
a)- Method Overloading (Compile Time Polymorphism)
b)-Method Overriding (Run Time Polymorphism)
 

Wednesday, January 14, 2015

Create Console Application and Configure as a Schedule task



using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespace Scheduler
{
classProgram
    {
staticvoid Main(string[] args)
        {
Console.Write("Message Send");
Console.ReadLine();
        }
    }
}

Note : I have created simple console application. Which run properly on command line

Now Schedule this application as a schedule task in windows 7 OS

Step 1

First of all copy the executable file of this application and keep it into separate folder on the target machine.

For this Right click on your project Name within solution ExplorerèOpen folderin file ExplorerèbinèdebugèCopy all file

Step 2

Now Create a folder on your target machine ( here I have created D:\Scheduler) and paste all copied item into this folder

Step 3

Now Click on Startècontrol panelè Choose Large Icon è Administrative tool è task scheduler 

Now task scheduler windows will be open with three pane

Step 4

In the Actions pane on the right, click “Create Basic Task…”



Step 5
The Create Task Wizard will open
Enter a name and description for the task



Step 6

Click “Next” to choose a trigger for the task
The trigger dialog for choosing when the task will run opens



Choose whether to run the task at specified times or when some event occurs
Click “Next”
Step 7
If you chose a time interval, a dialog to configure the times will open. Make a choice and click “Next”



Step 8
The “Action” dialog will open. Generally, you will choose “Start a Program”
Click “Next”


Step 9
The dialog for “Start a Program” will open. Enter or browse to the executable file or script you want to run

If needed, add arguments for your program or script



Step 10
Click “Next”
The “Summary” window will open where you can check to see if everything was entered as you wished. 
Click “Finish”


Author-Sayta Prakash