Tuesday, October 26, 2010

How To Create a New Login Name in SQL Server?

To create a new login name, you can use the "CREATE LOGIN" statement in a simple syntax like this:


CREATE LOGIN login_name WITH PASSWORD = 'password'  

How To List All Login Names on the Server?

If you want to see a list of all login names defined on the server, you can use the system view, sys.server_principals as shown in this tutorial exercise:


-- Login with sa    SELECT name, sid, type, type_desc FROM sys.server_principals  WHERE type = 'S';  

How To Change the Password of a Login Name?

If a developer lost the password of his or her login name, you can reset the password with the "ALTER LOGIN" statement as shown in this tutorial example:


-- Login with sa    ALTER LOGIN my_DBA WITH PASSWORD = 'mrurli222'; 

How To Change a Login Name?

If you want to change a login name, you can use the "ALTER LOGIN" statement as shown in this tutorial example:


-- Login with "sa"    -- Change login name  ALTER LOGIN Fyi_Login WITH NAME = Dba_Login;  

How To Disable a Login Name?

If you want temporarily disable a login name, you can use the "ALTER LOGIN" statement with a DISABLE keyword. If you want to enable it later on, you can use the ENABLE keyword. The tutorial exercise below shows how to disable and enable login name "Dba_Login":


-- Login with "sa"    -- Disable a login  ALTER LOGIN Fyi_Login DISABLE;    
-- View login status SELECT name, type, type_desc, is_disabled FROM sys.server_principals WHERE type = 'S';

How To Delete a Login Name?

If you don't want to keep a login name any more, you should delete it by using the "DROP LOGIN" statement as shown in this tutorial example:


-- Login with "sa"    DROP LOGIN Dba_Login;  

How To Create a User Name in a Database?

User names are security principals at the database level. If you want to allow a login name to access a specific database, you need to create a user name in that database and link it to the login name.


Creating a user name can be done by using the "CREATE USER" statement as shown in this tutorial exercise:


-- Login with "sa"    -- Create a login  CREATE LOGIN Fyi_Login WITH PASSWORD = 'IYF'  GO    -- Select a database  USE FyiCenterData;  GO    -- Create a user and link it to a login  CREATE USER Fyi_User FOR LOGIN Fyi_Login;  GO  

Login name "Fyi_Login" should be able to access database "FyiCenterData" through user name "Fyi_User".


How To List All User Names in a Database?

If you want to see a list of all user names defined in a database, you can use the system view, sys.database_principals as shown in this tutorial exercise:


-- Login with sa    -- Select a database  USE FyiCenterData;  GO    -- List all user names  SELECT name, sid, type, type_desc      FROM sys.database_principals WHERE type = 'S';  

How To Delete an Existing Database User?

If you don't want to keep a database user any more, you should delete the user by using the "DROP USER" statement. This tutorial exercise shows how to delete "Dba_User":


-- Login with "sa"    USE FyiCenterData;  GO    DROP USER Dba_User;  

Stored procedure execution on SQL Server startup

I have studied a very interesting topic in SQL Server and wish to blog the same in my site.
Scenario:
On each SQL Server database startup, I need to execute a procedure in my database. It's a very basicscenario in all places.


Solution:


For this, SQL Server is providing an option of using a system stored procedure sp_procoption


create procedure Murli_Insert_Procedure

as

begin

insert into tblMurli(id,val) values (5,'F')

end

EXEC sp_procoption @ProcName = 'Murli_Insert_Procedure',@OptionName = 'startup',@OptionValue = 'true'

Now, your stored procedure is set as a initial startup which will execute on DB start.

Temporary table Vs Temporary variable in SQL Server

We have seen lot of difference between temporary variable and temporary table. Here is a nice difference in Transaction perspective.

Temporary table is transaction dependent and it abides to the database transaction whereas temporary variable is not transaction bound.


Sample Query:

---------------------Temporary table -------------------------------


drop table #temp

create table #temp (id int, val varchar(100))

begin tran ins

insert into #temp values (1,'Venkat')

rollback tran ins

select * from #temp

We are not getting any records indicating the temporary table will bound to the transaction strategies.


------------------Temporary variable --------------------------


Declare @tempval table(id int, val varchar(100))

begin tran ins

insert into @tempval values (1,'Venkat')

rollback tran ins

select * from @tempval

Even we have provided rollback transaction. Records are available in the table variable.

list column names for a table

To list the column names for a table:

In SQL Server, we can retrieve these details by two methods.

1. This can be taken from the sys.objects and sys.columns table (Used in SQL Server 2000 and higher versions).
2. Another option is to use INFORMATION_SCHEMA.COLUMNS (This is introduced in SQL Server 2005 and higher version)


Below is the query to achieve the same,

drop table venkat_table
go
create table venkat_table (id int,val varchar(100),val1 varchar(100))

First Option:

SELECT *FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='venkat_table'

Second Option:

Joining sys.objects and sys.columns table based on the object Id.

SELECT C.name,O.* FROM sys.objects O INNER JOIN sys.columns CON O.object_id=C.object_id WHERE O.name='venkat_table'

View Log file information in SQL Server

Scenario:

Usually, we will face log space issue in our SQL Server. Most of the time, we dont know the reason for our logfile space. I would suggest to get a third party tool to check it. By reading through some of the forums. I found there is some undocumented DBCC command which is used to dig the log file and get some information to us.

This command won't give a very great information at least we can get some high level information. Let's see the command,
DBCC Log(Databasename, Option number)

Default option number is 0

For instance,

dbcc log ('master',0) - 0 indicates a very minimal information.

The above command will provide the below details,

Reindexing the entire database in sql server

Re-indexing the entire database:

Usually, if the database is too slow. DBA's were advised to re-index the tables. For some cases, we need to rebuild the indexes availables in the entire database.

For this scenario, we can rebuild the index by taking each table and re-index all the indexes associated with each table.

Fill factor:

Amount or compactness of data in the leaf level is defined by the term fill factor. Based on the operations on the database DBA's will decide the fill factor. If the insert/update/delete are very high in that case we will have very less fill factor (Around 60 to 70). If there is very less insert/update/delete, in that case we will have very high fill factor (Around 90). On an average, we will give 80 -90 %.



Below is the script to achieve this,

----------------------------------------------------------------------------
DECLARE @DatabaseTable VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT name AS DatabaseTable
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @DatabaseTable
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'DBCC DBREINDEX('+ @DatabaseTable + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @DatabaseTable
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO


-------------------------------------------------------------

How abt re-organsing the indexes (Rebuild index vs reorganise index):

1. Re-built can't be done on the production run time (Due to its high impact on rearranging the data and recreate of index) where as re-organise index can be done.

2. Indexes were recreated in case of re-building the index.

3. Re-built index is very effective when compared to the other.


To find the free space available in the log files:

Below is the command used to identify the amount the space available or percentage used.

DBCC SQLPERF (LOGSPACE)

Reindexing the entire database in sql server

Re-indexing the entire database:

Usually, if the database is too slow. DBA's were advised to re-index the tables. For some cases, we need to rebuild the indexes availables in the entire database.

For this scenario, we can rebuild the index by taking each table and re-index all the indexes associated with each table.

Fill factor:

Amount or compactness of data in the leaf level is defined by the term fill factor. Based on the operations on the database DBA's will decide the fill factor. If the insert/update/delete are very high in that case we will have very less fill factor (Around 60 to 70). If there is very less insert/update/delete, in that case we will have very high fill factor (Around 90). On an average, we will give 80 -90 %.



Below is the script to achieve this,

----------------------------------------------------------------------------
DECLARE @DatabaseTable VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT name AS DatabaseTable
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @DatabaseTable
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'DBCC DBREINDEX('+ @DatabaseTable + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @DatabaseTable
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO


-------------------------------------------------------------

How abt re-organsing the indexes (Rebuild index vs reorganise index):

1. Re-built can't be done on the production run time (Due to its high impact on rearranging the data and recreate of index) where as re-organise index can be done.

2. Indexes were recreated in case of re-building the index.

3. Re-built index is very effective when compared to the other.


To find the free space available in the log files:

Below is the command used to identify the amount the space available or percentage used.

DBCC SQLPERF (LOGSPACE)

Performance monitoring command in SQL Server

DBCC SQLPERF(umsstats) - This command will provide all the OS related information for your threads in the SQL Server instance. It provides the below values,

Node Id
Avg Sched
LoadSched
SwitchesSched Pass
IO Comp Passes
Scheduler ID (The below data will be populated for each scheduler ID)
online - Whether it's online or not
num tasks - Number of tasks
num runnable - Runnable tasks
num workers - Parallel workers involved in the scheduler
active workers - Active parallel workers involved in the scheduler
work queued - Works queued up in this schedule
cntxt switches - How many context switching happening in this schedule
cntxt switches(idle) - Idle threads after context switches.
preemptive switches - Prirority switches happened in this schedule.

Get details on the table contigencies

DBCC Showcontig will give a detailed insight on the data pages(OS level) for the tables.

This command will scan the table and provide the below details,

- Pages Scanned......................... - Number of pages scanned (Denotes the number of pages occupied by this table )
- Extents Scanned..............................: Number of Extents scanned (Denotes the number of Extents occupied by this table )
- Extent Switches..............................: Mixed extents
- Avg. Pages per Extent........................
- Scan Density [Best Count:Actual Count].......: How the data is compacted in the page.
- Extent Scan Fragmentation ...................: Fragmentation from Extent point of view
- Avg. Bytes Free per Page.....................
- Avg. Page Density (full) ...................... (High page density denotes the data is intact and your search will be faster. If the value is less, it indicates your data is scattered.

DBCC SHOWCONTIG --- This command will provide the details for the whole database tables.

DBCC SHOWCONTIG ('Murli_table') -- This command will provide the necessary information for that particular table.

Get Databasename from Database ID in SQL Server

DB_Name(DB_ID) will provide you the database name. The hierarchy is like system tables will have the initial values followed by user databases.

select DB_NAME(1) --- returns Master database
select DB_NAME(2)--- returns Tempdb database
select DB_NAME(3)--- returns Model database
select DB_NAME(4)--- returns MSDB database
select DB_NAME(5)--- returns User database1 etc..,

To find recently executed queries in SQL Server

To find recently executed queries,

Select dmStats.last_execution_time as 'Last Executed Time',dmText.text as 'Executed Query' from sys.dm_exec_query_stats as dmStats Cross apply sys.dm_exec_sql_text(dmStats.sql_handle) as dmText Order By
dmStats.last_execution_time desc

Monday, October 25, 2010

Update records form diff tables

This blog post illustrates how to update more than one column in a table with values from columns in another table and explains how to do it in the three RDBMS that we support.

Table Structures and values:

TableA has four columns: a, b, c, d (a is the primary key column)
TableB has five columns: a1, b1, c1, d1, e1 (a1 and b1 together constitute the primary key for this table)

The foreign key relationship between the two tables is based on A.a = B.a1

The data in these 2 tables is as follows:


I. TableA
a b c d
1 x y z
2 a b c
3 t x z

II. TableB
a1 b1 c1 d1 e1
1 x1 y1 z1 40
2 a1 b1 c1 50



The requirement is to write a SQL to update columns b, c and d in TableA from the columns b1, c1 and d1 from TableB where-ever the join condition satisfies and e1 > 40 in TABLEB.

Oracle:

UPDATE TABLEA
SET (b, c, d) = (SELECT b1, c1, d1 from TABLEB WHERE TABLEB.a1 = TABLEA.a and TABLEB.e1 > 40)
WHERE EXISTS (SELECT 1 from TABLEB WHERE TABLEB.a1 = TABLEA.a and TABLEB.e1 > 40)
/


Results after the update:

a b c d
————————————
1 x y z
2 a1 b1 c1
3 t x z



SQL Server:

UPDATE TABLEA
SET b = TABLEB.b1,
c = TABLEB.c1,
d = TABLEB.d1
FROM TABLEA, TABLEB
WHERE TABLEA.a = TABLEB.a1
AND TABLEB.e1 > 40
GO

Note: This is an extension in SQL Server i.e. the FROM clause – it does make it simple to understand and is a nice feature.




Results after the update:

a b c d
————————————
1 x y z
2 a1 b1 c1
3 t x z



DB2 LUW:

–Same as Oracle–

UPDATE TABLEA
SET (b, c, d) = (SELECT b1, c1, d1 from TABLEB WHERE TABLEB.a1 = TABLEA.a and TABLEB.e1 > 40)
WHERE EXISTS (SELECT 1 from TABLEB WHERE TABLEB.a1 = TABLEA.a and TABLEB.e1 > 40);



Results after the update:

a b c d
————————————
1 x y z
2 a1 b1 c1
3 t x z



NOTE:

It is very important to make sure that your where clause for the update statement is correct since that is what identifies the records that the update statement is going to qualify and do the update upon. If it is incorrect, then you can get wrong results. The reason I am mentioning this is because I have seen people write wrong where clauses and then wondering what went wrong because they specified the correct condition in the SET clause.

In the above example, if the Where condition was omitted, the other record’s columns would be updated to NULL value and this will be the final result set:


a b c d
————————————
1 Null Null Null
2 a1 b1 c1
3 Null Null Null

Configure SQL Server to Store ASP.NET Session State

For configure the Sql Server session state you must need to follow these steps first :-
1. First you need to execute script file i.e. InstallSqlState.sql and this script file automatically create database and required procedure to stores the session values
Note:- While execution of script it gives an error like "The specified @name ('[Uncategorized (Local)]') already exists" ignore this error
Note:- This InstallSqlState.sql you can get it from your pc it's in your windows folder dir Ex : C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322

2. You need to set the connection string in your configuration file ex:-
< mode="SQLServer" sqlConnectionString="data source=INDIGO62\SQLEXPRESS2008;user id=sa;password=murli" cookieless="false" timeout="20" />

Now you can access session objects as you used in In Proc state same as use here
Ex : Session["Name"] = "Murli";

For testing the records are in available or not in your database
check two tables ASPStateTempApplications and ASPStateTempSessions
in your tempdb database

for start world wide web publishing dir type this command in command prompt
net start w3svc
for strop this
net stop w3svc

Friday, October 22, 2010

Access Viewstate from another page

Yes, we can access the viewstate variables across pages. This is only possible if Cross Page Posting or Server.transfer is used to redirect the user to other page. If Response.redirect is used, then ViewState cannot be accessed across pages.

Before you continue reading this article, please read these articles on Cross Page Posting and Server.transfer.

Ok, so all set now... I will demonstrate this using the demo created by me. You can download the demo from the link at the top of this article.

I have created two *.aspx pages named:

1. ViewStateContainer.aspx: This page sets the ViewState variable and transfers the user to another page using Server.transfer.
2. AccessViewState.aspx: This page accesses the ViewState variable of ViewStateContainer.aspx page.

This is the code of ViewStateContainer.aspx page:
?

public partial class ViewStateContainer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ViewState["Page1"] = "Page1 ViewState";
Server.Transfer("AccessViewState.aspx");
}

public StateBag ReturnViewState()
{
return ViewState;
}
}

As you can see, I have set a ViewState variable in Page Load and transfer the user to AccessViewState.aspx page using the Server.transfer() method.

This page also contains a method ReturnViewState() which actually returns the ViewState of this page to the calling function. The return type of the method is StateBag class.

StateBag class: This class is the primary storage mechanism for all HTML and Web server controls. It stores attribute/value pairs as strings associated with the control. It tracks changes to these attributes only after the OnInit method is executed for a page request, and saves the changes to the page's or control's viewstate.

Now let's take look at AccessViewState.aspx Page code:
?


public partial class AccessViewState : System.Web.UI.Page
{
private StateBag PreviousPageViewState
{
get
{
StateBag returnValue = null;
if (PreviousPage != null)
{
Object objPreviousPage = (Object)PreviousPage;
MethodInfo objMethod = objPreviousPage.GetType().GetMethod ("ReturnViewState");
return (StateBag)objMethod.Invoke(objPreviousPage, null);
}
return returnValue;
}
}

protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
if (PreviousPageViewState != null)
{
Label1.Text = PreviousPageViewState["Page1"].ToString();
}
}
}
}

Whenever we use Server.transfer or Cross Page Posting, We can get the previous page object via PreviousPage property. Using Previous Page, we can find the controls of the previous page. For example, one can access Label control placed in ViewStateContainer Page in current Page.

Looking at the code, I have created a PreviousPageViewState property in this page, which returns the previous page's ViewState. It first checks whether PreviousPage is null or not, if it's not null, then it creates an object of the previous page. Now using Reflection, we can invoke the method of the previous class. Using MethodInfo class, I have invoked the ReturnViewState() method of ViewStateContainer Page.

In Page_Load event, I am able to access the ViewState variable of ViewStateContainer Page. You can access all the viewstate variables set in ViewStateContainer Page.

Thursday, October 21, 2010

Find Postback Control ID in Asp.net c#


string controlID = Page.Request.Params["__EVENTTARGET"];
Control postbackControl = null;
if (controlID != null && controlID != String.Empty)
{
postbackControl = Page.FindControl(controlID);
}
else
{
foreach (string ctrl in Page.Request.Form)
{ //Check if Image Button
if (ctrl.EndsWith(".x") || ctrl.EndsWith(".y"))
{
postbackControl = Page.FindControl(ctrl.Substring(0, ctrl.Length - 2));
break;
}
else
{
postbackControl = Page.FindControl(ctrl);
//Check if Button control
if (postbackControl is Button)
{
break;
}
}
}
}
Response.Write(postbackControl.ID);

Sort values in XSL

Distinct Year

<xsl:key name="distinctYear" match="state/elements/element[@type='Custom']/content" use="substring(date,7,10)"></xsl:key>

I have used three attributes here i.e.
1. name :- this is a key name which will use further.
2. match :- this is the route of content data
3. use :- this is attrubute value / name which we want to sort

<select id="ddYear" name="ddYear" onchange="javascript:fnOnchange()">
<xsl:for-each select="state/elements/element[@type='Custom']/content[generate-id() = generate-id(key('distinctYear', substring(date,7,10)))]">
<xsl:sort select="substring(date,7,10)" data-type="number" order="ascending" />
<option>
<xsl:value-of select="substring(date,7,10)"/>
</option>
</xsl:for-each>
</select>

here i used for-each loop to find all elements with distinct values

ex:-
generate-id() :- The generate-id() function returns a string value that uniquely identifies a specified node.
key(Param1,Param2) :- Param1 :- this is key name which assigned
Param2 :- this is the string value which want to be destinected

Monday, October 18, 2010

Import Excel Spreadsheet Data into SQL Server Database Table Using SqlBulkCopy

Using SqlBulkCopy to Import Excel Spreadsheet Data into SQL Server

Let's take an Excel Workbook with a worksheet, called Data, that contains 1000 rows of nonsense data broken into 2 columns, ID and Data.

I want to copy this data into a SQL Server Database Table, called ExcelData, with the same schema.

Just a little bit of code transfers the data from the Excel Spreadsheet into the SQL Server Database Table:

// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft
.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended
Properties=""Excel 8.0;HDR=YES;""";

// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select ID,Data FROM [Data$]", connection);

connection.Open();

// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=.;
Initial Catalog=Test;Integrated Security=True";

// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelData";
bulkCopy.WriteToServer(dr);
}
}
}

GridView Row Edit, Delete and Update

In this Post I am going to explain a simple light weight GridView Edit, Delete, and Update functionality. We are going to apply this functionality on Northwind Database, Employee table.

Following are the screen shots.

normal-vieweditmodeview

First of all I am going to explain about creating a Connection String.Connection String has mainly 3 properties.
DataSource — DataSource is your SQL Server name.
Initial Catalog
— Your Database name (Northwind in this case).
Integrated Security
– True

Integrated Security will access the SQL Server with the current windows identity established on the Operating System. For more information about Integrated Security refer this. We usually place the connection string in the Web.config file under “Configuration ==> ConnectionStrings” section.

Here is my connection string.


<connectionStrings>
<add name=“NorthwindConnectionString“ connectionString=“Data Source=*****(SQL Server Name);Initial Catalog=NorthWind;Integrated Security=True;“/>
</connectionStrings>

To learn more about different type of connection strings refer this.

Then, after we are done with your connection string in the Web.config file let’s move on to the C# code.

The Following Snippet is to bind GridView.
private void BindGridData() {
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))

{

conn.Open();

using (SqlCommand comm = new SqlCommand(“select E.EmployeeID,E.FirstName,E.LastName,E.Title,E.Country from Employees E”, conn))

{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}

The First Line using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources. Refer this for Complete Reference.

The following is how we write asp.net GridView web server control code in aspx page. I guess most of the people will be aware of the GridView events. For complete Reference refer this.

In the Code you can see I put AutoGenerateColumns=”false”. That means I have to write column names whatever I want to show to the user. If we put AutoGenerateColumns=”True”, that means u don’t have to write any custom code on your page and user can see each and every column in your dataset or datatable whatever you are binding to your gridview.

It is always good to have some control on these instead of giving up everything to it. I want to hide EmployeeID for the user. But I need it for querying the databse while updating and deleting the user stuff. So

How can we hide a column in a GridView and access it in the Code behind ?

We can do this in several ways!!! , But depends on what column we want to hide. I always follow this method.

Writing a Template Field and making it invisible. In the template field I will Place a label or some controls, So that it’s very easy to access those controls in the code behind by using FindControl method.

Suppose if we are trying to hide primary key of our table, there is actually no need to hide. GridView has a Property called DataKeyNames. We have to give our primary key column name to it. It will do the rest. we can see how we can access that in the code behind in the GridView_Rowupdating Event which I am going to explain later part of this article.

What is TemplateField, ItemTemplate, and EditItemTemplate?

We will use Template Field, whenever we want to define some custom control in the data bound controls like GridView, DataGrid or DataRepeater.

ItemTemplate is the content to display for the items in the TemplateField.

EditItemTemplate as the name itself it is the content to display for the items in the TemplateField when it is in Edit mode. Refer this for complete reference.

Take this simple Snippet.

<asp:TemplateField HeaderText=”LastName”>
<ItemTemplate>
<asp:Label runat=”server” ID=”LastName” Text=’<%#Eval(“LastName”) %>‘ />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtLastName” Text=’<%#Eval(“LastName”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdLastName” ControlToValidate=”txtLastName” ValidationGroup=”var1″ ErrorMessage=”*” />
</EditItemTemplate>
</asp:TemplateField>

In the above Snippet you are seeing a label in Item Template that means whenever we are showing GridView to the user Label will be visible to the user. If he clicks edit (or) in the edit mode he can be able to see the Textbox.

<asp:BoundField HeaderText=”FirstName” DataField=”FirstName” ReadOnly=”false”/>

The above piece of code will also do the same as label in ItemTemplate and Textbox in the EditItemTemplate. By default all the boundfields will be trasferred as Textboxes in Edit Mode. To avoid this we need to keep the property ReadOnly as false, Then in the edit mode nothing will happenes. It just visible like a label.

The reason I use TemplateField instead of BoundField is that, it is very easy to grab those controls in the codebehind if we user labels or textboxes. In case of the bound field’s we need to check what column it is and need to use index of that cloumn, which is little hard and even in future if we change the column order we have to change the code too.

<asp:GridView ID=”GridView1″ runat=”server” GridLines=”None” AutoGenerateColumns=”false” AlternatingRowStyle-BackColor=”#EEEEEE” EditRowStyle-BorderColor=”Red” onrowcancelingedit=”GridView1_RowCancelling” onrowcommand=”GridView1_RowCommand” onrowdeleting=”GridView1_RowDeleting” onrowediting=”GridView1_RowEditing” onrowupdating=”GridView1_RowUpdating” DataKeyNames=”EmployeeID”>

<Columns>

<asp:TemplateField Visible=”false” HeaderText=”EmployeeID”> <ItemTemplate>

<asp:Label runat=”server” ID=”EmployeeID” Text=’<%#Eval(“EmployeeID”)%>‘ />

</ItemTemplate>

</asp:TemplateField>

<%–<asp:BoundField HeaderText=”FirstName” DataField=”FirstName” />–%>

<asp:TemplateField HeaderText=”LastName”>
<ItemTemplate>
<asp:Label runat=”server” ID=”LastName” Text=’<%#Eval(“LastName”) %>‘ />
</ItemTemplate>

<EditItemTemplate>

<asp:TextBox runat=”server” ID=”txtLastName” Text=’<%#Eval(“LastName”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdLastName” ControlToValidate=”txtLastName” ValidationGroup=”var1″ ErrorMessage=”*” />

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText=”Title”>

<ItemTemplate>
<asp:Label runat=”server” ID=”Title” Text=’<%#Eval(“Title”) %>‘ />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtTitle” Text=’<%#Eval(“Title”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdTitle” ControlToValidate=”txtTitle” ValidationGroup=”var1″ ErrorMessage=”*” /> </EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText=”Country”>

<ItemTemplate>

<asp:Label runat=”server” ID=”Country” Text=’<%#Eval(“Country”) %>‘ />

</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtCountry” Text=’<%#Eval(“Country”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdCountry” ControlToValidate=”txtCountry” ValidationGroup=”var1″ ErrorMessage=”*” />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Action”>
<ItemTemplate>
<asp:LinkButton ID=”btnEdit” Text=”Edit” runat=”server” CommandName=”Edit” /> <br />
<asp:LinkButton ID=”btnDelete” Text=”Delete” runat=”server” CommandName=”Delete” />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID=”btnUpdate” Text=”Update” runat=”server” CommandName=”Update” />
<asp:LinkButton ID=”btnCancel” Text=”Cancel” runat=”server” CommandName=”Cancel” />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

If you see the Last TemplateField part in the above code, I am using the link buttons for edit, update, delete and cancel. May be you may think why am I using link buttons as we are provided with some command field buttons by GridView.

1) If we use command buttons we have less control on them while doing validations, i.e. while assigning validation groups.

2) Secondly if you want to include a custom field (some button or link) in the same column it’s not possible.

If we use proper command names for the buttons like “EDIT”, “DELETE”, “UPDATE”, “CANCEL” these will also trigger the appropriate GridView Events.

Ok let’s move on to Code behind what we have to do when user clicks Edit, Delete, Update and Cancel

When we click on Edit the OnRowEditing event will be fired. You can see the C# code below

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridData();
}

In the above code snippet as you see GridViewEditEventArgs will give the row number whatever you are editing by NewEditIndex property. So GridView will put the appropriate row into the Edit Mode by assigning row number to its EditIndex property. Then again we have to call that BindGridData () method to bind data for the textboxes.

So once after done with editing data, if we click update the following method will be triggered. It will call OnRowUpdating Event.

1) The First line is to get the Primary Key of the table using DataKeyNames Property of GridView.

2) The Second line is to access the value of the invisible column.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();
Label EmployeeID = GridView1.Rows[e.RowIndex].FindControl(“EmployeeID”) as Label; TextBox LastName = GridView1.Rows[e.RowIndex].FindControl(“txtLastName”) as TextBox; TextBox Title = GridView1.Rows[e.RowIndex].FindControl(“txtTitle”) as TextBox;
TextBox Country = GridView1.Rows[e.RowIndex].FindControl(“txtCountry”) as TextBox; String UpdateQuery = string.Format(“UPDATE Employees SET LastName=’{0}’, Title=’{1}’,Country=’{2}’ WHERE EmployeeID = {3}”,LastName.Text, Title.Text,Country.Text, Convert.ToInt32(EmployeeID.Text));

GridView1.EditIndex = -1;

BindGridData(UpdateQuery);

}

Once we access the required fields in the code behind, we need to update the data in the database and show the updated data to the user. So am calling the method BindGridData method which is overloaded . I am passing Update Query as a parameter to it. You can see that method in the following snippet.

private void BindGridData(string Query)

{

string connectionstring = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(Query + “;select E.EmployeeID,E.FirstName,E.LastName,E.Title,E.Country from Employees E”, conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}

If the user click cancels the following event (OnRowCancelling) will be fired. When you are setting the value of the EditIndex to -1 that means you are exiting from the editmode. So i.e. when user clicks cancel, here we are exiting from the editmode and rebinding the data to the GridView by calling BindGridData method.

protected void GridView1_RowCancelling(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridData();
}

If the user clicks the Delete button OnRowDeleting event will be fired. The following is the code for that event. Going into that code we are trying to get the primary key of the employee table(EmployeeID) by using GridView DataKeyNames and then pass the Query to the BindGridData method to bind the updated data to the GridView.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string EmployeeID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string Query = “delete Employee where Employee.EmployeeID = “ + EmployeeID;
BindGridData(Query);
}

Happy Coding .

Friday, October 8, 2010

Validation Expressions

Metacharacter Match
\ the escape character - used to find an instance of a metacharacter like a period, brackets, etc.
. (period) match any character except newline
x match any instance of x
^x match any character except x
[x] match any instance of x in the bracketed range - [abxyz] will match any instance of a, b, x, y, or z
| (pipe) an OR operator - [x|y] will match an instance of x or y
() used to group sequences of characters or matches
{} used to define numeric quantifiers
{x} match must occur exactly x times
{x,} match must occur at least x times
{x,y} match must occur at least x times, but no more than y times
? preceding match is optional or one only, same as {0,1}
* find 0 or more of preceding match, same as {0,}
+ find 1 or more of preceding match, same as {1,}
^ match the beginning of the line
$ match the end of a line
POSIX Class Match
[:alnum:] alphabetic and numeric characters
[:alpha:] alphabetic characters
[:blank:] space and tab
[:cntrl:] control characters
[:digit:] digits
[:graph:] non-blank (not spaces and control characters)
[:lower:] lowercase alphabetic characters
[:print:] any printable characters
[:punct:] punctuation characters
[:space:] all whitespace characters (includes [:blank:], newline, carriage return)
[:upper:] uppercase alphabetic characters
[:xdigit:] digits allowed in a hexadecimal number (i.e. 0-9, a-f, A-F)

Character class Match
\d matches a digit, same as [0-9]
\D matches a non-digit, same as [^0-9]
\s matches a whitespace character (space, tab, newline, etc.)
\S matches a non-whitespace character
\w matches a word character
\W matches a non-word character
\b matches a word-boundary (NOTE: within a class, matches a backspace)
\B matches a non-wordboundary

  • \
    The backslash escapes any character and can therefore be used to force characters to be matched as literals instead of being treated as characters with special meaning. For example, '\[' matches '[' and '\\' matches '\'.
  • .
    A dot matches any character. For example, 'go.d' matches 'gold' and 'good'.
  • { }
    {n} ... Match exactly n times
    {n,} ... Match at least n times
    {n,m} ... Match at least n but not more than m times
  • [ ]
    A string enclosed in square brackets matches any character in that string, but no others. For example, '[xyz]' matches only 'x', 'y', or 'z', a range of characters may be specified by two characters separated by '-'. Note that '[a-z]' matches alphabetic characters, while '[z-a]' never matches.
  • [-]
    A hyphen within the brackets signifies a range of characters. For example, [b-o] matches any character from b through o.
  • |
    A vertical bar matches either expression on either side of the vertical bar. For example, bar|car will match either bar or car.
  • *
    An asterisk after a string matches any number of occurrences of that string, including zero characters. For example, bo* matches: bo, boo and booo but not b.
  • +
    A plus sign after a string matches any number of occurrences of that string, except zero characters. For example, bo+ matches: boo, and booo, but not bo or be.
  • \d+
    matches all numbers with one or more digits
  • \d*
    matches all numbers with zero or more digits
  • \w+
    matches all words with one or more characters containing a-z, A-Z and 0-9. \w+ will find title, border, width etc. Please note that \w matches only numbers and characters (a-z, A-Z, 0-9) lower than ordinal value 128.
  • [a-zA-Z\xA1-\xFF]+
    matches all words with one or more characters containing a-z, A-Z and characters larger than ordinal value 161 (eg. ä or Ü). If you want to find words with numbers, then add 0-9 to the expression: [0-9a-zA-Z\xA1-\xFF]+



Typical examples

  • (bo*)
    will find "bo", "boo", "bot", but not "b"
  • (bx+)
    will find "bxxxxxxxx", "bxx", but not "bx" or "be"
  • (\d+)
    will find all numbers
  • (\d+ visitors)
    will find "3 visitors" or "243234 visitors" or "2763816 visitors"
  • (\d+ of \d+ messages)
    will find "2 of 1200 messages" or "1 of 10 messages"
  • (\d+ of \d+ messages)
    will filter everything from the last occurrence of "2 of 1200 messages" or "1 of 10 messages" to the end of the page
  • (MyText.{0,20})
    will find "MyText" and the next 20 characters after "MyText"
  • (\d\d.\d\d.\d\d\d\d)
    will find date-strings with format 99.99.9999 or 99-99-9999 (the dot in the regex matches any character)
  • (\d\d\.\d\d\.\d\d\d\d)
    will find date-strings with format 99.99.9999
  • (([_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+))
    will find all e-mail addresses

Thursday, October 7, 2010

How to get virtual path from physical path in ASP.NET?

Let's do the opposite of what Server.MapPath does. Is not so hard. Just a c# method and 4 lines of code.


We all know that in ASP.NET the method Server.MapPath give us the physical path given a virtual path, right? Now, you might need to do just the opposite… why not? I googled a lot on this, but found no suitable and/or pretty solution so I just coded this method in c# (yes, I love C#). It works fine for me, hope you can find it useful too.

public string GetVirtualPath(string physicalPath)
{
string rootpath = Server.MapPath("~/");
physicalPath = physicalPath.Replace(rootpath,
"");
physicalPath = physicalPath.Replace(
"\\", "/");
return "~/" + physicalPath;
}

Converting this C# method to VB.NET is quite easy, so no need for that.

Partial Class

Visual Studio .NET 2005, ASP.NET 2.0, shipped with a lesser-known functionality called a “Partial Class”. A Partial class is a class defined in 2 or more files. Each source file contains a section of the class which will combine when the application is compiled.

In previous versions of Visual Studio classes are confined to a single file. It was not possible to split up a single class into multiple files. In order to split up a class we have to use the keyword “Partial”. The purpose of the Partial Class is to allow more than one programmer to write code for the same class, at the same time.

Example




In the above example, the Employee class is split into 2 parts. The first part defines the GetName() method, and the second part defines the GetAge() method. When you compile this program both parts will be combined and compiled.

The important point to remember is both sections use the keyword Partial and the public access modifier.

Points to considered on creating Partial Class

  • All the parts must use the partial keyword.
  • During compile time, all the parts should be available to form the final class.
  • All the parts should have the same access modifiers. – Public, Private, Protected and etc.,
  • Any member declared in the partial class is available to all other parts.
  • If any part is abstract, the entire class is abstract
  • If any part is sealed, then entire class is sealed.
  • If any part has Inheritance, then it applies to the entire class.
  • We can create the Partial Structs, Interfaces and methods in the same way as we create partial classes.
  • Different parts of the partial calls can inherit from different interfaces.

In the above example two parts are declared as public. In the following example we will create one part as abstract.


Output

If you create an object for the Employee class, you will get the following error:

“Cannot create an instance of the abstract class or interface Examples.Employee”.

This is because the second part is declared as abstract, so the whole class became abstract. Hence you cannot create an object.

We can create nested classes as partial class; even when the main class is not partial.

Important Points in Partial Method

  • Partial method declarations must begin with partial keyword.
  • The return type of the partial class should be void
  • Partial methods cannot have the out parameter, but can have the ref parameter.
  • Partial methods can be private but they cannot be virtual.
  • Partial classes cannot be extern.

Dynamically Add a Control to the Page From a User Control

Dear Friend,

actualy this can't be done this way, because at this stage the page has loaded all the controls to build and it can't be modiified at this point as per the error message,you can do the following:
1- in the control page_load function place this line

this.Page.LoadComplete+=new EventHandler(addcont); // adds a function to the vent handler to be done after the page completes the loading

2- add this function which is used in the event handler above inside your control :
public void addcont(Object obj, EventArgs e)

{
Label newlable = new Label();

newlable.Text = "TestText here";
newlable.BackColor = System.Drawing.Color.Red;this.Page.Form.Controls.Add(newlable);

}

inside this function write all the controls you want to add to the page, this here adds a lable with a red background, with some test text in it..

I hope this helps,

please do not forget to mark my post as answer if it helps...

have a nice day,

Create Table From Class Files With There Propertys/ Convert GenericList to DataTable

DataTable dt = GetDataTable(_PageInfo);

private DataTable GetDataTable(PageEntriesInfo _PageInfo)
{
var dt = new DataTable();

foreach (var Info in typeof(CustomElementInfo).GetProperties())
{
dt.Columns.Add(new DataColumn(Info.Name, Info.PropertyType));
}

foreach (var t in _PageInfo.CustomElements)
{
//CustomElements are SubCategory List
var row = dt.NewRow();
foreach (var Info in typeof(CustomElementInfo).GetProperties())
{
row[Info.Name] = Info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}

Monday, October 4, 2010

4 steps to increase bandwidth performance for ASPX pages on IIS 6.0

This article is a warm up for my 4th article on .NET best practices. The 4th article was coming out to be too big to accommodate everything. So I have broken down the same in to 2 pieces, this article will show the basic steps needed for that article and the main article will talk in depth about the best practice. In case you have not read my previous articles on best practices below are some links.

Step 1:- Enable compression

Step 2:- Enable metabase.xml edit

Step 3:- Set the compression level and extension types

Step 4:- Does it really work?

Introduction and warning

In this article we will try to understand how to enable compression on IIS 6.0. Once we have enabled compression we will use fiddler to see how bandwidth performance increases due to the same.

Please feel free to download my free 500 question and answer eBook which covers .NET , ASP.NET , SQL Server , WCF , WPF , WWF@ http://www.questpond.com .

Do not jump to a conclusion

As I have clearly mentioned this article will form the base for my 4th article on .NET best practices. So please do not jump to a conclusion and enable IIS compression on production servers. There are issues of CPU performance, compression levels and browser compatibility due to IIS compression enablement. I will be talking about those details later. For now we will just concentrate on how to enable IIS compression and how does it increase bandwidth performance.

Step 1:- Enable compression

The first step is to enable compression on IIS. So right click on websites ? properties and click on the service tab. To enable compression we need to check the below two text boxes from the service tab of IIS website properties. Below figure shows the location of both the checkboxes.

Step 2:- Enable metabase.xml edit

Metadata for IIS comes from ‘Metabase.xml’ which is located at “%windir%\system32\inetsrv\”. In order that compression works properly we need to make some changes to this XML file. In order to make changes to this XML file we need to direct IIS to gives us edit rights. So right click on your IIS server root ? go to properties and check ‘enable direct metabase edit’ check box as shown in the below figure.


Step 3:- Set the compression level and extension types

Next step is to set the compression levels and extension types. Compression level can be defined between 0 to 10, where 0 specifies a mild compression and 10 specifies the highest level of compression. This value is specified using ‘HcDynamicCompressionLevel’ property. There are two types of compression algorithms ‘deflate’ and ‘gzip’. This property needs to be specified in both the algorithm as shown in the below figures.


We need to also specify which file types need to be compressed. ‘HcScriptFileExtensions’ help us to specify the same. For the current scenario we specified that we need to compress ASPX outputs before they are sent to the end browser.

Step 4:- Does it really work?

Once you are done with the above 4 steps, it’s time to see if the compression really works. So we will create a simple C# asp.net page which will loop “10000” times and send some kind of output to the browser.

protected void Page_Load(object sender, EventArgs e)
{
for (int i; i <>
In order to see the difference before compression and after compression we will run the fiddler tool as we run our ASP.NET loop page. You can download fiddler from http://www.fiddler2.com/fiddler2/version.asp .

Below screen shows data captured by fiddler without compression and with compression. Without compression data is “80501 bytes” and with compression it comes to “629 bytes”. I am sure that’s a great performance increase from bandwidth point of view.

Assign Value to Asp.Net TextBox with mode="Password"

Introduction

ASP.NET server control doesn't add/display the value in a password textbox because of security concerns. On most of the web sites at the time of registration password is asked. You must have noticed after submitting the page if you are again redirected to the page due to unsuccessful registration value of password field is lost.This is due to security concerns as everything is gets rendered on the client side So when you view the source in the browser password value will be there.

Solution 1

Add an attribute to textbox.Add this following line of code when you want set the value

TextBox1.Attributes.Add("value", "thePassword")
Above solution will work, but if a user does view source on the form, the password is visible as plain text and that is never good from a security point of view. Rather, I would use Viewstate to hold the password value and if the user doesn't change it then retrieve the value from view state.

Solution 2

But if explicitly you want to set the value of password text box again then use following method in .NET 2.0

txtPassword.Attributes["value"] = Request.Form[txtPassword.ClientID]; //in C#.Net 2.0
Enjoy..

Alt+ Shortcut keys

Have you ever Wondered how someone makes a Heart, Arrow or even a TM trademark symbol with their Keyboard?

All you need to do is Hold down your "ALT" key and press another key on the keyboard to create a symbol.

Here is a list of some you can make. Have Fun!!

· Alt + 0153 - Trademark symbol
· Alt + 0169 - Copyright symbol
· Alt + 0174 - Registered trademark symbol
· Alt + 0176 - Degree symbol
· Alt + 0177 - Plus-or-minus sign
· Alt + 0182 - Paragraph mark
· Alt + 0190 - Fraction, three-fourths
· Alt + 0215 - Multiplication sign
· Alt + 0162 - The cent sign
· Alt + 0161 - Upside down exclamation point
· Alt + 0191 - Upside down question mark
· Alt + 1 - Smiley fsce
· Alt + 2 - Black smiley face
· Alt + 15 - Sun
· Alt + 12 - Female sign
· Alt + 11 - Male sign
· Alt + 6 - Spade sign
· Alt + 5 - Club symbol
· Alt + 3 - Heart
· Alt + 4 - Diamond
· Alt + 13 - Eighth note
· Alt + 14 - Beamed eighth note
· Alt + 8721 - N-ary summation (auto sum)
· Alt + 251 - Square root check mark
· Alt + 8236 - Infinity
· Alt + 24 - Up arrow
· Alt + 25 - Down arrow
· Alt + 26 - Right pointing arrow
· Alt + 27 - Left arrow
· Alt + 18 - Up/down arrow
· Alt + 29 - Left right arrow


.