Tuesday, September 6, 2011

Get values of a check box to do a command in for loop


protected void Btn_ApproveChkd_Click(object sender, EventArgs e)
{
try
{
int itemChecked = 0;
foreach (GridViewRow Gitem in grdDispatchGrid.Rows)
{               
CheckBox ChkGrid = (CheckBox)Gitem.FindControl("ChkApprove");
if (ChkGrid.Checked == true)
{
itemChecked = 1;
break;
}
}
if (itemChecked == 1)

{
foreach (GridViewRow Gitem in grdDispatchGrid.Rows)

{                   
int _LeaveId = Convert.ToInt32(grdDispatchGrid.DataKeys[Gitem.RowIndex].Values["leave_id"].ToString());
con.Open();

string Qry = "ReqLeaveApproved";

SqlCommand cmd = new SqlCommand(Qry, con);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add("@Emp_Id", SqlDbType.NChar);

cmd.Parameters["@Emp_Id"].Value = Session["_EmpId"];

cmd.Parameters.Add("@leave_id", SqlDbType.Int);

cmd.Parameters["@leave_id"].Value = _LeaveId;

cmd.Parameters.Add("@Status", SqlDbType.Int);

cmd.Parameters["@Status"].Value = "2";

cmd.ExecuteNonQuery();

con.Close();

}

Response.Redirect(
"FrmAdminApproval.aspx");

}

else if (itemChecked == 0)

{

}

}

catch (Exception Ex)

{

}

}

Javascript Funtion to Select All the Check Box in a Column of a Grid


<script type="text/javascript" language="javascript">
function SelectAll(CheckBox) {

// Give the Grid ID in the below line
TotalChkBx = parseInt('<%= this.grdDispatchGrid.Rows.Count %>');

var TargetBaseControl = document.getElementById('<%= this.grdDispatchGrid.ClientID %>');

// Give the ColumnId of a grid which must be checked

var TargetChildControl = "ChkApporove";

var Inputs = TargetBaseControl.getElementsByTagName("input");

for (var iCount = 0; iCount < Inputs.length; ++iCount)
{

if (Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl, 0) >= 0)

Inputs[iCount].checked = CheckBox.checked;
}

}   
</script>


<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChkApporove" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" Text="All" onclick="SelectAll(this);" />
</HeaderTemplate>
</asp:TemplateField>

Write Data to A File Using FileStream and StreamWriter


using System.IO;

   private void Write2File(string msg, string filePath)
   {
      FileStream fs = 
new FileStream(filePath, FileMode.Append);
      StreamWriter sw = 
new StreamWriter(fs);
      sw.WriteLine(msg);
      sw.Flush();
      sw.Close();
      fs.Close();
   }

Asp.net Complete Tutorial

Asp.net Complete Tutorial

Grid on row Edit and Update ...




protected void GridViewEmpAttendance_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridViewEmpAttendance.EditIndex = e.NewEditIndex;
            SendEmpAndCenterToGetAttendance(dpd_CenterName.SelectedItem.Text.ToString(), dpd_emp.SelectedItem.Text.ToString());
        }

        protected void GridViewEmpAttendance_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridViewEmpAttendance.EditIndex = -1;
            SendEmpAndCenterToGetAttendance(dpd_CenterName.SelectedItem.Text.ToString(), dpd_emp.SelectedItem.Text.ToString());
        }

        protected void GridViewEmpAttendance_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Label _ecode = (Label)GridViewEmpAttendance.Rows[e.RowIndex].FindControl("lbl_ecode");
            Label _Date = (Label)GridViewEmpAttendance.Rows[e.RowIndex].FindControl("lbl_date");
            DropDownList _EmpStatus = (DropDownList)GridViewEmpAttendance.Rows[e.RowIndex].FindControl("DStatusEdit");
            string ecode = _ecode.Text.ToString();
            string status = _EmpStatus.SelectedValue.ToString();
            string dat = _Date.Text.ToString();
            MtdUpdateAttendance(ecode, dat, status);
            GridViewEmpAttendance.EditIndex = -1;
            SendEmpAndCenterToGetAttendance(dpd_CenterName.SelectedItem.Text.ToString(), dpd_emp.SelectedItem.Text.ToString());
        }

        protected void GridViewEmpAttendance_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
            {
                DropDownList DDLStatus = (DropDownList)e.Row.FindControl("DStatusEdit");
                DDLStatus.DataSource = StatusBind();
                DDLStatus.DataTextField = "Status";
                DDLStatus.DataValueField = "Status";
                DDLStatus.DataBind();
                DDLStatus.Items.Insert(0, new ListItem("Select", "0"));
                DDLStatus.SelectedValue = Convert.ToString(GridViewEmpAttendance.DataKeys[e.Row.RowIndex]["status"].ToString());
            }
        }

Execute Stored Procedure with Parameters





protected void CallSPwithParams(string passedparameter)
{
using (SqlConnection sqlcon = new SqlConnection(dbconn))
 {
  string updatequerry = "StoredProcedureName";
  SqlCommand cmd = new SqlCommand(updatequerry, sqlcon);
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Parameters.AddWithValue("@sqlparam", passedparameter );
  sqlcon.Open();
  cmd.ExecuteNonQuery();
  sqlcon.Close();
               
  }
}

Read Database Connection String from Web.config


Read Database Connection String from Web.config

1.Place the connection string in AppSetting the Web.Config File
<appSettings>
<add key="dbcon" value="Data Source=Ipaddress Or Hostname;
Initial Catalog=DatabaseName;User ID=sa;Password=password123;"/>
</appSettings>
Read the Connection String in the Code:
public static string dbconn = ConfigurationManager.AppSettings["dbcon"].ToString();

2.Place the connection string in connectionStrings in the Web.Config File
<connectionStrings>
<add name="ImageUploaded" connectionString="Data Source=10.200.2.28;Initial Catalog=CoolDB;User ID=sa;Password=123" providerName="System.Data.SqlClient" />
</connectionStrings>
Read the Connection String in the Code:
public static string CONN_STRING1 = ConfigurationManager.ConnectionStrings["ImageUploaded"].ConnectionString;

Execute Stored Procedure with Parameters





protected void CallSPwithParams(string passedparameter)
{
using (SqlConnection sqlcon = new SqlConnection(dbconn))
 {
  string updatequerry = "StoredProcedureName";
  SqlCommand cmd = new SqlCommand(updatequerry, sqlcon);
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Parameters.AddWithValue("@sqlparam", passedparameter );
  sqlcon.Open();
  cmd.ExecuteNonQuery();
  sqlcon.Close();
               
  }
}

Reading xml data

Reading xml data

DECLARE @MyXML XML
set @MyXML = @MyXML =
'<referenceranges><referencerange>
<property type="other" value="Male">
<lst gender="Male" value="4.0, 5.0">Negative </lst>
</property><property type="other" value="Male">
<btw gender="Male" value="4.0-6.0">Equivocal</btw>
</property><property type="other" value="Male">
<grq gender="Male" value="6.0">Positive </grq>
</property><property type="other" value="Female">
<lst gender="Female" value="4.0">Negative</lst>
</property><property type="other" value="Female">
<btw gender="Female" value="4.0-6.0">Equivocal</btw>
</property><property type="other" value="Female">
<grq gender="Female" value="6.0">Positive</grq>
</property>
</referencerange></referenceranges>'
 
B.test.value('@value[1]', 'nvarchar(400)') as Gender,
B.test.value('(lst/@value)[1]', 'nvarchar(400)') as lstvalue
B.test.query('lst').value('.', 'nvarchar(400)') as Lst,                            B.test.value('(btw/@value)[1]', 'nvarchar(400)') as btwvale,
B.test.query('btw').value('.', 'nvarchar(400)') as btw,    
B.test.value('(grq/@value)[1]', 'nvarchar(400)') as grqvalue,    
B.test.query('grq').value('.', 'nvarchar(400)') as grq    
FROM @MyXML.nodes('referenceranges/referencerange/property') AS B(test)

SELECT

New Features of Denali.

SQL BASICS SYNTAX



In this page, we list the SQL syntax for each of the SQL commands in this tutorial, making this an easy reference for someone to learn SQL. For detailed explanations of each SQL syntax, please go to the individual section by clicking on the keyword.
Select Statement
SELECT "column_name" FROM "table_name"
Distinct
SELECT DISTINCT "column_name"
FROM "table_name"
Where
SELECT "column_name"
FROM "table_name"
WHERE "condition"
And/Or
SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{[AND|OR] "simple condition"}+
In
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...)
Between
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'
Like
SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN}
Order By
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC]
Count
SELECT COUNT("column_name")
FROM "table_name"
Group By
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
Having
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
HAVING (arithematic function condition)
Create Table Statement
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )
Drop Table Statement
DROP TABLE "table_name"
Truncate Table Statement
TRUNCATE TABLE "table_name"
Insert Into Statement
INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...)
Update Statement
UPDATE "table_name"
SET "column_1" = [new value]
WHERE {condition}
Delete From Statement
DELETE FROM "table_name"
WHERE {condition}

ISNULL,NULLIF Functions



DECLARE @Char char(10)

SELECT @Char = NULL
SELECT ISNULL(@Char,'ABC' )
Result: ABC
SELECT @Char ='ABC'
SELECT NULLIF(@Char,'ABC')
Result: NULL

Dates between Startdate and Enddate


-- these would be your input parameters
DECLARE
        @empno
int,
        @start_date
datetime,
        @end_date
datetime,
        @project
nvarchar(50)
-- set them to some values for testing
SELECT
        @empno
= 1,
        @start_date
= '10/01/2009',
        @end_date
= '10/04/2009',
        @project
= 'abc'

-- this is used by the loop
DECLARE @working_date datetime
SET @working_date = @start_date
WHILE @working_date < @end_dateBEGIN
       
INSERT
                MyTable
               
(
                empno
,
               
[date],
                project
               
)
       
SELECT
                @empno
,
                @working_date
,
                @project

       
SET @working_date = DATEADD(d, 1, @working_date)
EN

How To Export Gridview into Excel


protected void btnexcel_Click(object sender, EventArgs e)
{
BindGridView();
this.GridView1.AllowPaging = false;
this.GridView1.DataBind();
Export("Result.xls", this.GridView1);

}


public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
table.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}


private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}

Using SQL Server to collect information from your Oracle server

Using SQL Server to collect information from your Oracle server


How many DBA's out there have to manage Microsoft SQL Server instances and Oracle database servers? More than you think, and I am one of them. Just over a year ago one of our departments wanted to purchase a very expensive product that only runs on an Oracle database. When the software was purchased; 2 Oracle DBAs were also hired. Then it started, and we were all asked to cross train each other on the two database systems.
On the SQL Server side I had created several reports to provide information on all our SQL Servers via a linked server connection. I decided to do the same and collect basically the same information from the Oracle servers. Here is a list of data I wanted to collect from Oracle.
  • Job Status Data
  • Current Error Information
  • Database ONLINE Status
  • Patch Data
  • Patch Set Data
To perform this task I first had to install the Oracle client (in this case it was for Oracle 10g) on the SQL server that will create the linked connection to the Oracle server. Without the client installed the link server parameter '@provider=' would not work as the Microsoft provided Oracle driver does not work properly. Even Microsoft recommends using the Oracle client. So make sure you install the Oracle client. If you are using a 64bit server just install the 32bit client as the 64 bit client may cause issues. I never did find out why this is the case.
Once installed you can open up the SQL Server Management Studio (SSMS) and create a link connection from your SQL server to your Oracle server. This link can be created by the GUI (see Books On Line) or with the script below.
Note: You must replace 'ORACLESRV1' with the name of your Oracle server. Also you need to change the user name 'REPORTS_USER' and provide its password 'PASSWORD'. Once complete you can execute this code. The user and password are the credentials you have created on the Oracle server. Ensure that the login has the rights to the VIEWs on SYSMAN.MGMT$*
PRINT 'Creating Oracle link connection...'
PRINT ' '
EXEC master.dbo.sp_addlinkedserver @server = N'ORACLESRV1', @srvproduct=N'Oracle', @provider=N'OraOLEDB.Oracle', @datasrc=N'ORACLESP'
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'ORACLESRV1',@useself=N'False',@locallogin=NULL,@rmtuser=N'REPORTS_USER',@rmtpassword='PASSWORD' 
EXEC master.dbo.sp_serveroption @server=N'ORACLESRV1', @optname=N'collation compatible', @optvalue=N'true'
EXEC master.dbo.sp_serveroption @server=N'ORACLESRV1', @optname=N'data access', @optvalue=N'true'
EXEC master.dbo.sp_serveroption @server=N'ORACLESRV1', @optname=N'use remote collation', @optvalue=N'true' 
Now that you have created a linked connection to the Oracle server you can test this connection with the following script. It performs a SELECT against a system view on the Oracle server.
SELECT
[JOB_NAME], [JOB_OWNER], [JOB_TYPE], [SCHEDULED_TIME],
[START_TIME], [END_TIME], [STATUS], [TARGET_NAME],
[TARGET_TYPE]
FROM ORACLESRV1..[SYSMAN].[MGMT$JOB_EXECUTION_HISTORY] 
The information displayed is the execution history for jobs on your Oracle server. Neat! By querying other system views you can get a lot of information that is also displayed in the Oracle Enterprise Manager Web interface.
Now that your tests are good you should delete the linked connection with the script below.
IF EXISTS (SELECT srv.name FROM sys.servers srv WHERE srv.server_id != 0 AND srv.name = N'ORACLESRV1')EXEC master.dbo.sp_dropserver @server=N'ORACLESRV1', @droplogins='droplogins' 
This code will detect if the linked connection is there and delete it.
There you have it. You can now see and collect information regarding your Oracle server without using any Oracle tools. You can now collect the related information and display it in SQL Server Report Server (SSRS). The script provided will perform the following:
  1. Creates a database called: ORACLEREPORTS
  2. Creates permanent tables: tblOracleJobStats - Job statistics, tblOracleCurrErrors - Shows errors, tblOracleOnlinStatus - Show if databases are online, tblOraclePatches and tblOraclePatchSets - Show level of patches installed
  3. Creates a stored procedure called: sp_dba_Oracle_Status - This stored procedure will create a new link connection to your Oracle server, perform a TRUNCATE on your tables and then repopulated with several SELECT statements. You can add this stored procedure to a job to collect your data whenever you like. I run this on an hourly basis.
Once the script has executed you can just run the stored procedure to collect your information. Also you can create simple reports in SSRS to display the data. The completed SQL script is located in the Resources section below with additional notes within it.

open data source code..


SELECT * FROM
OPENDATASOURCE('SQLNCLI10','Data Source=192.168.25.25\sqlexpress;User ID=sa;Password=**********').Windata.dbo.tblinvoice order by 1 desc

XML TO SQL SERVER


If you’ve got some XML data in a SQL Server column, how can you flatten it out and query it or present it as though it was relational data? It turns out this is quite easy...
Setup
Let’s create a simple table to hold our data;
CREATE TABLE XmlSourceTable
(
RecordId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
XmlData XML NOT NULL
)
GO
And we’ll define some straightforward XML to import;
xml version="1.0" ?>
<Root>
<Person>
<Name>SimonName>
<Age>20Age>
<Skills>
<Skill>CookingSkill>
<Skill>CleaningSkill>
Skills>
Person>
<Person>
<Name>PeterName>
<Age>21Age>
<Skills>
<Skill>IroningSkill>
Skills>
Person>
Root>
Ages may have been changed to protect the innocent J
Next, we’ll import it into my table using one of the mechanisms SQL Server provides – each XML file will be imported into a single row in the target table.
INSERT INTO XmlSourceTable(XmlData)
SELECT *
FROM OPENROWSET(
BULK 'C:\XmlSource.xml', SINGLE_BLOB)
AS ImportSource
GO
After this, if we do a quick query...
SELECT * FROM XmlSourceTable
... we can see that we get a single row back containing an ID and some XML;
RecordId XmlData
----------- -------
1 Simon20
(1 row(s) affected)
Queries
The simplest way to extract this data is to use the CROSS APPLY keyword, as this executes a function against each row and then adds the returned data to the result set. Combining this with a method that can be called on the XML data type called nodes, we get some great results. A quick query like this;
SELECT
pref.value('(Name/text())[1]', 'varchar(50)') as PersonName,
pref.value('(Age/text())[1]', 'int') as PersonAge,
pref.query('Skills') as PersonSkills
FROM
XmlSourceTable CROSS APPLY
XmlData.nodes('/Root/Person') AS People(pref)
GO
... yields a completely different result set to our last query;
PersonName PersonAge PersonSkills
---------- --------- ----------------------
Simon 20 Cooking
Peter 21 Ironing
(2 row(s) affected)
We can see this query has flattened my single row of relational data with embedded hierarchical XML into two rows and columns of relational data. I’ve also included a subset of the XML as a column, just to show I can! Of course, if I wanted to I could modify this to get a list of people and their skills;
SELECT
pref.value('(Name/text())[1]', 'varchar(50)') as PersonName,
sref.value('(text())[1]', 'varchar(50)') as PersonSkill
FROM
XmlSourceTable CROSS APPLY
XmlData.nodes('//Person') AS People(pref) CROSS APPLY
pref.nodes('Skills/Skill') AS Skill(sref)
GO
What is it Doing?
This SQL can be difficult to understand when you first look at it, but it isn’t really that complex. Breaking it down there are three key concepts that we’ll cover below – using my first query above that fetches PersonName, PersonAge, and PersonSkills as an example.
CROSS APPLY
The first concept is the use of CROSS APPLY, which many people haven’t used before. What this is doing is roughly equivalent to the following steps (note: this is my idiots guide to how I think about it, not a description of how the query optimiser does it);
1. Fetch the rows from the XmlSourceTable table.
2. For each row, call the “nodes” function on the XmlData column. This could be some other function too – it needn’t be on XML data. See the docs on APPLY for more info.
3. Duplicate the XmlSourceTable row once for every row returned by the table valued function “nodes”.
4. Add the columns returned by the “nodes” function to the columns in the result set.
5. Continue doing filtering, joining, and column selection as for any other SQL query.
I hope that makes it a little clearer.
nodes() function
The XML data type in SQL Server defines a number of methods that can be called on it. One of these is “nodes” – and what this does is basically select a list of XML nodes that match an XQuery expression. Knowing this, look at the statement in my SQL;
XmlData.nodes('/Root/Person') AS People(pref)
This is using the path “/Root/Person” to ensure that all Person nodes that exist under the Root are selected. The result is aliased as a table named People, and each resulting XML node will be output as a separate row, in the “pref” column.
Plenty of alternative syntaxes are available for selecting this list of nodes, and this really is the core of how to flatten out the XML. I’ve also used “//Skill” syntax in my second query, for example, which selects every Skill node found in the XML it is used on.
Other XML functions
The last concept is the use of the selector XML functions – in my example I’ve used “value()” and “query()”. Both of these use XQuery expressions to select XML data.
Firstly, I’ve used the value() function to extract a specific value from the XML, and convert it to a SQL Server data type;
pref.value('(Name/text())[1]', 'varchar(50)') as PersonName
The “text()” function here retrieves the inner text from within the XML “Name” node. The “[1]” suffix acts as an indexer, and fetches the first result matched. I know there’s only one name node per person, but I need to make sure SQL Server knows this too. Finally, the second argument is the data type it should be converted to. For an Age, I’ve used ‘int’, but here we’re converting to a varchar type.
The “query()” function allows me to return an XML fragment;
pref.query('Skills') as PersonSkills
This returns the XML that matches the “Skills” node, and is found underneath the current Person element held in “pref” (i.e. the search is relative to the contents of pref). This means it returns fragments such as;
Ironing
Conclusion
None of this is all that difficult once you know how – so I hope this has given you a quick start to using XML data in SQL! Don’t forget to read up more generally on the XML data type and XML indexes.