Tag Archive: asp.net


In ASP.GridView, if you hide a column, which will means you cannot get its value in code in the same time.

The reason and Solution:

Ah… You’ve discovered the additional security feature that a GridView has
but a DataGrid didn’t.

Basically, Microsoft

A selection of code samples for executing queries against MS Access using parameters.

Some Asp.net Controls support you customize the layout within LayoutTemplate tag, and you can even add new controls with it. e.g., add a VerifyCode feature for ASP:Login control. However, you will found you cannot get the customized control directly as other common ones, such as the customized VerifyCode textbox in login control in below,

The issue

Following code will encounter “The name ‘tbVerifyCode’ does not exist in the current context” error in Page_Load Method,
protected void Page_Load(object sender, EventArgs e)
{

If your application redirects (navigates) from one ASP.NET Web page to another, you will frequently want to pass information from the source page to the target page. For example, you might have a page where users can select items to purchase. When users submit the page, you want to call another page that can process the information that the user has entered.

You can pass information between pages in various ways, some of which depend on how the redirection occurs. Options include the following:

  • Use a query string, which appends information onto the URL of the target page. You can use a query string when using a HyperLink [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlink(VS.80).aspx ] control to build navigation into a page or when you are programmatically redirecting to another page using the Redirect [ http://msdn.microsoft.com/en-us/library/t9dwyts4(VS.80).aspx ] method.

    Passing values in a query string works even if the pages are not in the same Web application; it also works if you want to pass information to a page that is not an ASP.NET Web page. If the target page is an ASP.NET Web page, you can read the value of the query string out of the QueryString [ http://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring(VS.80).aspx ] property of the HttpRequest [ http://msdn.microsoft.com/en-us/library/system.web.httprequest(VS.80).aspx ] object.

    NoteNote

    Never pass sensitive data using a query string, because the information is visible to users and can easily be modified, thus representing a potential security risk.

  • Use session state to store information that is then accessible to all ASP.NET Web pages in the current application. However, this takes server memory, and the information is stored until the session expires, which can be more overhead than you want for simply passing information to the next page. For details, see ASP.NET State Management Overview [ http://msdn.microsoft.com/en-us/library/75x4ha6s(VS.80).aspx ] .

  • On the target page, read control values and public property values directly out of the source page. This strategy works in two situations: when the source page cross-posts to the target page (for more information, see How to: Post ASP.NET Web Pages to a Different Page [ http://msdn.microsoft.com/en-us/library/ms178140(VS.80).aspx ] ), and when you call the Transfer [ http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer(VS.80).aspx ] method to transfer execution from the source to the target page on the server. The strategy of reading values directly from the source page is described in this topic.

Getting Public Property Values from the Source Page

If you are designing the source page specifically for sharing information with target pages, and both pages are ASP.NET Web pages, in the source page you can add public properties that expose information you want to share between pages. You can then read the values of the properties in the target pages.

NoteNote

You can read source page properties in the target page only if both pages are in the same Web application.

To get public property values from the source page

  1. On the source page, create one or more public properties.

    The following code example shows a property named CurrentCity that exposes the value of a TextBox [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox(VS.80).aspx ] control named textCity.

    Visual Basic
    Public ReadOnly Property CurrentCity() As String
        Get
            Return textCity.Text
        End Get
    End Property

  ASP.Net 1.1后引入了对提交表单自动检查是否存在XSS(跨站脚本攻击)的能力。当用户试图用之类的输入影响页面返回结果的时候,ASP.Net的引擎会引发一个 HttpRequestValidationExceptioin。默认情况下会返回如下文字的页面:

Server Error in ‘/YourApplicationPath’ Application

A potentially dangerous Request.Form value was detected from the client
(txtName=”“).

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (txtName=”“).

….

  这是ASP.Net提供的一个很重要的安全特性。因为很多程序员对安全没有概念,甚至都不知道XSS这种攻击的存在,知道主动去防护的就更少了。ASP.Net在这一点上做到默认安全。这样让对安全不是很了解的程序员依旧可以写出有一定安全防护能力的网站。

  但是,当我Google搜索 HttpRequestValidationException 或者 “A potentially dangerous Request.Form value was detected from the client”的时候,惊奇的发现大部分人给出的解决方案竟然是在ASP.Net页面描述中通过设置 validateRequest=false 来禁用这个特性,而不去关心那个程序员的网站是否真的不需要这个特性。看得我这叫一个胆战心惊。安全意识应该时时刻刻在每一个程序员的心里,不管你对安全的概念了解多少,一个主动的意识在脑子里,你的站点就会安全很多。

  为什么很多程序员想要禁止 validateRequest 呢?有一部分是真的需要用户输入”<>“之类的字符。这就不必说了。还有一部分其实并不是用户允许输入那些容易引起XSS的字符,而是讨厌这种报错的形式,毕竟一大段英文加上一个ASP.Net典型异常错误信息,显得这个站点出错了,而不是用户输入了非法的字符,可是自己又不知道怎么不让它报错,自己来处理报错。

  对于希望很好的处理这个错误信息,而不使用默认ASP.Net异常报错信息的程序员们,你们不要禁用validateRequest=false。

  正确的做法是在你当前页面添加Page_Error()函数,来捕获所有页面处理过程中发生的而没有处理的异常。然后给用户一个合法的报错信息。如果当前页面没有Page_Error(),这个异常将会送到Global.asax的Application_Error()来处理,你也可以在那里写通用的异常报错处理函数。如果两个地方都没有写异常处理函数,才会显示这个默认的报错页面呢。

  举例而言,处理这个异常其实只需要很简短的一小段代码就够了。在页面的Code-behind页面中加入这么一段代码:

protected void Page_Error(object sender, EventArgs e)
{

方法一:
现在假设有两个页面A、B,我们的目的是把A页面的数据提交到B页面。
首先在A页面建立B页面需要访问A页面的数据项的访问属性。

public

Tip/Trick: Localization and Master Pages

Today, I found a great solution to create Multilingual Websites (Localization)

Introduction

While seeking on the internet for a solution to implement localization within an ASP.NET application using a MasterPage, I realized that a lot of people have got the same problem to solve. Unfortunately, I could not find a suitable solution thus, I intended to do my own implementation.

Background

The solution presented within this article uses the standard localization mechanism of the .NET framework.

Using the code

The published solution uses the Session object as storage for the currently selected culture. This will be initialized during the Session_Start method that is part of the global.asax file.

If a culture change is requested by the user, the MasterPage changes the stored culture in the Session object.

In a BasePage that inherits from Page, the method InitializeCulture is overridden and sets the appropriate culture information stored in the Session object to the current thread. Therefore, every Web Form needs to derive from this BasePage.

Let’s start with the Global.asax file:

void Session_Start(object sender, EventArgs e)
{
    //set english as default startup language
    Session["MyCulture"] = "en-GB";
}

Alternatively, the culture can be defined in the Web.config file with the key <globalization culture="en-GB" /> and then be processed and stored in the Session object from the Session_Start method.

The next step is the master page:

<%@ Master Language="C#" AutoEventWireup="true"
           CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>[Smart-Soft - Masterpage with Localization Support]</title>
</head>

<body>
    <form id="theForm" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder" runat="server">
        </asp:contentplaceholder>
    </div>
    <div style="margin-top:20px;">
        <asp:LinkButton ID="btnSetGerman" runat="server" Text="Deutsch"
           CommandArgument="de-CH" OnClick="RequestLanguageChange_Click">
        </asp:LinkButton>
        <asp:LinkButton ID="btnSetEnglish" runat="server" Text="English"
           CommandArgument="en-GB" OnClick="RequestLanguageChange_Click">
        </asp:LinkButton>
    </div>
    </form>
</body>
</html>

The buttons to change the culture can be either placed in the MasterPage directly, or in any embedded UserControl. In order to determine the requested language, the CommandArgument attribute of the LinkButton is used.

..And the code-behind of the master page:

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void RequestLanguageChange_Click(object sender, EventArgs e)
    {
        LinkButton senderLink = sender as LinkButton;

        //store requested language as new culture in the session
        Session["MyCulture"] = senderLink.CommandArgument;

        //reload last requested page with new culture
        Server.Transfer(Request.Path);
    }
}

The requested language, passed within the CommandArgument, is processed and stored in the Session object. Afterwards, the initially requested page will be reloaded on the server side.

Last but not least, the BasePage:

/// <summary>
/// Custom base page used for all web forms.
/// </summary>
public class BasePage : Page
{
    private const string m_DefaultCulture = "en-GB";

    protected override void InitializeCulture()
    {
        //retrieve culture information from session
        string culture = Convert.ToString(Session["MyCulture"]);

        //check whether a culture is stored in the session
        if (!string.IsNullOrEmpty(culture)) Culture = culture;
        else Culture = m_DefaultCulture;

        //set culture to current thread
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);

        //call base class
        base.InitializeCulture();
    }
}

As mentioned above, the InitializeCulture method is overridden, and gets the stored culture from the Session object and assigns it to the currently running thread.

Remark: In this article, only the culture was mentioned. Of course, there is also the UI culture. But it is not of any further interest in this article since the handling is absolutely identical. For more information, please see the MSDN pages. :)

For a running example, download the Zip file here. MasterPageWithLocalization.zip (10.92 kb)

Value of Selected Server Side CheckboxList Item in Client Javascript

[Issue]

If you are using CheckboxList ASP.NET

Copy from: http://odetocode.com/Articles/428.aspx

Once you know a user’s identity, you need to determine what actions you’ll allow the user to perform, and what pages you’ll allow a user to visit. A common technique for managing authorization rules like this is to categorize users into groups, or roles, and make authorization decisions based on the roles assigned to a user. For example, you might have 10,000 registered users for your application but define only 3 roles: administrators, registered users, and anonymous users. Using roles reduces the amount of administrative work required to run a site. When you want to grant or restrict access to all registered users on the site, you only need to apply the rule to one role, and not change the rules for each individual user account.

We typically use roles in our web.config files to allow and deny access for files and folders to groups of users. These rules appear

Powered by WordPress | Theme: Motion by 85ideas.