Showing posts with label ASP.Net. Show all posts
Showing posts with label ASP.Net. Show all posts

Friday, June 11, 2010

Selecting a Row in ASPxGridView

I found that with the flood of new possibilities with DevExpress grid view a simple functionality of selecting one row is bit hidden. After doing bit of searching in the internet I found the way and thought to share it.

The way we need to do this is by using a java script and bind that in to the RowClick event of the grid.

The java script will look like the following.

<script type="text/javascript">
        function OnRowClick(e) {
            //Unselect all rows
            dxgdSearch._selectAllRowsOnPage(false);
            //Select the row
            dxgdSearch.SelectRow(e.visibleIndex, true);
        }
</script>

Then the binding to the RowClick would be as below.

<ClientSideEvents RowClick="function(s, e) { OnRowClick(e); }"></ClientSideEvents>

The outcome of this is a grid which you can select a row.

The value of the selected row can be taken as below.

dxgdSearch.GetRowValues(dxgdSearch.FocusedRowIndex, "Customer_ID")

For example in my application I used to pass the Customer Id to the Customer.aspx form as below.

 
 


  1. Response.Redirect("~/Customer.aspx?cusID= " + dxgdSearch.GetRowValues(dxgdSearch.FocusedRowIndex, "Customer_ID"));


 

The full source is as of below.

Page.aspx

 
 


  1. <asp:Content ID="Content4" ContentPlaceHolderID="MainContent" runat="server">
  2.     <script type="text/javascript">
  3.         function OnRowClick(e) {
  4.             //Unselect all rows
  5.             dxgdSearch._selectAllRowsOnPage(false);
  6.             //Select the row
  7.             dxgdSearch.SelectRow(e.visibleIndex, true);
  8.         }
  9.     </script>
  10.     <dx:ASPxGridView ID="dxgdSearch" ClientInstanceName="dxgdSearch" runat="server" AutoGenerateColumns="False"
  11.         SettingsBehavior-AllowFocusedRow="True" SettingsBehavior-AllowMultiSelection="False">
  12.         <ClientSideEvents RowClick="function(s, e) { OnRowClick(e); }"></ClientSideEvents>
  13.         <Columns>
  14.             <dx:GridViewDataTextColumn Name="Id" ShowInCustomizationForm="True" VisibleIndex="1"
  15.                 Caption="Customer ID" FieldName="Customer_ID" Visible="False">
  16.             </dx:GridViewDataTextColumn>
  17.             <dx:GridViewDataTextColumn Name="Name" ShowInCustomizationForm="True" VisibleIndex="0"
  18.                 Caption="Name" FieldName="Full_Name">
  19.             </dx:GridViewDataTextColumn>
  20.             <dx:GridViewDataTextColumn Name="TelephoneNo" ShowInCustomizationForm="True" VisibleIndex="1"
  21.                 Caption="Tele. No." FieldName="Mobile_Number">
  22.             </dx:GridViewDataTextColumn>
  23.             <dx:GridViewDataTextColumn Name="EMail" ShowInCustomizationForm="True" VisibleIndex="2"
  24.                 Caption="EMail" FieldName="Email">
  25.             </dx:GridViewDataTextColumn>
  26.             <dx:GridViewDataHyperLinkColumn Name="Select" VisibleIndex="3">
  27.                 <DataItemTemplate>
  28.                     <asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("Customer_ID") %>'
  29.                         OnClick="Button1_Click" Text="Edit" />
  30.                 </DataItemTemplate>
  31.             </dx:GridViewDataHyperLinkColumn>
  32.         </Columns>
  33.         <SettingsBehavior AllowFocusedRow="True"></SettingsBehavior>
  34.         <Settings ShowGroupPanel="True" ShowFilterRow="True" />
  35.         <Settings ShowFilterRow="True" ShowGroupPanel="True"></Settings>
  36.     </dx:ASPxGridView>
  37. </asp:Content>


Page.aspx.cs

 
 


  1. protected void Button1_Click(object sender, EventArgs e)
  2. {
  3.     Response.Redirect("~/Customer.aspx?cusID= " + dxgdSearch.GetRowValues(dxgdSearch.FocusedRowIndex, "Customer_ID"));
  4. }


Thursday, June 10, 2010

Unable to start debugging on the web server

Recently a set of developers who are working in one of my projects started getting an error while trying to debug the web application under development using ASP.Net. The targeted framework was .Net 4.0 and they were using Visual Studio 2010 in 64bit machines. The problem was whenever they tried to run/debug the application they gets an error saying unable to start debugging on the web server even though there are no compile errors as shown below.

image

It gave an error HTTP Error 500.21 - Internal Server Error Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list when ran direct from IIS. The error page is shown below.

image_thumb[1]

Later I found the reason for this is ASP.Net 4 was not properly installed on the machine. To fix this get an administrative privileged command prompt.

image

Then type in the following,

aspnet_regiis -ir

You can find the aspnet_regiis.exe at the folder,

[Windows Dir]\Microsoft.NET\Framework64\v4.0.xxxxx

for example,

C:\Windows\Microsoft.NET\Framework64\v4.0.30319

This will register ASP.Net 4.0 in your machine, the -ir option will keep the existing applications unchanged. If you want them to be changed to use the new version use -i instead -ir.

When the installer ends type iisreset to restart the IIS service.

image

Now your applications will work fine without any complains.

Saturday, May 15, 2010

Preserving State in ASP.Net

As you know a main challenge in web development is preserving the state of the application. We say web is stateless because web server treats each HTTP request for a page as an independent request. The server will not know any knowledge of variable values that were set/used during the previous requests. For example in Windows applications after we start the application if we set a variable to a certain value in a form it will be there until we close the form. But in web since the page is getting posted back the value will be normally lost.

To overcome this limitation in web ASP.Net provides two main methods and they are having different options under them.

  1. Client Side State Management
    1. View State
    2. Cookies
    3. Query String
  2. Server Side State Management
    1. Session State
    2. Application State
    3. Profile Properties

1.1- View State

Viewstate is a technique used in ASP.Net to preserve the state changes during the page postbacks. The viewstate data is always belong to the page, so this needs to be used when we want to store data at page level and retrieve them on the same page. Viewstate data will not be available from another page.

Viewstate uses a hidden form field named __VIEWSTATE as default to store the state information. When the “EnableViewstate” property of a control is set to true ASP.Net will start saving the control state in the viewstate. If we enable this property for many controls then soon the viewstate hidden variable will be large, and that may slow our application since this needs to be transferred at each postback. For example each time we submit a page the viewstate will go from our machine to server and from server to our machine. Due to this reason we should consider whether it is really required before enabling viewstate for a control. One advantage viewstate has is that it is not using server resources.

Apart from the viewstates of the controls in the form we can also add the values we need to preserve to the viewstate.

Adding a value -





  1. ViewState["Text"] = value;








  1. ViewState.Add("Text", value);




Retrieving a value -





  1. object o = ViewState["Text"];








  1. string str = (string) ViewState["Text"];




Read more at http://msdn.microsoft.com/en-us/library/bb386448.aspx.

1.2- Cookies

We use cookies to store frequently changed small amount of data at client side. We can control the life span of a cookie. For example we can create a cookie which expires when the session is over or which exists indefinitely in the client machine.

Cookies are light weight since they are text based structures having key value pairs. They are not taking any server resources since they are at client, but this also adds a disadvantage on security because users/hackers can tamper them. To prevent this we can encrypt cookies but this will reduce application performance. There is also a limit to the amount of data which we can be stored in a cookie. Also if cookies are blocked in browser the application will fail.

Adding a value -





  1. Response.Cookies["userData"]["Name"] = "Arjuna";
  2. Response.Cookies["userData"]["lastVisit"] = DateTime.Now.ToString();
  3. Response.Cookies["userData"].Expires = DateTime.Now.AddDays(1);








  1. HttpCookie aCookie = new HttpCookie("userData");
  2. aCookie.Values["Name"] = "Arjuna";
  3. aCookie.Values["lastVisit"] = DateTime.Now.ToString();
  4. aCookie.Expires = DateTime.Now.AddDays(1);
  5. Response.Cookies.Add(aCookie);




Retrieving a value -





  1. HttpCookie cookie = Request.Cookies["userData"];
  2. if (cookie == null)
  3. {
  4.     lblCookieText.Text = "Cookie not found.";
  5. }
  6. else
  7. {
  8.     lblCookieText.Text = cookie.Values[0] + ", " + cookie.Values["lastVisit"];
  9. }




Read more at http://msdn.microsoft.com/en-us/library/ms178194.aspx.

1.3- Query String

A query string is the information added at the end of the URL. This is supported by all the browsers and does not consume server resources. But this has limited capacity and security problems.

Adding a value -





  1. Response.Redirect("Webform2.aspx?Name=" +
  2. this.txtName.Text + "&LastName=" +
  3. this.txtLastName.Text);




Retrieving a value -

Using Webform2.





  1. this.TextBox1.Text = Request.QueryString[0];
  2. this.TextBox2.Text = Request.QueryString["LastName"];




 

2.1- Session State

Session state (variables) needs to be used to store session specific data. For example the logged in user information can be stored in session. Session variables are accessible by the entire set of pages in an application within the same session.

Session is created once a user visits a site and the session will end when the user leaves a site or when user becomes idle. Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object. One disadvantage is that the session variables are taking server resources.

Adding a value -





  1. Session["Name"] = “My Name”;




Retrieving a value -





  1. string str = (string) Session["Name"];




Read more at http://msdn.microsoft.com/en-us/library/ms178581.aspx.


2.2- Application State

Application state (variables) are used to store application specific data. Application state will be accessible to any users connected to the application. Normally global data which are infrequently changed, having no security concerns are stored in an application state.

The HttpApplicatioState instance is created at the first time a user accesses any URL resource in an application and the application state is lost when the application is ended. For example if the web server is restarted. If the value is required after application restart then before application end the required values needs to be transfered to a non volatile medium such as a database for later retrieval. The HttpApplicationState class is most often accessed through the Application property of the HttpContext class. When using the application state we need to remove any unnecessary items as soon as it is not required to maintain the site performance.

Adding a value -

When adding a value to an application variable it is always good to lock it before adding data since application state data can be accessed by multiple threads at the same time. Otherwise invalid data or erroneous data will appear. The loack needs to be removed after adding or changing the value to make the application state available for other threads.





  1. Application.Lock ();
  2. Application["NumberofViews"] = 1;
  3. Application.UnLock ();




Retrieving a value -





  1. string str = (string)Application["NumberofViews"];




Read more at http://msdn.microsoft.com/en-us/library/ms178594.aspx.

2.3 Profile Properties

Profile properties uses an ASP.Net profile and is user specific. This is similar to session state except that the data stored in profile properties are not lost when session is ended.

We can store the profile data in a place that we like. If we are using SQL Server to store them then we can use SqlProfileProvider, if not we can write our own profile provider classes so the profile data will be stored in custom formats and in a custom storage mechanisms, such as an XML file, or even to a Web service. But performance will be less since the data is stored in a data store. Also to use it additional configurations and to keep it in a fully optimized level maintenance activities are required.

Adding a value -

First we need to add the required provider and the properties to the web.config file.





  1. <profile enabled="true">
  2.   <providers>
  3.     <clear/>
  4.     <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
  5.   </providers>
  6.   <properties>
  7.     <add name="UserName" />
  8.   </properties>
  9. </profile>




Retrieving a value -





  1. TextBox1.Text = System.Web.Profile.DefaultProfile.Properties["UserName"].DefaultValue.ToString();




Read more at http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx.

Read more on ASP.Net state managements at http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx.

Sunday, December 13, 2009

Disabling Right Click

To disable right click context menu you can use one of the following methods.


Method 1 – Using attribute oncontextmenu attribute of the body tag.
By using this you can block the right click action and the context menu without using JavaScript.





  1. <body oncontextmenu="return false">




This will be useless if you need to do some action on the click. In such a case use the Method 2.

 

Method 2 – Using JavaScript.

Place the following JavaScript and modify the script as you need. This will just show a popup window to the user saying that Right clicking is disabled.





  1. <script language="javascript">
  2.     document.onmousedown = disableRightClick;
  3.     function disableRightClick(e) {
  4.         if (event.button == 2) {
  5.             alert("Right click is disabled.");
  6.             return false;
  7.         }
  8.     }
  9. </script>




Thursday, February 12, 2009

IE Developer Toolbar not Working

Recently I needed to install IE Developer Toolbar to get some values of some applications. But after the installation I found out that it is not displaying any information about the loaded site.
Later I got to know that IE Developer Toolbar is not working if Internet Explorer Enhanced Security Configuration is installed.
So if you are also facing the same problem go to Add / Remove Programs and open up the Windows Components wizard and uncheck Internet Explorer Enhanced Security Configuration to remove it and when the wizard is finished and after you have restarted the Internet Explorer the IE Developer Toolbar will function as usual.

Thursday, July 31, 2008

Implementing a File Download in ASP.NET

Recently I gave some help to a colleague of mine implementing a file download. So I thought of sharing it with you.
If you need to make a web site user to download a file from your site you have to use HTTPResponse.Page.Response object. By using this you will be able to make the user download numerous kinds of files to their machines. The code required is as follows.

// This defines the type of the file that you are allowing to download.
Response.ContentType = "application/vnd.ms-excel";
// Path to the file to be downloaded.
string FilePath = MapPath("Xcel.xlsx");
// Initiating the file download.
Response.WriteFile(FilePath);
Response.End();

The above code will let the user download an Excel file named Xcel. Aprt from Excel you can use other file types as well by changin the Response.ContentType to the required file type.
A list of available content types are as follows.