Thursday, December 22, 2011

Ajax UpdatePanel Example in ASP.NET using C#

Ajax UpdatePanel Example in ASP.NET using C# 


 UpdatePanel control in ASP.NET is used to define a region that you want to refresh without affecting the web page. In this example we take a UpdatePanel, button and a label. When you click the Button it will generate the random number and show result in label.

 UpdatePanel.aspx (source code):

<%@ Page Title="" Language="C#" MasterPageFile="~/DotnetinfomediaMaster.master" AutoEventWireup="true"
CodeFile="UpdatePanel.aspx.cs" Inherits="UpdatePanel" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div>
<h2 style="color: Green">
UpdatePanel in ASP.NET 4, C#</h2>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="update_Button" Text="Generate Random NO" Width="187px"
OnClick="update_Button_Click" />
<br />
<br />
<asp:Label runat="server" ID="Label1" Font-Bold="True" Font-Names="Cambria" Font-Size="X-Large"
ForeColor="#003300" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>


UpdatePanel.aspx.cs (C# code file):



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class UpdatePanel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void update_Button_Click(object sender, EventArgs e)
{
Label1.Text = "Random Number : " + new Random().Next().ToString();
}
}



Scrollable GridView With Fixed Headers Asp.Net

Scrollable GridView With Fixed Headers Asp.Net

how to create scrollable GridView with fixed headers which don't get scrolled with records and stay on the top in asp.net using css 


Html Source :
  
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" Height="200px" 
                       Width="200px" ScrollBars="Vertical">

<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1"
              RowStyle-VerticalAlign="Bottom"
              OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" 
                InsertVisible="False" 
                ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" 
                                 SortExpression="Name" />
<asp:BoundField DataField="Location" HeaderText="Location" 
                             SortExpression="Location" />
</Columns>
<HeaderStyle CssClass="header"Height="20px" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [EmployeeID], [EmployeeName], [EmployeeLocation] FROM [EMPDetails]">
</asp:SqlDataSource>
</asp:Panel>
</div>
</form>


css style in the head section
<head runat="server">
<title>Dotnetinfomedia scrollable GridView with fixed headers</title>
<style type="text/css">
.header
  {
    font-weight:bold;
    position:absolute;
   background-color:White;
  }
 </style>
</head>

Place the code  in Gridview RowData Bound


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if(e.Row.RowIndex == 0) e.Row.Style.Add("height","40px"); } }

Happy coading !! 
By
http://dotnetinfomedia.blogspot.com/


Monday, December 19, 2011

What is a Trigger?

A trigger is a sql block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed.


The Syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER trigger_name 
{BEFORE | AFTER | INSTEAD OF } 
{INSERT [OR] | UPDATE [OR] | DELETE} 
[OF col_name] 
ON table_name 
[REFERENCING OLD AS o NEW AS n] 
[FOR EACH ROW] 
WHEN (condition)  
BEGIN 
--- sql statements  
END; 

Friday, December 16, 2011

LINQ with samples


INTRODUCTION TO LINQ??

LINQ stand for Language-Integrated Query is now available as a integral part of Visual Studio 2008.
LINQ has a great power of querying on any source of data, data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and that are give below.
  • LINQ to Object
  • LINQ to ADO.Net  
    • LINQ to SQL
    • LINQ to Dataset
    • LINQ to Entities
  • LINQ to XML
Here we will see how a linq can be utilized in a company module.
The company class will contain a Collection of employee class and employee will contain a struct for individual addresses.
Hierarchy: 
CompanyLINQ.JPG
If we have a project with above hierarchy, let’s see how we can use LINQ to access details from multilevel classes.
After creation of companies we will try to find the details at multilevel and see how conditionally data can be fetched.
1)      List details of employees
2)      Count no of employees in each company
3)      List employees who are staying in Bangalore
4)      List employee who is paid highest in each companies
5)      Overall Highest paid employee
6)      Salary paid by companies in each city
7)      Salary paid by each company in each city.
List details of employees:
Now we shall list all the employees with their details and company name.


var EmpDetails = from comp in ListCompany 
                 select new {
                       Emp = (from emp in comp.ListEmp  
                              select new {
                                   Company = comp.Name, 
                                   emp 
                              })
                  }; 
Here we use sub queries since we need all employee details with their respective company name and both the details are at different levels.
So first we Loops through the companies in the company list  
from comp in ListCompany  
and then within each selected company it loops through each employee
from emp in comp.ListEmp 
  
Count no of employees in each company:
  var LessEmp = from  Comp in  ListCompany  
                select new { 
                                       Comp.Name,
                       EmpCount = Comp.ListEmp.Count
                            };   
List employees who are staying in Bangalore: 
Here we use compound from clause to retrieve the employees who are staying in any city that contains BAN or ban.  
var EmpInACity = from comp in ListCompany 

                 from emplist in comp.ListEmp 
                 where emplist.Address.City.ToUpper().Contains(&quot;BAN&quot;)
                 select new {
                        CompName = comp.Name,
                        EmployeeName = emplist.Name 
                 }; 
List employee who is paid highest in each companies: 
For finding the highest paid employee we first loop through all the companies and employees in each company using compound from clause.
Where condition filters only those employees those have the salary equal to the max salary in current company. 
var  EmpHighSalEachComp = from comp in ListCompany 
                          from empHigh in comp.ListEmp  
                          where empHigh.salary == comp.ListEmp.Max(
                          HighEmp => HighEmp.salary) 
                          select new {
                                 CompanyName = comp.Name, 
                                 EmpHighName = empHigh.Name,
                                 EmpHighSal = empHigh.salary
                          }; 
Overall Highest paid employee:
The same above procedure is followed but the only difference comes in the where condition where we match the employee’s salary to the max salary from all the companies. 
var EmpHighSal = from comp in ListCompany
                 from emp in comp.ListEmp 
                 where emp.salary == ListCompany.Max(
                 TComp => TComp.ListEmp.Max(HighEmp => HighEmp.salary))
                 select new {
                        CompanyName = comp.Name ,
                        EmployeeName = emp.Name,
                        EmpSal = emp.salary
                 }; 
Salary paid by companies in each city: 
Here we will group by city and sum up all the salaries of the employees who are staying in that city. 
var CompanyCityWise = from comp in ListCompany          

                      from emp in comp.ListEmp 
                                       group emp by emp.Address.City into CityWiseEmp 
                      select new {
                             State = CityWiseEmp.Key, 
                             TotalSalary = CityWiseEmp.Sum(emp => emp.salary) 
                      }; 
Salary paid by each company in each city. 
Here for each company a group by clause is applied and from each company employees staying at different locations are fetched.
var  CityWiseSalary = from comp in ListCompany 
                      select new { 
                             comp.Name,
                             Emp =(from emp in comp.ListEmp 
                             group emp by emp.Address.City into CityWiseEmp
                             select new {
                                    State = CityWiseEmp.Key,
                                    TotalSalary = CityWiseEmp.Sum(emp => emp.salary) 
                             })
                      }; 
More references on LINQ:

What is LINQ?


Microsoft New Baby
Microsoft new baby yes I am talking about LINQ stand for Language-Integrated Query is now available as a integral part of Visual Studio Orcas. Microsoft releases the new Visual Studio with the name of Orcas and all Microsoft previous efforts (Windows Communication Foundation WCF, Windows Workflow Foundation WWF, Windows Presentation Foundation WPF, Windows CardSpace and LINQ) are integrated in this Studio. From last one and half years Anders Hejlsberg team done a tremendous job in the overcoming the gap between the data impedance. Mr. Anders team gives a native syntax to developers in the form LINQ to C# and VB.Net for accessing data from any repository. The repository could be in memory object, database (still MS SQL Server only) and XML files.
What is LINQ?
Still lots of folks don’t understand what LINQ is doing. Basically LINQ address the current database development model in the context of Object Oriented Programming Model. If some one wants to develop database application on .Net platform the very simple approach he uses ADO.Net. ADO.Net is serving as middle ware in application and provides complete object oriented wrapper around the database SQL. Developing application in C# and VB.Net so developer must have good knowledge of object oriented concept as well as SQL, so it means developer must be familiar with both technologies to develop an application. If here I can say SQL statements are become part of the C# and VB.Net code so it’s not mistaken in form of LINQ. According to Anders Hejlsberg the chief architect of C#.
             “Microsoft original motivation behind LINQ was to address the impedance mismatch between programming languages and database.”
LINQ has a great power of querying on any source of data, data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and that are give below.
  • LINQ to Object {Queries performed against the in-memory data}
  • LINQ to ADO.Net
    • LINQ to SQL (formerly DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported}
    • LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}
    • LINQ to Entities {Microsoft ORM solution}
  • LINQ to XML (formerly XLinq) { Queries performed against the XML source}
I hope few above lines increase your concrete knowledge about Microsoft LINQ and now we write some code snippet of LINQ.


1. Code Snippet
int[] nums = new int[] {0,1,2};var res = from a in nums             where a < 3             orderby a             select a;foreach(int i in res)    Console.WriteLine(i);
Output:012
All SQL Operates are available in LINQ to Object like Sum Operator in the following code.
2. Code Snippet
int[] nums = new int[] {2,4,6,2};int result = nums.Sum();Console.WriteLine(result);


Output:1
2

One thing that I want to share with you guys is LINQ to Object support querying against any object that inherits from IEnumerable (all .Net collection inherits from IEnumerable interface). LINQ to Object provided main types of Operator Type that are give below.
Operator Types
Operator Name
Aggregation
  • Aggregate
  • Average
  • Count
  • LongCount,
  • Max,
  • Min,
  • Sum
Conversion
  • Cast,
  • OfType,
  • ToArray,
  • ToDictionary,
  • ToList,
  • ToLookup,
  • ToSequence
Element
  • DefaultIfEmpty,
  • ElementAt,
  • ElementAtOrDefault,
  • First,
  • FirstOrDefault,
  • Last,
  • LastOrDefault,
  • Single,
  • SingleOrDefault
Equality
  • EqualAll
Generation
  • Empty,
  • Range,
  • Repeat
Grouping
  • GroupBy
Joining
  • GroupJoin,
  • Join
Ordering
  • OrderBy,
  • ThenBy,
  • OrderByDescending,
  • ThenByDescending,
  • Reverse
Partitioning
  • Skip,
  • SkipWhile,
  •  Take,
  •  TakeWhile
Quantifiers
  • All,
  • Any,
  • Contains
Restriction
  • Where
Selection
  • Select,
  • SelectMany
Set
  • Concat,
  • Distinct,
  • Except,
  • Intersect,
  • Union
To the good use of above operator types I need samle patient class so here it
using System;
public class Patient
{
    // Fields
    private string _name;
    private int _age;
    private string _gender;
    private string _area;
    // Properties
    public string PatientName
    {
        get { return _name; }
        set { _name = value; }
    }
    public string Area
    {
        get { return _area; }
        set { _area = value; }
    }
    public String Gender
    {
        get { return _gender; }
        set { _gender = value; }
    }
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}
Here is my code that intiliaze patients object with following data.
List<Patient> patients = new List<Patient> {
           new Patient { PatientName="Ali Khan", Age=20, Gender="Male" , Area = "Gulshan"},
           new Patient { PatientName="Ahmed Siddiqui", Age=25 ,Gender="Male", Area = "NorthKarachi" },
           new Patient { PatientName="Nida Ali", Age=20, Gender="Female", Area = "NorthNazimabad"},
           new Patient { PatientName="Sana Khan", Age=18, Gender="Female", Area = "NorthNazimabad"},
           new Patient { PatientName="Shahbaz Khan", Age=19, Gender="Male", Area = "Gulshan"},
           new Patient { PatientName="Noman Altaf", Age=19, Gender="Male", Area = "Gulshan"},
           new Patient { PatientName="Uzma Shah", Age=23, Gender="Female", Area = "NorthKarachi"}};
Patient p = new Patient();
        p.Age =33; p.Gender = "male";
        p.PatientName = "Hammad Ali"
        p.Area = "Defence";         
        patients.Add(p);
I have been written a blog on the new way of initilaztion.

This code snippet fetch those records whose gender is equal to “Male”.
 
   gdView.DataSource = from pa in patients
                        where pa.Gender == "Male"
                        orderby pa.PatientName, pa.Gender, pa.Age
                        select pa;
   gdView.DataBind();
The following code snippet uses the selection operator type, which brings all those records whose age is more than 20 years.
 var mypatient = from pa in patients
                  where pa.Age > 20
                  orderby pa.PatientName, pa.Gender, pa.Age
                  select pa;
       
        foreach(var pp in mypatient)
        {
        Debug.WriteLine(pp.PatientName + " "+ pp.Age + " " +          pp.Gender);
        }
 The following code snippet uses the grouping operator type that group patient data on the bases area. 
var op = from pa in patients
group pa by pa.Area into g
select new {area = g.Key, count = g.Count(), allpatient = g};
 foreach(var g in op)
 {
    Debug.WriteLine(g.count+ "," + g.area);
    foreach(var l in g.allpatient)
     {
       Debug.WriteLine("\t"+l.PatientName);
     }
 }

This code snippet determine the count of those records, which lay in above 20 years. 
int patientCount = (from pa in patients
                    where pa.Age > 20
                    orderby pa.PatientName, pa.Gender, pa.Age
                    select pa).Count();

All the above codes are few example of LINQ to Object technique of LINQ. In my up coming post you will see both LINQ to SQL and LINQ to XML code snippets.