Sunday, February 28, 2010

Web Page

------------------------------
Securing Your Config files
---------------------------

Two Ways

1. Using Command prompt with Commands
2. Using Enterprise Library


1. Using Command prompt with Commands

1. Go to Command Prompt

2. Change Directory to C:\Windows\Microsoft.NET\Framework\v2.0.50727

3. To Encrypt a Section in Web.Cofig - type following -

aspnet_regiis -pef ""

i.e. aspnet_regiis -pef "connectionStrings" “C:\Inetpub\wwwroot\TestWebSite"

i.e. aspnet_regiis -pef "system.web/identity" “C:\Inetpub\wwwroot\TestWebSite"

4. Go to your website root directory, and create a File AppUser.Aspx and type the following line save it.

a. < %@ Page Language="VB" % >

< % Response.Write( System.Security.Principal.WindowsIdentity.GetCurrent().Name ) % >

b. Now, open your browser and call this page, this will show you a DOMAIN/UserName under which you website is running. Take a note of it. Now go back to command prompt.

5. Run the following command on command prompt to allow Permission to Users e.g. "NT Authority\Network Service", and the User Your Web Site is using it. run following command

aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT Authority\Network Service"

aspnet_regiis -pa "NetFrameworkConfigurationKey" "DOMAIN/USERNAME"

6. After successful completion of command, remove the AppUser.Aspx file.

7. If you ever want to decrypt the section you encrypted, use following command

aspnet_regiis -pdf "CONFIG_SECTION" "PHYSICAL_PATH"

You do not need to make any code change in your application for encryption or decryption, .NET automatically does it for you.

For more details you can visit http://msdn.microsoft.com/en-us/library/ms998283.aspx

File: App.Config using Command Prompt

So what would you do to encrypt the same in case of App.Config, above command only work for Web.Config. Here is a trick – Copy the contents of App.Config into Web.Config file, or you can rename as web.config. Follow the same instructions as above, and after encryption, copy the file contents or rename it back to App.Config.


2. Using Enterprise Library

If you have downloaded and Installed Microsoft Enterprise Library Configuration Tool, just open Web.Config or App.Config and select the section you want to encrypt, Go into Protection à Protection Provider and choose a provider you want (default is none) and save the file, you are done. BUT, you may have to follow #4 - #6, if .NET is not able to read encrypted section.


----------------------------------------------------
Data Transform from Master Page to Content Page
----------------------------------------------------
1. By Using Property.
2. By Using Session.


1. By Using Property

In Master Page :-

public string CatFilter
{
get { return DropDownList1.SelectedValue.ToString(); }
}


In content Page :-

protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = ((MasterTest)Page.Master).CatFilter;

}


2. By Using Session.


In Master Page :-

Session["name"] = DropDownList1.SelectedValue.ToString();


In content Page :-

if(Convert.ToString(Session["name"]) != string.Empty)
Label1.Text = Session["name"].ToString();




----------------------------------------------
Common Validation Messages in web pages
----------------------------------------------
1. Record already exists.
2. Record updated successfully.
3. Mass updation is not allowed.
4. 'No row has been selected for edit! Please select a row'.
5. Deletion failed for the referenced Item(s).
6. Click the /'New/' icon to add new items.
7. Record saved successfully.
8. Are you sure, you want to delete?.
9. Please select an item to delete.
10. On multirow selecte and click on edit: Mass updation is not allowed.
11. The record Already exist.
12. Please Select a record before Updating.
13. Please Enter the value ---.
14. Record Should not be Empty.
15. Sorry, You are not Authoried User.
16. Please Select .....
17. Admin Confirmation Required.
18. Please Contact Your System Admin.


---------------------------
Web Page code check list
---------------------------

1. Is the Webpage marked with an appropriate namespace ?

2. Does the Webpage title map to ------ ?

3. Does all the controls name/Id follow naming conventions ?

4. Is all the client side script placed in a separate script file ?

5. Is the Webpage code properly indented ?

6. Does all the static text driven from label control ?

7. Is the maxlength specified as per the DB specifications for all the

input controls ?

8. Are all the Style definitions derived from the Theme ?

9. Are all the actions in the webpage implemented via aspButton control ?

10. Are all the alert messages implemented using javascript (or radAlert) ?

11. Are all the alert messages to the User driven from the resource file ?

12. Is the Webpage globalized/localized ?

13. Is the Webpage code properly grouped to respective content placeholders ?

14. Have all the unused variables been removed ?

15. Have all the unused Usings been removed ?

16. Have all the variables been checked for loss of data during conversion ?

17. Does the Switch Statement contain a default case ?

18. Have all the debugging statements (using alert and Response. Write) been

removed ?

19. Does all the variables, methods and Classes follow naming conventions ?

20. Is the Program Header complete and meaningful ?

21. Is every object checked for null before usage ?

22. Is data grouped together for efficient processing ?

23. Is necessary data getting inserted in the DB properly ?

24. Is user input being thoroughly validated before being processed?

25. Does the screen work with “no” data? (if no records are in the Database)

26. Has any repetitive code been organized into a separate function?

27. Are the necessary conditions being checked before looping?

28. Have all the class member variable names been started with m_?

29. Is the code properly indented as per the standards ?

30. Have all the static text been driven from the usage of constants?

31. Does all the variables, methods and Classes have appropriate access

specifiers?

32. Is the exception Handling implemented?

33. Have all the Service references been closed ?

34. Is the code logically grouped using namespace ?

35. Is the code physically grouped using region block ?

36. Is the Strict layering followed for all communications within the

application ?

37. Is the data passing mechanism strictly through c# custom class

objects(BDto) only ?

38. Are all the constants defined in their respective constant files ?

39. Is Theme set at Page Pre-Initialization event ?

40. Is Page UI culture set at Page Pre-Initialization event ?

41. Does the classes implement IDisposable wherever applicable ?


------------------------------
HTML Design Test for Table
------------------------------
border="1" cellpadding="0" cellpadding="0"

Sunday, February 21, 2010

Telerik Controls

How to Start Using Telerik Control
-----------------------------------

1. Install RadControlS_dev.msi, and Add References of below in path C:/Programfiles/Telerik/.....

1. Telerik.Web.UI.dll
2. Telerik.Web.UI.xml


2. In Web.config

1. Add below under httpHandlers tag in the Web.config

< add path="Telerik.Web.UI.WebResource.axd" verb="*" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" validate="false"/>



2. Add below in assemblies tag in the Web.config

< add assembly="Telerik.Web.Design, Version=2009.3.1103.35, Culture=neutral, PublicKeyToken=121FAE78165BA3D4" />


Database Connection
--------------------

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\Testdb1.mdf;user

Instance=True;Integrated Security=True;");



3. In UI (.aspx page)
---------------------

1. Add Telerik Script Manager before using talerik Control in .aspx page

< telerik:RadScriptManager ID="RadScriptManager1" runat="server" >
< /telerik:RadScriptManager >

2. Add below, after Page Tag (in .aspx page)

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>


4. Start to use Telerik Controls



======================================
1. Telerik radGrid
======================================

# 1. simple
------------
// (in .aspx page)

<telerik:RadGrid ID="RadGrid1" runat="server" />

// In Code Behand
// namespaces
using System.Data;
using System.Data.SqlClient;
using Telerik.Web.UI;

// con is sqlconnection object,
con.Open();
SqlCommand cmd = new SqlCommand("select * from EMP_Tab1", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
RadGrid1.DataSource = dr;
RadGrid1.DataBind();
}


OR


con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("select * from EMP_Tab1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RadGrid1.DataSource = ds;
RadGrid1.DataBind();
Session["data"] = ds;
con.Close();



# 2.1 complex with radGrid and Edit mode = "InPlace"
----------------------------------------------
// (in .aspx page)

< telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging = "true" PageSize="5" AllowSorting="true"
AllowFilteringByColumn ="true" AutoGenerateColumns = "false" OnUpdateCommand="GV_UpdateCmd"
OnNeedDataSource="GridView1_NeedDs" >
< MasterTableView DataKeyNames="EMPid" EditFormSettings-EditColumn-ButtonType="LinkButton"
EditFormSettings-EditColumn-AutoPostBackOnFilter="false" EditMode="InPlace" >
< Columns >
< telerik:GridBoundColumn UniqueName="EmpID" Visible="false" DataField="EmpID" DataType="System.Int32"

HeaderText="Emp ID" >
< /telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpName" DataField="EmpName" DataType = "System.String" HeaderText="Emp Name" >
</telerik:GridBoundColumn >
<telerik:GridBoundColumn UniqueName="EmpDesignation" DataField="empDesgination" DataType="System.String"

HeaderText="Designation" >
</telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpDept" DataField="empDept" DataType="System.String" HeaderText="Department" >
< /telerik:GridBoundColumn >
< telerik:GridEditCommandColumn UniqueName="EditEmp" EditText="Edit" >
< /telerik:GridEditCommandColumn >
< /Columns >
< /MasterTableView >
< /telerik:RadGrid >




// In Code behand

// Namespaces
using System.Data;
using System.Data.SqlClient;
using Telerik.Web.UI;


// method to bind radGrid control
public void Bind_radGrid()
{
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("select * from EMP_Tab1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RadGrid1.DataSource = ds;
RadGrid1.DataBind();
Session["data"] = ds;
con.Close();

}

// NeedDataSource Event store temporary data source
protected void GridView1_NeedDs(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = Session["data"];
}


// UpdateCommand Event for Edit data within radGrid (Edit mode = "InPlace")
protected void GV_UpdateCmd(object sender, GridCommandEventArgs e)
{
string strEmpID = String.Empty;
string strEmpName = String.Empty;
string strDesc = String.Empty;
string strDept = String.Empty;
GridEditableItem item = (GridEditableItem)e.Item;

foreach (object obj in item["EmpID"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strEmpID = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpName"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strEmpName = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpDesignation"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strDesc = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpDept"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strDept = ((TextBox)obj).Text;
}
}
con.Open();
string strQuery = "Update EMP_Tab1 set empName='" + strEmpName + "',EmpDesgination='" + strDesc +

"',EmpDept='" + strDept + "' where empId='" + strEmpID + "'";
SqlCommand cmdUpdate = new SqlCommand(strQuery, con);
cmdUpdate.ExecuteNonQuery();
con.Close();
Bind_radGrid();

}





# 2.2 complex with radGrid and Edit mode = "EditForms"
-------------------------------------------------------

// Changes in the UI and UpdateCommand Event
/// In UI radGrid Property set EditMode="EditForms"
/// In UI every GridBoundColumn set EditFormColumnIndex="0" or "1"
/// In UI add < EditFormSettings ColumnNumber="2" /> within < MasterTableView >
/// In Code Behand UpdateCommand Event change 'GridEditableItem' to GridEditFormItem

// In UI


< telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging = "true" PageSize="5" AllowSorting="true"
AllowFilteringByColumn ="true" AutoGenerateColumns = "false" OnUpdateCommand="GV_UpdateCmd"
OnNeedDataSource="GridView1_NeedDs" >
< MasterTableView DataKeyNames="EMPid" EditFormSettings-EditColumn-ButtonType="LinkButton"
EditFormSettings-EditColumn-AutoPostBackOnFilter="false" EditMode="EditForms" >
< Columns >
< telerik:GridBoundColumn UniqueName="EmpID" Visible="false" EditFormColumnIndex="0" DataField="EmpID"

DataType="System.Int32" HeaderText="Emp ID" >
< /telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpName" DataField="EmpName" EditFormColumnIndex="0" DataType = "System.String"

HeaderText="Emp Name" >
< /telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpDesignation" DataField="empDesgination" EditFormColumnIndex="1"

DataType="System.String" HeaderText="Designation" >
< /telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpDept" DataField="empDept" EditFormColumnIndex="1" DataType="System.String"

HeaderText="Department" >
< /telerik:GridBoundColumn >
< telerik:GridEditCommandColumn UniqueName="EditEmp" EditText="Edit" >
< /telerik:GridEditCommandColumn >
< /Columns >
< EditFormSettings ColumnNumber="2" / >
< /MasterTableView >

< /telerik:RadGrid >




// In Code behand

// NameSpaces
using System.Data;
using System.Data.SqlClient;
using Telerik.Web.UI;


// Bind radGrid Control
public void Bind_radGrid()
{
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("select * from EMP_Tab1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RadGrid1.DataSource = ds;
RadGrid1.DataBind();
Session["data"] = ds;
con.Close();

}

// NeedDataSource Event for Temporary Stored DataSource
protected void GridView1_NeedDs(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = Session["data"];
}

// Update Command Event for Edit data in radGrid (Edit mode = "EditForms")
protected void GV_UpdateCmd(object sender, GridCommandEventArgs e)
{
string strEmpID = String.Empty;
string strEmpName = String.Empty;
string strDesc = String.Empty;
string strDept = String.Empty;
//GridEditableItem item = (GridEditableItem)e.Item;
GridEditFormItem item = (GridEditFormItem)e.Item;
foreach (object obj in item["EmpID"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strEmpID = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpName"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strEmpName = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpDesignation"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strDesc = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpDept"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strDept = ((TextBox)obj).Text;
}
}
con.Open();
string strQuery = "Update EMP_Tab1 set empName='" + strEmpName + "',EmpDesgination='" + strDesc +

"',EmpDept='" + strDept + "' where empId='" + strEmpID + "'";
SqlCommand cmdUpdate = new SqlCommand(strQuery, con);
cmdUpdate.ExecuteNonQuery();
con.Close();
Bind_radGrid();

}



# 2.3 In .ASPX page improve Edit view (EditFormSettings) & Add (ExpandCollapseColumn) with radGrid & Edit mode = "EditForms"
-------------------------------------------------------------------------------------------------------------------------

< EditFormSettings ColumnNumber="2" EditColumn-FooterStyle-Font-Bold="true" CaptionFormatString="Edit details for Subject ID

: {0}"
CaptionDataField="SubjectID" >
< FormTableItemStyle Wrap="False"< > /FormTableItemStyle >
< FormCaptionStyle CssClass="EditFormHeader"> < /FormCaptionStyle >
< FormMainTableStyle GridLines="None" CellSpacing="0" CellPadding="3" Width="100%" / >
< FormTableStyle GridLines="Horizontal" CellSpacing="0" CellPadding="2" Height="110px"
Width="100%" / >
< FormTableAlternatingItemStyle Wrap="False"> < /FormTableAlternatingItemStyle >
< FormStyle Width="100%" BackColor="#eef2ea" > < /FormStyle >
< EditColumn UpdateText="Update" UniqueName="EditCommandColumn1" CancelText="Cancel" >
< /EditColumn >
< FormTableButtonRowStyle HorizontalAlign="Left" > < /FormTableButtonRowStyle >
< /EditFormSettings >
< ExpandCollapseColumn ButtonType="ImageButton" Visible="False" UniqueName="ExpandColumn" >
< HeaderStyle Width="19px" / >
< /ExpandCollapseColumn >





# 3.1 In .ASPX Page (radGrid with Edit mode = "InPlace" and In Edit mode add and bind radCombo within radGrid
----------------------------------------------------------------------------------

// In UI radGrid property add Event ( OnItemDataBound="radGrid_ItemDataBound" )
// In UI add GridTempleteColumn, and under EditItemTemplate with RadComboBox

< telerik:GridTemplateColumn HeaderText="ID" Visible="false" EditFormColumnIndex="0" >

< EditItemTemplate >
< telerik:RadComboBox runat="server" ID="Id" Width="156px" EmptyMessage="--Select--" >
< /telerik:RadComboBox >
< /telerik:GridTemplateColumn >

// In Code Behand add event

protected void radGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{

if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{

GridEditableItem editForm = (GridEditableItem)e.Item;
RadComboBox radcombo = (RadComboBox)editForm.FindControl("Id");
radcombo.DataSource = sssss;
radcombo.DataTextField = ssss.Columns[0].ToString();
radcombo.DataValueField = ssss.Columns[0].ToString();
radcombo.DataBind();
}

}



# 3.2 In .ASPX Page (radGrid with Edit mode = "EditForms" and In Edit mode add and bind radCombo within radGrid
----------------------------------------------------------------------------------

// In .ASPX page radGrid property add Event ( OnItemDataBound="radGrid_ItemDataBound" )
// In .ASPX page add GridTempleteColumn, and under EditItemTemplate with RadComboBox

< telerik:GridTemplateColumn HeaderText="ID" Visible="false" EditFormColumnIndex="0" >

< EditItemTemplate >
< telerik:RadComboBox runat="server" ID="Id" Width="156px" EmptyMessage="--Select--" >
< /telerik:RadComboBox >
< /telerik:GridTemplateColumn >

// In Code Behand add event

protected void radGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{

if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
{
GridEditFormItem editForm = (GridEditFormItem)e.Item;
RadComboBox cmbShortId = (RadComboBox)editForm.FindControl("ShortId");
Label lblShortName = (Label)editForm.FindControl("lblShortid");
String strlblShortName = lblShortName.Text;
cmbShortId.DataSource = null;
cmbShortId.DataBind();
if (ViewState["ShortID"] != null)
{
cmbShortId.Items.Insert(0, new RadComboBoxItem("-Select-", "0"));
//if(cmbShortId.DataSource == null)
cmbShortId.DataSource = ViewState["ShortID"];
cmbShortId.DataTextField = "ShortName";
cmbShortId.DataValueField = "ShortId";
if (strlblShortName != String.Empty)
cmbShortId.SelectedValue = strlblShortName;
cmbShortId.DataBind();
}
}

}


# 4. In .ASPX Page with radGrid get selected row key Value
-----------------------------------------------------

// Suppose in Employee table EMPID is Unique key value
// get select row EMPID.

1. IN .ASPX Page


/// take GridTemplateColumn under ItemTemplate under LABEL WITH Bind Text as empid
< MasterTableView >
< Columns >
< telerik:GridTemplateColumn HeaderText="Emp ID" Visible="false" EditFormColumnIndex="0" >
< ItemTemplate >
< asp:Label ID="lblEMPId" Text='<% #DataBinder.Eval(Container.DataItem, "empId") %>'

runat="server" > </asp:Label >
< /ItemTemplate >
< /telerik:GridTemplateColumn >
</Columns >
< /MasterTableView >

2. IN Code Behand in Required Event add below code

int getEmpid;
GridItemCollection gvSelectedItms = gvEmp.SelectedItems;
foreach (GridItem RowItem in gvSelectedItms)
{
lblTemp = (Label)RowItem.FindControl("lblEmp_Id");
getEmpid = Convert.ToInt32(lblTemp.Text);
}




# 5. In Telerik Grid Selected Grid Row Bind Values in Other Control like (Textbox etc)
----------------------------------------------------------------------------------

// Select the Row of the Grid
// Click the Edit Button than selected Row Display values in Other controls like Textbox etc.

// In UI

< telerik:RadGrid .......... >

< ClientSettings EnableRowHoverStyle="true" >
< Selecting AllowRowSelect="true" / >
< /ClientSettings >

..............

< /RadGrid >

// in Code Behand any button Click Event

GridItemCollection gvSelectedItms = gvEmp.SelectedItems;
if (gvEmp.SelectedItems.Count > 0 && gvEmp.SelectedItems.Count < 2)
{
foreach (GridItem RowItem in gvSelectedItms)
{

if (RowItem.Cells[3].Text.ToString() != " ")
txtEmpName.Text = RowItem.Cells[3].Text.ToString();
if (RowItem.Cells[4].Text.ToString() != " ")
txtEmpShortName.Text = RowItem.Cells[4].Text.ToString();
if (RowItem.Cells[5].Text.ToString() != " ")
txtDescription.Text = RowItem.Cells[5].ToolTip.ToString();
if (RowItem.Cells[9].Text.ToString() != " ")
radComboShortId.FindItemByText(RowItem.Cells[9].Text.ToString()).Selected = true;
}
}



# 6. radGrid Page Size Set in Web.Config
----------------------------------------

// In UI

PageSize=" < %$appSettings:GridPageSize % > "

// In Web.Config

< add key="GridPageSize" value="10"/ >



=========================
# 1. Telerik radComboBox
=========================

1. sample
------

// in UI

< telerik:RadComboBox ID="RadComboBox1" runat="server" / >


// In Code Behand

con.Open();
SqlCommand cmd = new SqlCommand("select EmpID,EmpName from EMP_Tab1", con);
SqlDataReader dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
RadComboBox1.DataSource = dr1;
RadComboBox1.DataTextField = "EmpName";
RadComboBox1.DataValueField = "EmpID";
RadComboBox1.DataBind();
}
con.Close();



2. Reflect Selected Item In the radComboBox
-----------------------------------------
// Example, select 5th Item in radComboBox
radComboEmpId.FindItemByText(RowItem.Cells[4].Text.ToString()).Selected = true;




----------------------------------------------------------------
Telerik Grid - How to select multiple row select in the grid to avoid check boxes
-----------------------------------------------------------------


First Define the following Client events and properties for the Telerik Grid:
< telerik:RadGrid ID="gvRegistrationSearch" >
< ClientSettings EnableRowHoverStyle="true" >
< Selecting AllowRowSelect="true" / >
< ClientEvents OnRowClick="RowClick" OnRowDeselecting="RowDeselecting" OnRowSelecting="RowSelecting" OnRowDblClick="" / >
< /ClientSettings >
< PagerStyle Mode="NextPrevAndNumeric" AlwaysVisible="true" / >

The Javascript functions are listed below:

var clickedItemIndex;
var deselected;
var selected;

function RowClick(sender, args) //Attach to the OnRowClick client event
{
var master = $find('< %= gvRegistrationSearch.ClientID % > ').get_masterTableView();
var index = args.get_itemIndexHierarchical();
master.get_dataItems()[index].set_selected(!master.get_dataItems()[index].get_selected());
clickedItemIndex = index;

if (master.get_dataItems()[index].get_selected())
selected = true;
else
selected = false;
}

function RowDeselecting(sender, args) //Attach to the OnRowDeselecting client event
{
if (clickedItemIndex != args.get_itemIndexHierarchical())
args.set_cancel(true);
else if (selected)
deselected = false;
else
deselected = true;
}

function RowSelecting(sender, args) //Attach to the OnRowSelecting client event
{
if (clickedItemIndex == args.get_itemIndexHierarchical() && deselected)
args.set_cancel(true);
else
deselected = false;
}

To Access the Values form the code behind use the below code example as reference.



Int32 countSelectedItems = gvRegistrationSearch.SelectedIndexes.Count;
GridItemCollection gvSelectedItms = gvRegistrationSearch.SelectedItems;
StringBuilder RegistrationNOCollection = new StringBuilder();
if (gvSelectedItms.Count > 0)
{
foreach (GridItem RowItem in gvSelectedItms)
{
String tempRegNo=RowItem.Cells[3].Text.ToString();
if(!String.IsNullOrEmpty(tempRegNo))
RegistrationNOCollection.Append(tempRegNo + ",");
}
}
else
{
Response.Write("< script > alert('Please select at least one item to Delete!')< /script > ");
return;
}

Pending Point: IE enables only single selection at the moment.
Reference Links:
http://demos.telerik.com/aspnet-ajax/grid/examples/client/selecting/defaultcs.aspx
http://www.telerik.com/community/forums/aspnet-ajax/grid/row-selection-question.aspx

===========================


Please use the below method to implement multi row select functionality for the Telerik grid.

< telerik:RadGrid ID="RadGrid1" DataSourceID="SqlDataSource1" AllowMultiRowSelection="true"
runat="server" AllowSorting="True" GridLines="None" >
< ClientSettings EnableRowHoverStyle="true" >
< Selecting AllowRowSelect="True" / >
< /ClientSettings >
< /telerik:RadGrid >

No Javascript event binding required required

Imp: Please provide a label control below the grid that displays the below message.

Note: Use Ctrl + left mouse click to de select a selected row.

For references please use the below article.

http://demos.telerik.com/aspnet-ajax/grid/examples/client/selecting/defaultcs.aspx
--

===========================



Please add One more content place holder ["cphBreadCrumbLink"] to all your pages which all using "TrustMaster" master page.

Add BreadCrumb Link to Content Place holder "cphBreadCrumLink".

Add all your page action Tool bar within content place holder "cphPageMenu"

For any further clarification feel free to ask me..


Start with Telerik Control

Teleric Controls
================


// Register Assembly (page level)
---------------------

< %@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" % >



// ScriptManager (Form Level)

< telerik:RadScriptManager runat="server" ID="RadScriptManager1" / >



// Web.config

< compilation debug="true" >
< assemblies >
< add assembly="Telerik.Web.Design, Version=2009.3.1103.35, Culture=neutral, PublicKeyToken=121FAE78165BA3D4"/ >
< add assembly="Telerik.Web.Design, Version=2009.3.1103.20, Culture=neutral, PublicKeyToken=121FAE78165BA3D4"/ >
< /assemblies >
< /compilation >




< httpHandlers >

< add path="Telerik.Web.UI.WebResource.axd" verb="*" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" validate="false"/ >

< /httpHandlers >










Grid Binding
-------------
SubjectBDto objSubjectBDTo = new SubjectBDto();

gvSubject.DataSource = null;
gvSubject.DataBind();

AdministrationService.AdministrationServiceClient objAdministrationServiceClient = new AdministrationService.AdministrationServiceClient();
DataTable dsSubject = objAdministrationServiceClient.GetSubjectList(); // objSubjectBDTo.SubjectList(); // new Vatsalya.BusinessComponent.Administration.Lookup.SubjectBC().GetSubjectList();
if(dsSubject != null)
if (dsSubject.Rows.Count > 0)
{
gvSubject.DataSource = dsSubject;
gvSubject.DataBind();
Session["data"] = dsSubject;
}










------------------------------------------------------------------------Two Telerik DateTimePicker controls with in RadGrid edit mode DateTimePicker Image Visiablity
------------------------------------------------------------------------

In UI
--------

< telerik:RadGrid
ID="RadGrid1"
runat="server"
EnableEmbeddedSkins="false"
Skin="Custom"
GridLines="Both"
Width="500px"
AutoGenerateColumns="false"
DataSourceID="XmlDataSource1"
>
< MasterTableView >
< Columns >
< telerik:GridEditCommandColumn / >
< telerik:GridDateTimeColumn ColumnEditorID="GridDateTimeColumnEditor1" DataField="datetime" HeaderText="Date/Time" PickerType="DateTimePicker" / >
< /Columns >
< /MasterTableView >
< /telerik:RadGrid >

< h2 > Using RadGrid ItemCreated< /h2 >

< telerik:RadGrid
ID="RadGrid2"
runat="server"
EnableEmbeddedSkins="false"
Skin="Custom"
GridLines="Both"
Width="500px"
AutoGenerateColumns="false"
DataSourceID="XmlDataSource1"
OnItemCreated="RadGrid2_ItemCreated"
>
< MasterTableView >
< Columns >
< telerik:GridEditCommandColumn / >
< telerik:GridDateTimeColumn DataField="datetime" HeaderText="Date/Time" PickerType="DateTimePicker" / >
< /Columns >
< /MasterTableView >
< /telerik:RadGrid >

< asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/datasource.xml" / >


In Code Behand
--------------


if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
RadDateTimePicker picker = ((e.Item as GridEditableItem)["datetime"].Controls[0]) as RadDateTimePicker;
picker.ImagesPath = "~/picker_images/";
}




--------------------------------------------------------
Accessing Row Data In Telerik RadGrid (Server Side)
--------------------------------------------------------

Hi There, Ive no problems using Javascript to read the rows of a telerik radgrid component im using however I can seem to find anyway to access the row data server side when a postback occurs. Ive spent ages looking for solution but no luck. Any pointers would be greatly appreciated.


Answers
------


You might want to look at the DataKeyValues property of the OwnerTableView object, which will let you access a collection of values that represent the fields in a given row. I use it during the EditCommand event handler, since a user of my site is directed to an edit page if they click on the link to edit a row in the grid, and I need to pass along certain info about the given row in the query string.

If this turns out to be what you need, you'll also need to define which fields should be made available through this property. To do that, look at the MasterTableView.DataKeyNames property in the property sheet for the grid. You basically specify a comma-delimited list of field names.




-------------------------------
Empty Check validation
----------------------------------

Radalert (Teleric control)


function validate()
{
if (document.getElementById('< %=txtSubjectId.ClientID % > ').value == "") {
radalert('Please Enter BusinessRole Name');
return false;
} else if (document.getElementById('< %=txtSubjectName.ClientID % > ').value == "") {
radalert('Please Select Application Role Number');
return false;
} else if (document.getElementById('< %=txtSubShortName.ClientID % > ').value == "") {
radalert('Please Select Application Role Number');
return false;
}
else {
return true;
}
}



In Button
---------
OnClientClick="return validate();"






-------------------------------------------------------------------------------
Set default value of telerik:GridDropDownColumn inside of telerik:RadGrid
--------------------------------------------------------------------------



I have a telerik:RadGrid that is bound to a SQL Data Source. One of the columns is for "Location" which is really a look up value in another table.

< telerik:GridDropDownColumn
DataField="d_location_id"
DataSourceID="dsLocation"
UniqueName="d_location_id"
DataType="System.Int32"
ListValueField="d_location_id"
ListTextField="Abbreviation"
HeaderText="Location" >
< /telerik:GridDropDownColumn >
My list of locations is stored in an ObjectDataSource, which is bound to a static DataTable and sorted alphabetically for me already. What I would like to do is be able to set the default option for this dropdown.

For example, suppose I have the following locations:

1 Home
2 Work
3 Parents
4 Car
I would like to have Parents be my default value.

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

Not sure if it is the best or most straightforward way or not, but it does work.

protected void gridMyInfo_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item.IsInEditMode && e.Item.ItemIndex < 0)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;

GridDropDownListColumnEditor editor = editMan.GetColumnEditor("d_location_id") as GridDropDownListColumnEditor;
editor.ComboBoxControl.SelectedIndex = editor.ComboBoxControl.Items.FindItemIndexByText("Parents");
}
}


-------------------------------------------------------------------------------
In edit mode RadCombobox in RadGrd. Popup telerik:RadGrid
--------------------------------------------------------------------------

In .ASPX
-----------

< telerik:GridTemplateColumn HeaderText="BusinessRole ID" Visible="false" EditFormColumnIndex="0" >
< ItemTemplate >
< asp:Label ID="lblBusinessRole_ID" Text='< % #DataBinder.Eval(Container.DataItem, "BusinessRoleId") % > '
runat="server" > < /asp:Label >
< /ItemTemplate >

< /telerik:GridTemplateColumn >



In code behand
------------------

protected void gvBusinessRole_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
AdministrationService.AdministrationServiceClient objAdministrationServiceClient = new AdministrationService.AdministrationServiceClient();

if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem editForm = (GridEditableItem)e.Item;
RadComboBox radcombo = (RadComboBox)editForm.FindControl("ApplicationRoleId");
radcombo.DataSource = objAdministrationServiceClient.GetApplicationRoleIdList();
radcombo.DataTextField = objAdministrationServiceClient.GetApplicationRoleIdList().Columns[0].ToString();
radcombo.DataValueField = objAdministrationServiceClient.GetApplicationRoleIdList().Columns[0].ToString();
radcombo.DataBind();

}

}


Selected values update to Database
-----------------------------------

protected void gvBusinessRole_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{

GridEditableItem editForm = (GridEditableItem)e.Item;
RadComboBox radcombo = (RadComboBox)editForm.FindControl("ApplicationRoleId");

strApplicationRoleId = radcombo.SelectedValue.ToString();

objBusinessRoleBDto.ApplicationRoleId = Convert.ToInt32(strApplicationRoleId);

// Call the service to update the values
AdministrationService.AdministrationServiceClient objAdministrationServiceClient = new AdministrationService.AdministrationServiceClient();
objAdministrationServiceClient.UpdateBusinessRole(objBusinessRoleBDto);

Bind_gvBusinessRoles();



RadGrid Popup
--------------

// Method for Grid Popup
public void Bind_gvBusinessRoles()
{
BusinessRoleBDto objBusinessRoleBDTo = new BusinessRoleBDto();

gvBusinessRole.DataSource = null;
gvBusinessRole.DataBind();


// Calling service to Grid Popup operation.
AdministrationService.AdministrationServiceClient objAdministrationServiceClient = new AdministrationService.AdministrationServiceClient();
DataTable dsBusinessRole = objAdministrationServiceClient.GetBusinessRoleList();

if (dsBusinessRole != null)
if (dsBusinessRole.Rows.Count > 0)
{
gvBusinessRole.DataSource = dsBusinessRole;
gvBusinessRole.DataBind();
Session["data"] = dsBusinessRole;
}

}




-------------------------------------------------------------------------------
How to calculate RadGrid cell value on Client side? telerik:RadGrid
--------------------------------------------------------------------------

Each cell contains NumericTextBox. Is it possible to calculate one cell based on other cells in the same row (on client side).


ASPX:

< Columns >
< rad:GridTemplateColumn UniqueName="Price" HeaderText="Price" >
< EditItemTemplate >
< radI:RadNumericTextBox ID="txtPrice" runat="server" >
< /radI:RadNumericTextBox >
< /EditItemTemplate >
< /rad:GridTemplateColumn >
< rad:GridTemplateColumn UniqueName="Quantity" HeaderText=" Number of Items" >
< EditItemTemplate >
< radI:RadNumericTextBox ID="txtQuantity" runat="server" >
< /radI:RadNumericTextBox >
< /EditItemTemplate >
< /rad:GridTemplateColumn >
< rad:GridTemplateColumn UniqueName="TotalAmount" HeaderText="Total" >
< EditItemTemplate >
< radI:RadNumericTextBox ID="txtTotalAmount" runat="server" >
< /radI:RadNumericTextBox >
< /EditItemTemplate >
< /rad:GridTemplateColumn >
< /Columns >



C#

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{

if (e.Item is GridDataItem && e.Item.IsInEditMode)
{
GridDataItem item = (GridDataItem)e.Item;
RadNumericTextBox txtPrice= item.FindControl("txtPrice") as RadNumericTextBox; // Get the textbox for column Price
RadNumericTextBox txtQuantity= item.FindControl("txtQuantity") as RadNumericTextBox; // Get the textbox for column Quantity
RadNumericTextBox txtTotalAmount= item.FindControl("txtTotalAmount") as RadNumericTextBox; // Get the textbox for column "TotalAmount", if it is template as shown in aspx

txtPrice.Attributes.Add("onFocusout", "return calculate('" + txtPrice.ClientID + "','" + txtQuantity.ClientID + "','" + txtTotalAmount.ClientID + "')");
txtQuantity.Attributes.Add("onFocusout", "return calculate('" + txtPrice.ClientID + "','" + txtQuantity.ClientID + "','" + txtTotalAmount.ClientID + "')");
txtTotalAmount.Attributes.Add("onfocus", "return calculate('" + txtPrice.ClientID + "','" + txtQuantity.ClientID + "','" + txtTotalAmount.ClientID + "')");
}
}


JavaScript:

< script type="text/javascript" >
function calculate(price, quantity, totalAmount)
{
var text1 = $find(price); //I used Asp.net Ajax find method
var text2 = $find(quantity);
var text3 = $find(totalAmount);
var total = text1.GetValue() * text2.GetValue();
text3.SetValue(total);
}
< /script >




-------------------------------------------------------------------------------
how to set wcf credentials when Telerik radgrid consumes the wcf service?
--------------------------------------------------------------------------


have a wcf service that requires client credentials so I can set this via code like this :

wcf.ClientCredentials.UserName.UserName = "user"; wcf.ClientCredentials.UserName.Password = "password";




OK if you need to get data from another server, it looks like you need to create your own server-side class as an ObjectDataSource on the server to be the client for your WCF service, because the browser's cross-domain restrictions will prevent the RadGrid from making client-side requests to both servers.

Your ObjectDataSource does the work of making the WCF requests.

Here's the Telerik RadGrid docs for how to use an ObjectDataSource: http://demos.telerik.com/aspnet-ajax/controls/examples/integration/aspajaxgridapplication/defaultcs.aspx?product=grid

...and here's Microsoft's docs on ObjectDataSource: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.aspx






-------------------------------------------------------------------------------
Changing how a telerik radgrid marks a row as “modified”
--------------------------------------------------------------------------

am working with the Telerik Winforms Radgrid version 2009.2.9.701 in visual studio 2008 (C#) and I've come across and issue I can't seem to find a solution for.

When the radgrid is populated and the user changes a cell within a row, the row is not flagged as "modified" until the user actually clicks onto another location on the datagrid. If the user modifies any values in a row and immediately clicks the "Save" button on my winform, the row is not flagged as having been modified and is not showing up in my list of modified rows.

I am using the following code to gather the modified rows ...

DataTable modifiedRows = dataTable.GetChanges(DataRowState.Modified);
My question is as follows: Is there a way to mark a row as "Modified" when the user changes a value in ANY cell in the row, without the user having to click off of the row before clicking the save button. I can't seem to find the flag that marks a data row as "Modified".


1 Answer
---------

This might be a bit of a work around but can you make the Save button move the focus off the grid when clicked? This may cause the grid row to be marked Modified.

private void SaveButton_Click(object sender, EventArgs e)
{
SaveButton.Focus();
// Do work to save the grid's modified rows
}





-------------------------------------------------------------------------------
Telerik RadGrid Add/Edit Row Performance Issue
--------------------------------------------------------------------------

*Are you duplicating the bind behaviour in the gridPhone_NeedDataSource event, your ItemUpdated, Deleted and Inserted events, and the native Rad Grid binding behviour (by using a asp:SqlDataSource control)?* It would be useful to see your code-behind to see if you are or not.

How many records do you have in the grid? I find if I have a large number of items in the Grid and have some of the advanced features turned on (I've noticed you've got row selecting enabled) the grid grinds to a halt.





--------------------------------------------------------
Accessing Row Data In Telerik RadGrid (Server Side)
--------------------------------------------------------

Hi There, Ive no problems using Javascript to read the rows of a telerik radgrid component im using however I can seem to find anyway to access the row data server side when a postback occurs. Ive spent ages looking for solution but no luck. Any pointers would be greatly appreciated.


Answers
------


You might want to look at the DataKeyValues property of the OwnerTableView object, which will let you access a collection of values that represent the fields in a given row. I use it during the EditCommand event handler, since a user of my site is directed to an edit page if they click on the link to edit a row in the grid, and I need to pass along certain info about the given row in the query string.

If this turns out to be what you need, you'll also need to define which fields should be made available through this property. To do that, look at the MasterTableView.DataKeyNames property in the property sheet for the grid. You basically specify a comma-delimited list of field names.


--------------------------------------------------------
// Alert message in Code behand using Teleric RadAlert
--------------------------------------------------------

String radalertscript = "function f(){radalert('Record updated successfully.', 330, 110,'ProjectName'); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);";
//ScriptManager.RegisterClientScriptBlock(updatePanelId, updatePanelId.GetType(), "message", radalertscript, true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", radalertscript);

About Assembly

What is .Net Assembly?

It is unit of deployment

The .NET assembly is the standard for components developed with the Microsoft .NET.

.net assemblies may or may not be Executable,
i.e they might exist as the executable (.exe) file or (DLL) file.

All the .net assemblies contain

1. defination of types,
2. versioning information fo the type
3. meta-data,
4. manifest.


TWO kind of assemblies in .NET
------------------------------

1. Private
2. Public or shared

Private Assembly
--------------
Private assembly are simple and copied with each calling assemblies in the calling assemblies folder.

Public Assembly OR Shared Assembly or Strong Named Assembly
---------------
public assemblies are copied in a single locaiton (Global assembly cache)
for all calling assemblies within the same application.
the same copy of the shared assembly is used from its original location
Hence, shared assemblies are not copied in the private Folders of each calling assembly.

Each Shared assembly has 4 part names

1. face name
2. version
3. public key token
4. culture information

Assembly can be a single file or it may consist of the multiple files

in case of multi-file, there is one master module containing the manifest
while other assemblies exist as non-manifest modules.



[assembly:AssemblyKeyFileAttribute(@"sgKey.snk")]

[assembly:AssemblyKeyFileAttribute("PublicKey.snk")]



Satallite Assembly
------------------

Assembly containing no executable code—only resources. Typically,
satellite assemblies are used for storing localized data.
Satellite assembles can be added, modified, and loaded into a .NET application
at runtime without recompiling. Use the Assembly Linking Utility
to create satellite assemblies by compiling .resource files.

ADO.NET

--------------------------------------------------------------------
ExecuteReader - ExecuteNonQuery - ExecuteScaler - ExecuteQuery
--------------------------------------------------------------------

Execute Reader..
1.Returns a datareader with data.
2.It is done by command object.
3.It is readonly.
4.It executes only select command.
5. This is known as a forward-only retrieval of records.It uses your sql statement to read through the table from the first to the last.


Execute NonQuery..
1.It will not return any data.
2.It is used with insert and update.
3.It returns only the number of rows affected.

Execute Scaler..
1.It returns only one value.
2.That value will the first column first row value.
used with aggregate functions like SUM() COUNT() etc

Execute Query..
1.Its for command objects.
2.It returns the value given by database through select statement.

--------------------------------------------
Convert a DataReader to DataTable in ASP.NET
---------------------------------------------


SqlConnection conn = null;
try
{
string connString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;
conn = new SqlConnection(connString);
string query = "SELECT * FROM Customers";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();


-------------------------------------------------------------------
Convert a DataReader to DataTable in ASP.NET (using ADO.NET 1.1)
-------------------------------------------------------------------


string connString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;
conn = new SqlConnection(connString);
string query = "SELECT * FROM Customers";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dtSchema = dr.GetSchemaTable();
DataTable dt = new DataTable();
// You can also use an ArrayList instead of List<>
List listCols = new List();
if (dtSchema != null)
{
foreach (DataRow drow in dtSchema.Rows)
{
string columnName = System.Convert.ToString(drow["ColumnName"]);
DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"]));
column.Unique = (bool)drow["IsUnique"];
column.AllowDBNull = (bool)drow["AllowDBNull"];
column.AutoIncrement = (bool)drow["IsAutoIncrement"];
listCols.Add(column);
dt.Columns.Add(column);
}
}
// Read rows from DataReader and populate the DataTable
while (dr.Read())
{
DataRow dataRow = dt.NewRow();
for (int i = 0; i <>
{
dataRow[((DataColumn)listCols[i])] = dr[i];
}
dt.Rows.Add(dataRow);
}
GridView2.DataSource = dt;
GridView2.DataBind();