Monday, February 13, 2012

public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

protected void btnExcel_Click(object sender, ImageClickEventArgs e)

{

Response.ClearContent();

Response.Buffer = true;

Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));

Response.ContentType = "application/ms-excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

gvdetails.AllowPaging = false;

gvdetails.DataBind();

//Change the Header Row back to white color

gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");

//Applying stlye to gridview header cells

for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)

{

gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");

}

int j = 1;

//This loop is used to apply stlye to cells based on particular row

foreach (GridViewRow gvrow in gvdetails.Rows)

{

gvrow.BackColor = Color.White;

if (j <= gvdetails.Rows.Count)

{

if (j % 2 != 0)

{

for (int k = 0; k < gvrow.Cells.Count; k++)

{

gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");

}

}

}

j++;

}

gvdetails.RenderControl(htw);

Response.Write(sw.ToString());

Response.End();

}

Monday, February 6, 2012

http://dotnetguts.blogspot.in

SQL FAQ ESSENTIAL
http://dotnetguts.blogspot.in/2007/08/sql-queries-faq.html

SQL Queries FAQ

T-SQL Queries

1. 2 tables
Employee Phone
empid
empname
salary
mgrid empid
phnumber

2. Select all employees who doesn't have phone?
SELECT empname
FROM Employee
WHERE (empid NOT IN
(SELECT DISTINCT empid
FROM phone))


3. Select the employee names who is having more than one phone numbers.
SELECT empname
FROM employee
WHERE (empid IN
(SELECT empid
FROM phone
GROUP BY empid
HAVING COUNT(empid) > 1))

4. Select the details of 3 max salaried employees from employee table.
SELECT TOP 3 empid, salary
FROM employee
ORDER BY salary DESC

5. Display all managers from the table. (manager id is same as emp id)
SELECT empname
FROM employee
WHERE (empid IN
(SELECT DISTINCT mgrid
FROM employee))

6. Write a Select statement to list the Employee Name, Manager Name
under a particular manager?
SELECT e1.empname AS EmpName, e2.empname AS ManagerName
FROM Employee e1 INNER JOIN
Employee e2 ON e1.mgrid = e2.empid
ORDER BY e2.mgrid

7. 2 tables emp and phone.
emp fields are - empid, name
Ph fields are - empid, ph (office, mobile, home). Select all employees
who doesn't have any ph nos.
SELECT *
FROM employee LEFT OUTER JOIN
phone ON employee.empid = phone.empid
WHERE (phone.office IS NULL OR phone.office = ' ')
AND (phone.mobile IS NULL OR phone.mobile = ' ')
AND (phone.home IS NULL OR phone.home = ' ')

8. Find employee who is living in more than one city.
Two Tables:
Emp City
Empid Empid
empName City

Salary
SELECT empname, fname, lname
FROM employee
WHERE (empid IN
(SELECT empid
FROM city
GROUP BY empid
HAVING COUNT(empid) > 1))

9. Find all employees who is living in the same city. (table is same
as above)
SELECT fname
FROM employee
WHERE (empid IN
(SELECT empid
FROM city a
WHERE city IN
(SELECT city
FROM city b
GROUP BY city
HAVING COUNT(city) > 1)))

10. There is a table named MovieTable with three columns - moviename,
person and role. Write a query which gets the movie details where Mr.

Amitabh and Mr. Vinod acted and their role is actor.
SELECT DISTINCT m1.moviename
FROM MovieTable m1 INNER JOIN
MovieTable m2 ON m1.moviename = m2.moviename
WHERE (m1.person = 'amitabh' AND m2.person = 'vinod' OR
m2.person = 'amitabh' AND m1.person = 'vinod') AND (m1.role = 'actor')
AND (m2.role = 'actor')
ORDER BY m1.moviename

11. There are two employee tables named emp1 and emp2. Both contains
same structure (salary details). But Emp2 salary details are incorrect
and emp1 salary details are correct. So, write a query which corrects
salary details of the table emp2
update a set a.sal=b.sal from emp1 a, emp2 b where a.empid=b.empid

12. Given a Table named "Students" which contains studentid, subjectid
and marks. Where there are 10 subjects and 50 students. Write a Query
to find out the Maximum marks obtained in each subject.

13. In this same tables now write a SQL Query to get the studentid
also to combine with previous results.

14. Three tables – student , course, marks – how do go @ finding name
of the students who got max marks in the diff courses.
SELECT student.name, course.name AS coursename, marks.sid, marks.mark
FROM marks INNER JOIN
student ON marks.sid = student.sid INNER JOIN
course ON marks.cid = course.cid
WHERE (marks.mark =
(SELECT MAX(Mark)
FROM Marks MaxMark
WHERE MaxMark.cID = Marks.cID))

15. There is a table day_temp which has three columns dayid, day and
temperature. How do I write a query to get the difference of
temperature among each other for seven days of a week?
SELECT a.dayid, a.dday, a.tempe, a.tempe - b.tempe AS Difference
FROM day_temp a INNER JOIN
day_temp b ON a.dayid = b.dayid + 1

OR
Select a.day, a.degree-b.degree from temperature a, temperature b
where a.id=b.id+1

16. There is a table which contains the names like this. a1, a2, a3,
a3, a4, a1, a1, a2 and their salaries. Write a query to get grand
total salary, and total salaries of individual employees in one query.
SELECT empid, SUM(salary) AS salary
FROM employee
GROUP BY empid WITH ROLLUP
ORDER BY empid

17. How to know how many tables contains empno as a column in a database?
SELECT COUNT(*) AS Counter
FROM syscolumns
WHERE (name = 'empno')

18. Find duplicate rows in a table? OR I have a table with one column
which has many records which are not distinct. I need to find the
distinct values from that column and number of times it's repeated.
SELECT sid, mark, COUNT(*) AS Counter
FROM marks
GROUP BY sid, mark
HAVING (COUNT(*) > 1)

19. How to delete the rows which are duplicate (don't delete both
duplicate records).
SET ROWCOUNT 1
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND
b.age1 = a.age1) > 1
WHILE @@rowcount > 0
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND
b.age1 = a.age1) > 1
SET ROWCOUNT 0

20. How to find 6th highest salary
SELECT TOP 1 salary
FROM (SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

21. Find top salary among two tables
SELECT TOP 1 sal
FROM (SELECT MAX(sal) AS sal
FROM sal1
UNION
SELECT MAX(sal) AS sal
FROM sal2) a
ORDER BY sal DESC

22. Write a query to convert all the letters in a word to upper case
SELECT UPPER('test')

23. Write a query to round up the values of a number. For example even
if the user enters 7.1 it should be rounded up to 8.
SELECT CEILING (7.1)

24. Write a SQL Query to find first day of month?

SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1,
GETDATE())) AS FirstDay
Datepart Abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms

25. Table A contains column1 which is primary key and has 2 values (1,
2) and Table B contains column1 which is primary key and has 2 values
(2, 3). Write a query which returns the values that are not common for
the tables and the query should return one column with 2 records.
SELECT a.col1
FROM a, b
WHERE a.col1 <>
(SELECT b.col1
FROM a, b
WHERE a.col1 = b.col1)
UNION
SELECT b.col1
FROM a, b
WHERE b.col1 <>
(SELECT a.col1
FROM a, b
WHERE a.col1 = b.col1)

26. There are 3 tables Titles, Authors and Title-Authors. Write the
query to get the author name and the number of books written by that
author, the result should start from the author who has written the
maximum number of books and end with the author who has written the
minimum number of books.

27.
UPDATE emp_master
SET emp_sal =
CASE
WHEN emp_sal > 0 AND emp_sal <= 20000 THEN (emp_sal * 1.01) WHEN emp_sal > 20000 THEN (emp_sal * 1.02)
END


Monday, January 30, 2012

Level 3 -Class Using to Gridview Editing

3_INVOICINGAPPLICATIONWITHACLASS\INVOICING\INVOICE.CS

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

namespace Invoicing

{

public class clsInvoice

{

private string _InvoiceReference;

private string _InvoiceComments;

private DateTime _InvoiceDate;

private string _ProductName;

private string _ProductDescription;

private int _Qty;

private double _Amount;

private double _PaidAmount;

private double _TaxAmount;

private string _CustomerName;

private string _CustomerAddress;

private int _UnitCost;

public string InvoiceReference

{

set

{

if (value.Length == 0)

{

throw new Exception("Invoice number is compulsory");

}

_InvoiceReference = value;

}

get

{

return _InvoiceReference;

}

}

public string InvoiceComments

{

set

{

_InvoiceComments = value;

}

get

{

return _InvoiceComments;

}

}

public DateTime InvoiceDate

{

set

{

_InvoiceDate = value;

}

get

{

return _InvoiceDate;

}

}

public string ProductName

{

set

{

if (value.Length == 0)

{

throw new Exception("Product name is compulsory");

}

_ProductName = value;

}

get

{

return _ProductName;

}

}

public string ProductDescription

{

set

{

_ProductDescription = value;

}

get

{

return _ProductDescription;

}

}

public int Quantity

{

set

{

if (value < 1)

{

throw new Exception("Quantity should be numeric");

}

_Qty = value;

}

get

{

return _Qty;

}

}

public double Amount

{

set

{

_Amount = value;

}

get

{

return _Amount;

}

}

public double PaidAmount

{

set

{

_PaidAmount = value;

}

get

{

return _PaidAmount;

}

}

public double TaxAmount

{

set

{

_TaxAmount = value;

}

get

{

return _TaxAmount;

}

}

public string CustomerName

{

set

{

if (value.Length == 0)

{

throw new Exception("Customer Name is compulsory");

}

_CustomerName = value;

}

get

{

return _CustomerName;

}

}

public string CustomerAddress

{

set

{

_CustomerAddress = value;

}

get

{

return _CustomerAddress;

}

}

public int UnitCost

{

set

{

if (value == 0)

{

throw new Exception("Unit cost is compulsory");

}

_UnitCost = value;

}

get

{

return _UnitCost;

}

}

public void Insert()

{

SqlConnection ObjConnection = new SqlConnection();

ObjConnection.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];

ObjConnection.Open();

SqlCommand objCommand = new SqlCommand();

objCommand.Connection = ObjConnection;

objCommand.CommandText = "Insert into invoice(InvoiceReference,InvoiceComments,InvoiceDate,ProductName,Description,Qty,Amount,TaxAmount,PaidAmount,CustomerName,CustomerAddress,UnitCost) values('" + _InvoiceReference + "','" + _InvoiceComments + "','" + _InvoiceDate + "','" + _ProductName + "','" + _ProductDescription + "'," + _Qty.ToString() + "," + _Amount.ToString() + "," + _TaxAmount.ToString() + "," + _PaidAmount.ToString() + ",'" + _CustomerName + "','" + _CustomerAddress + "'," + _UnitCost.ToString() + ")";

objCommand.ExecuteNonQuery();

ObjConnection.Close();

}

public void Update()

{

SqlConnection ObjConnection = new SqlConnection();

ObjConnection.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];

ObjConnection.Open();

SqlCommand objCommand = new SqlCommand();

objCommand.Connection = ObjConnection;

objCommand.CommandText = "update invoice set InvoiceComments='" + _InvoiceComments + "',InvoiceDate='" + _InvoiceDate + "',ProductName='" + _ProductName + "',Description='" + _ProductDescription + "',Qty=" + _Qty.ToString() + ",Amount=" + _Amount + ",TaxAmount=" + _TaxAmount + ",PaidAmount=" + _PaidAmount + ",CustomerName='" + _CustomerName + "',CustomerAddress='" + _CustomerAddress + "',UnitCost=" + _UnitCost + "where InvoiceReference='" + _InvoiceReference + "'";

objCommand.ExecuteNonQuery();

}

public void Delete()

{

SqlConnection ObjConnection = new SqlConnection();

ObjConnection.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];

ObjConnection.Open();

SqlCommand objCommand = new SqlCommand();

objCommand.Connection = ObjConnection;

objCommand.CommandText = "delete from invoice where InvoiceReference='" + _InvoiceReference + "'";

objCommand.ExecuteNonQuery();

}

public DataSet getInvoice()

{

SqlConnection ObjConnection = new SqlConnection();

ObjConnection.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];

ObjConnection.Open();

DataSet objdataset = new DataSet();

SqlDataAdapter objDataAdapter = new SqlDataAdapter("Select * from invoice", ObjConnection);

objDataAdapter.Fill(objdataset);

ObjConnection.Close();

return objdataset;

}

public void LoadInvoice(string InvoiceNumber)

{

SqlConnection ObjConnection = new SqlConnection();

ObjConnection.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];

ObjConnection.Open();

DataSet objdataset = new DataSet();

SqlDataAdapter objDataAdapter = new SqlDataAdapter("Select * from invoice where InvoiceReference='" + InvoiceNumber + "'", ObjConnection);

objDataAdapter.Fill(objdataset);

_CustomerName = objdataset.Tables[0].Rows[0]["Customername"].ToString();

_CustomerAddress = objdataset.Tables[0].Rows[0]["CustomerAddress"].ToString();

_Amount = Convert.ToInt16(objdataset.Tables[0].Rows[0]["Amount"]);

_PaidAmount = Convert.ToDouble(objdataset.Tables[0].Rows[0]["PaidAmount"]);

_InvoiceDate = Convert.ToDateTime(objdataset.Tables[0].Rows[0]["InvoiceDate"]);

_InvoiceComments = objdataset.Tables[0].Rows[0]["InvoiceComments"].ToString();

_InvoiceReference = objdataset.Tables[0].Rows[0]["InvoiceReference"].ToString();

_ProductName = objdataset.Tables[0].Rows[0]["ProductName"].ToString();

_ProductDescription = objdataset.Tables[0].Rows[0]["Description"].ToString();

_Qty = Convert.ToInt16(objdataset.Tables[0].Rows[0]["Qty"]);

_TaxAmount = Convert.ToDouble(objdataset.Tables[0].Rows[0]["TaxAmount"]);

_UnitCost = Convert.ToInt16(objdataset.Tables[0].Rows[0]["UnitCost"]);

}

}

}


3_InvoicingApplicationWithaClass\InvoiceEntry.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InvoiceEntry.aspx.cs" Inherits="InvoiceEntry" %>

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>

<style type="text/css">

.style2

{

text-align: center;

}

.style3

{

color: #663300;

font-weight: bold;

}

style>

head>

<body>

<div class="style2">

<span class="style3" lang="en-us">Simple Invoicing Applicationspan>

div>

<form id="form1" runat="server">

<div>

<asp:Label ID="Label1" runat="server" Text="Customer Name">asp:Label>

<asp:TextBox ID="txtCustomerName" runat="server">asp:TextBox>

<asp:Label ID="Label2" runat="server" Text="Customer Address">asp:Label>

<asp:TextBox ID="txtCustomerAddress" runat="server" TextMode="MultiLine">asp:TextBox>

<asp:Label ID="Label3" runat="server" Text="Invoice Number">asp:Label>

<asp:TextBox ID="txtInvoiceNumber" runat="server">asp:TextBox>

<br />

<br />

<br />

<asp:Label ID="Label4" runat="server" Text="Invoice Date">asp:Label>

<span lang="en-us">

<asp:TextBox ID="txtInvoiceDate" runat="server">asp:TextBox>

<asp:Label ID="Label5" runat="server" Text="Product Name">asp:Label>

<asp:TextBox ID="txtProductName" runat="server">asp:TextBox>

<asp:Label ID="Label6" runat="server" Text="Product Description">asp:Label>

<asp:TextBox ID="txtProductDescription" runat="server">asp:TextBox>

<br />

<br />

<asp:Label ID="Label7" runat="server" Text="Unit Cost">asp:Label>

<asp:TextBox ID="txtUnitCost" runat="server">asp:TextBox>

<asp:Label ID="Label8" runat="server" Text="Quantity">asp:Label>

<asp:TextBox ID="TxtQuantity" runat="server">asp:TextBox>

<asp:Label ID="Label9" runat="server" Text="Total Amount to be paid">asp:Label>

<asp:TextBox ID="txtAmountToBePaid" runat="server">asp:TextBox>

<br />

<br />

<asp:Label ID="Label10" runat="server" Text="Total Amount paid">asp:Label>

<asp:TextBox ID="txtAmountPaid" runat="server">asp:TextBox>

<asp:Label ID="Label12" runat="server" Text="Tax Amount">asp:Label>

<asp:TextBox ID="txtTaxAmount" runat="server">asp:TextBox>

<asp:Label ID="Label11" runat="server" Text="Comments">asp:Label>

<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine">asp:TextBox>

<br />

<asp:Button ID="btnAddInvoice" runat="server" Text="Add Invoice"

style="height: 26px" onclick="btnAddInvoice_Click" />

<asp:Button ID="btnUpdateInvoice" runat="server" Text="update Invoice" onclick="btnUpdateInvoice_Click"

/>

<asp:Button ID="btnDeleteInvoice" runat="server" Text="Delete Invoice" onclick="btnDeleteInvoice_Click"

/>

span>

div>

<asp:DataGrid ID="dtgInvoice" runat="server"

onselectedindexchanged="dtgInvoice_SelectedIndexChanged" BackColor="White"

BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"

ForeColor="Black" GridLines="Vertical">

<FooterStyle BackColor="#CCCC99" />

<SelectedItemStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right"

Mode="NumericPages" />

<AlternatingItemStyle BackColor="White" />

<ItemStyle BackColor="#F7F7DE" />

<Columns>

<asp:ButtonColumn CommandName="Select" Text="Select">asp:ButtonColumn>

Columns>

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

asp:DataGrid>

<asp:Label ID="lblErrorMessage" runat="server" ForeColor="Red" Text="Label">asp:Label>

form>

body>

html>

3_INVOICINGAPPLICATIONWITHACLASS\InvoiceEntry.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;

using Invoicing;

public partial class InvoiceEntry : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

LoadGrid();

}

private void LoadGrid()

{

// load the data set in to the data grid

clsInvoice objInvoice = new clsInvoice();

dtgInvoice.DataSource = objInvoice.getInvoice();

dtgInvoice.DataBind();

}

public void clearText()

{

txtInvoiceNumber.Text = "";

txtComments.Text = "";

txtInvoiceDate.Text = "";

txtProductName.Text = "";

txtProductDescription.Text = "";

TxtQuantity.Text = "";

txtAmountToBePaid.Text = "";

txtTaxAmount.Text = "";

txtAmountPaid.Text = "";

txtCustomerName.Text = "";

txtCustomerAddress.Text = "";

txtUnitCost.Text = "";

}

protected void btnAddInvoice_Click(object sender, EventArgs e)

{

try

{

clsInvoice objInvoice = new clsInvoice();

setObjectFromUI(objInvoice);

objInvoice.Insert();

LoadGrid();

clearText();

}

catch (Exception ex)

{

lblErrorMessage.Text = ex.Message.ToString();

}

}

public void setObjectFromUI(clsInvoice objInvoice)

{

try

{

objInvoice.CustomerName = txtCustomerName.Text;

objInvoice.CustomerAddress = txtCustomerAddress.Text;

objInvoice.Amount = Convert.ToDouble(txtAmountToBePaid.Text);

objInvoice.PaidAmount = Convert.ToDouble(txtAmountPaid.Text);

objInvoice.InvoiceDate = Convert.ToDateTime(txtInvoiceDate.Text);

objInvoice.InvoiceComments = txtComments.Text;

objInvoice.InvoiceReference = txtInvoiceNumber.Text;

objInvoice.ProductName = txtProductName.Text;

objInvoice.ProductDescription = txtProductDescription.Text;

objInvoice.Quantity = Convert.ToInt16(TxtQuantity.Text);

objInvoice.TaxAmount = Convert.ToDouble(txtTaxAmount.Text);

objInvoice.UnitCost = Convert.ToInt16(txtUnitCost.Text);

}

catch (Exception ex)

{

throw ex;

}

}

public void setUIfromObject(clsInvoice objInvoice)

{

txtCustomerName.Text = objInvoice.CustomerName;

txtCustomerAddress.Text = objInvoice.CustomerAddress;

txtAmountToBePaid.Text = objInvoice.Amount.ToString();

txtAmountPaid.Text = objInvoice.PaidAmount.ToString();

txtInvoiceDate.Text = objInvoice.InvoiceDate.ToString();

txtComments.Text = objInvoice.InvoiceComments.ToString();

txtInvoiceNumber.Text = objInvoice.InvoiceReference.ToString();

txtProductName.Text = objInvoice.ProductName.ToString();

txtProductDescription.Text = objInvoice.ProductDescription.ToString();

TxtQuantity.Text = objInvoice.Quantity.ToString();

txtTaxAmount.Text = objInvoice.TaxAmount.ToString();

txtUnitCost.Text = objInvoice.UnitCost.ToString();

}

protected void btnUpdateInvoice_Click(object sender, EventArgs e)

{

clsInvoice objInvoice = new clsInvoice();

try

{

setObjectFromUI(objInvoice);

objInvoice.Update();

clearText();

LoadGrid();

}

catch (Exception ex)

{

lblErrorMessage.Text = ex.Message.ToString();

}

}

protected void btnDeleteInvoice_Click(object sender, EventArgs e)

{

clsInvoice objInvoice = new clsInvoice();

setObjectFromUI(objInvoice);

objInvoice.Delete();

clearText();

LoadGrid();

}

protected void dtgInvoice_SelectedIndexChanged(object sender, EventArgs e)

{

clsInvoice objInvoice = new clsInvoice();

objInvoice.LoadInvoice(dtgInvoice.SelectedItem.Cells[1].Text.ToString());

setUIfromObject(objInvoice);

}

}