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

Wednesday, June 9, 2010

LoadDataRow(object[], LoadOption) and ConstraintException

See The LoadDataRow and Delete Methods of DataTable for intention.


Introduction

In this test, I will use LoadDataRow to perform content update on a DataTable with or without primary key constraint. LoadOption is passed in a parameter with this call LoadDataRow(object[], LoadOption). For result using LoadDataRow(object[], bool), please see this.

When the LoadDataRow method is call, the following statement is used:
   employee.LoadDataRow(
      new object[] { "B223456789", "Denise", "Miller", 13.00 },
      LoadOption.OverwriteChanges);
When primary key is applied, the following statement is used and it will be executed before the LoadDataRow method:
   employee.PrimaryKey = new DataColumn[] {eid}; // eid is the EmpId column  

Before presenting the test results, we will first set up a DataTable with 2 rows without primary key constraint. Our DataTable will have the following columns:
ColumnNameEmpIdFirstNameLastNameSalaryLastName and FirstName **
DataTypestringstringstringdecimalstring
MaxLength1035-1-170
Uniquetruefalsefalsefalsefalse
AllowDBNullfalsefalsefalsetruetrue

** The column of LastName and FirstName is defined as an expression column containing the values from the column of LastName and the column of FirstName.

Every test is based on this table with the initial sample data. The 2nd row is the target to update by using the LoadDataRow method. A grid shown in each test is represented the final result of the DataTable even though the update performed by the LoadDataRow method may fail. Execution messages about the RowState of the 2nd row and its versions are shown afterwards. For clarity, the initial state of the 2nd row is also attached to each test for reference.

The rest of the page is generated by the application developed in C# under Visual 2008 Profession SP + .NET 3.5 SP1 on Windows XP Professional SP3.


Set up a DataTable with 2 rows
- EmpId is the unique key (eid.Unique = true).
- Primary key is not set up initially.

  • Initial Table:
  • EmpIdFirstNameLastNameSalaryLastName and FirstName
    A123456789BettyeWilliams11.00Williams, Bettye
    B223456789RexBloomer12.00Bloomer, Rex

  • Status duing execution:
  • Initial state: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex


No primary key applied
Expect errors [System.Data.UniqueConstraint.CheckConstraint]!
The last row remains unchanged.

  • Resulted DataTable:
  • EmpIdFirstNameLastNameSalaryLastName and FirstName
    A123456789BettyeWilliams11.00Williams, Bettye
    B223456789RexBloomer12.00Bloomer, Rex

  • Status duing execution:
  • Initial state: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    Executing LoadDataRow(...)
    Column 'EmpId' is constrained to be unique.  Value 'B223456789' is already present.
    System.Data.ConstraintException
    at System.Data.UniqueConstraint.CheckConstraint(DataRow row, DataRowAction action) at System.Data.DataTable.RaiseRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction, Boolean fireEvent) at System.Data.DataTable.SetNewRecordWorker(DataRow row, Int32 proposedRecord, DataRowAction action, Boolean isInMerge, Int32 position, Boolean fireEvent, Exception& deferredException) at System.Data.DataTable.InsertRow(DataRow row, Int32 proposedID, Int32 pos, Boolean fireEvent) at System.Data.DataTable.LoadRow(Object[] values, LoadOption loadOption, Index searchIndex) at System.Data.DataTable.LoadDataRow(Object[] values, LoadOption loadOption) ...

    After error: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex


Primary key applied, no AcceptChanges before or after LoadDataRow
No error! The last row is updated.

  • Resulted DataTable:
  • EmpIdFirstNameLastNameSalaryLastName and FirstName
    A123456789BettyeWilliams11.00Williams, Bettye
    B223456789DeniseMiller13.00Miller, Denise

  • Status duing execution:
  • Initial state: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    Executing LoadDataRow(...)
    After LoadDataRow: [B223456789, Denise] RowState: Unchanged
    Version: Original Value: Denise
    Version: Current Value: Denise
    Version: Proposed doesn't not exist.
    Version: Default Value: Denise


No primary key, AcceptChanges before LoadDataRow
Expect errors [System.Data.UniqueConstraint.CheckConstraint]!
The last row remains unchanged.

  • Resulted DataTable:
  • EmpIdFirstNameLastNameSalaryLastName and FirstName
    A123456789BettyeWilliams11.00Williams, Bettye
    B223456789RexBloomer12.00Bloomer, Rex

  • Status duing execution:
  • Initial state: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    Apply AcceptChanges(): [B223456789, Rex] RowState: Unchanged
    Version: Original Value: Rex
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    Executing LoadDataRow(...)
    Column 'EmpId' is constrained to be unique.  Value 'B223456789' is already present.
    System.Data.ConstraintException
    at System.Data.UniqueConstraint.CheckConstraint(DataRow row, DataRowAction action) at System.Data.DataTable.RaiseRowChanging(DataRowChangeEventArgs args, DataRow eRow, DataRowAction eAction, Boolean fireEvent) at System.Data.DataTable.SetNewRecordWorker(DataRow row, Int32 proposedRecord, DataRowAction action, Boolean isInMerge, Int32 position, Boolean fireEvent, Exception& deferredException) at System.Data.DataTable.InsertRow(DataRow row, Int32 proposedID, Int32 pos, Boolean fireEvent) at System.Data.DataTable.LoadRow(Object[] values, LoadOption loadOption, Index searchIndex) at System.Data.DataTable.LoadDataRow(Object[] values, LoadOption loadOption) ...

    After error: [B223456789, Rex] RowState: Unchanged
    Version: Original Value: Rex
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex


Primary key applied, AcceptChanges before LoadDataRow
No error! The last row is updated.

  • Resulted DataTable:
  • EmpIdFirstNameLastNameSalaryLastName and FirstName
    A123456789BettyeWilliams11.00Williams, Bettye
    B223456789DeniseMiller13.00Miller, Denise

  • Status duing execution:
  • Initial state: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    Apply AcceptChanges(): [B223456789, Rex] RowState: Unchanged
    Version: Original Value: Rex
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    Executing LoadDataRow(...)
    After LoadDataRow: [B223456789, Denise] RowState: Unchanged
    Version: Original Value: Denise
    Version: Current Value: Denise
    Version: Proposed doesn't not exist.
    Version: Default Value: Denise


No primary key, LoadDataRow in conjunction with Begin/EndLoadData
Expect errors [System.Data.DataTable.EnableConstraints()]!
Duplicate rows are found.

  • Resulted DataTable:
  • EmpIdFirstNameLastNameSalaryLastName and FirstName
    A123456789BettyeWilliams11.00Williams, Bettye
    B223456789RexBloomer12.00Bloomer, Rex
    B223456789DeniseMiller13.00Miller, Denise

  • Status duing execution:
  • Initial state: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    BeginLoadData(): turn off notification/constraints/indexing.

    Executing LoadDataRow(...)
    After LoadDataRow: [B223456789, Denise] RowState: Unchanged
    Version: Original Value: Denise
    Version: Current Value: Denise
    Version: Proposed doesn't not exist.
    Version: Default Value: Denise

    EndLoadData(): turn on validation, constraints, etc.

    Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
    System.Data.ConstraintException
    at System.Data.DataTable.EnableConstraints() at System.Data.DataTable.set_EnforceConstraints(Boolean value) at System.Data.DataTable.EndLoadData() ...

    After error: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex


Primary key applied, LoadDataRow in conjunction with Begin/EndLoadData
No error! The last row is updated.

  • Resulted DataTable:
  • EmpIdFirstNameLastNameSalaryLastName and FirstName
    A123456789BettyeWilliams11.00Williams, Bettye
    B223456789DeniseMiller13.00Miller, Denise

  • Status duing execution:
  • Initial state: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    BeginLoadData(): turn off notification/constraints/indexing.

    Executing LoadDataRow(...)
    After LoadDataRow: [B223456789, Denise] RowState: Unchanged
    Version: Original Value: Denise
    Version: Current Value: Denise
    Version: Proposed doesn't not exist.
    Version: Default Value: Denise

    EndLoadData(): turn on validation, constraints, etc.

    [B223456789, Denise] RowState: Unchanged
    Version: Original Value: Denise
    Version: Current Value: Denise
    Version: Proposed doesn't not exist.
    Version: Default Value: Denise


Primary key applied, LoadDataRow in conjunction with Begin/EndLoadData, ApplyChanges before BeginLoadData
No error! The last row is updated.

  • Resulted DataTable:
  • EmpIdFirstNameLastNameSalaryLastName and FirstName
    A123456789BettyeWilliams11.00Williams, Bettye
    B223456789DeniseMiller13.00Miller, Denise

  • Status duing execution:
  • Initial state: [B223456789, Rex] RowState: Added
    Version: Original doesn't not exist.
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    Apply AcceptChanges(): [B223456789, Rex] RowState: Unchanged
    Version: Original Value: Rex
    Version: Current Value: Rex
    Version: Proposed doesn't not exist.
    Version: Default Value: Rex

    BeginLoadData(): turn off notification/constraints/indexing.

    Executing LoadDataRow(...)
    After LoadDataRow: [B223456789, Denise] RowState: Unchanged
    Version: Original Value: Denise
    Version: Current Value: Denise
    Version: Proposed doesn't not exist.
    Version: Default Value: Denise

    EndLoadData(): turn on validation, constraints, etc.

    [B223456789, Denise] RowState: Unchanged
    Version: Original Value: Denise
    Version: Current Value: Denise
    Version: Proposed doesn't not exist.
    Version: Default Value: Denise

Saturday, May 8, 2010

Extract File Extension and Check Image Format

[ Intention | Requirements | Discussion and Implementation | Final Code Snippets ]

Intention [top]

Once in a while, we all may need to extract the file extension from a file name. In the past, when I was doing it in Java, I used to use the String.lastIndexOf() to search for the last period in the filename and then extract the rest of the substring. We can apply the same idea in .NET using String.LastIndexOf() as well. However, .NET provides a single static method call; it makes everything a lot easier. However, this static method internal implementation is not using regular expression to extract the file extension. Yesterday, I was browsing around my old code and thinking that I would like to use regular expression to capture the file extension. Thus, I pick the portion of my file upload program for conversion. First, I will start with the requirements for this file upload portion and then go into the detail discussion. Finally I will present the complete code snippets. In this exercise, I will also show you how to check the image format.

Requirements [top]

  1. Use regular expression to capture or extract the file extension from the file name but the leading period (.) of the resulted file extension must be trimmed off. For example, .txt becomes txt.
  2. A file extension cannot contain spaces.
  3. Save the uploaded file if only if the file extension is one of the listed extensions (see the list below) and the file must be one of the supported image formats.
  4. Supported file extensions are BMP, GIF, PNG, TIFF, JPG, and JPEG.
  5. Supported image formats are BMP, GIF, PNG, TIFF and JPEG. They are also corresponding to the above file extensions

Discussion and Implementation [top]

There are a few ways to extract a file extension from a file name. One of the simple ways is to use System.IO.Path.GetExtension() method by passing the file name as a parameter, e.g.,

   System.IO.Path.GetExtension("abc.txt")

In this example, .txt is the extracted file extension and it always comes with a leading period (.). In order to fit our 1st requirement, we could remove the leading period from the resulted file extension. Unfortunately, the requirement binds us to use regular expression. Thus, the regular expression should look like the following (non-named capturing):

      \.([^.]+)$

According to the 2nd requirement (the extension cannot contain spaces), the previous regular expression is revised and becomes:

      \.([^(\s|.)]+)$

In C#, we can do the following to fulfill the #1 and the #2 requirements:

      String pattern = @"\.([^(\s|.)]+)$";        
      String fileExt = null;

      Regex r = new Regex(pattern);
      Match m = r.Match(filename);
      if (m.Success) {
        fileExt = m.Groups[1].Value;
      }

As we can see, the captured text is always placed inside the group 1 (at index 1), not 0. What if we have many captured groups? It could be hard to remember which one is what. Luckily, .NET supports name capturing. It greatly helps in coding and back-reference. In this example, the requirement is simple and we don't have to use named capture. But to exercise this named capture feature, we could revise the regular expression a bit and then reference the name in our code. Let's say that the captured text name is called ext. The revised code snippet becomes:

      String pattern = @"\.(?<ext>[^(\s|.)]+)$";        
      String fileExt = null;

      Regex r = new Regex(pattern);
      Match m = r.Match(filename);
      if (m.Success) {
        fileExt = m.Groups["ext"].Value; 
      }

A part of the third requirement is to check the resulted file extension against our supported file extension list. We can continuously get help from regular expression. Let's define our pattern for matching. In C#, we can write this:

      String SupportedImageExtPatterns = "^(BMP|GIF|PNG|TIFF|JPE?G)$";

To check the resulted file extension against the list, in C#, we can implement this way:

      Match m1 = Regex.Match(fileExt, 
                             SupportedImageExtPatterns,
                             RegexOptions.IgnoreCase);
      if (m1.Success) {
        ...
      }
or using one single statement,
      if (Regex.Match(fileExt, 
                      SupportedImageExtPatterns,
                      RegexOptions.IgnoreCase).Success) {  
          ...
      }

How to check the file is one of the supported image format? Since the file is uploaded via HTTP, the file could be anything. For this matter, we first need to confirm if the file is an image by referencing to the file's Stream object and then try to convert it to an image. If we get an ArgumentException, it is not an image. Let's say the file upload object is called FileUpload1. In C#, we can write the following to execute the idea.

      System.Drawing.Image theImage = null;
      try {
        theImage = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
      }
      catch (System.ArgumentException) {  // not an image
        ...
      }
After we've confirmed that the file is an image, we can go ahead to check the image format against our list with the help of the Equals() method of System.Drawing.Imaging.ImageFormat. For convenience, I group all the required System.Drawing.Imaging.ImageFormat objects together in an array so that I can iterate through the array for checking.
       System.Drawing.Imaging.ImageFormat[] SupportedImageFormats = { 
             System.Drawing.Imaging.ImageFormat.Bmp,      
             System.Drawing.Imaging.ImageFormat.Gif,      
             System.Drawing.Imaging.ImageFormat.Png,
             System.Drawing.Imaging.ImageFormat.Tiff,
             System.Drawing.Imaging.ImageFormat.Jpeg      
       };

The code snippet for checking image format in C# is illustrated below:
       System.Drawing.Imaging.ImageFormat[] SupportedImageFormats = { 
         System.Drawing.Imaging.ImageFormat.Bmp,      
         System.Drawing.Imaging.ImageFormat.Gif,      
         System.Drawing.Imaging.ImageFormat.Png,
         System.Drawing.Imaging.ImageFormat.Tiff,
         System.Drawing.Imaging.ImageFormat.Jpeg      
       };

       System.Drawing.Image theImage = null;
       try {
         theImage = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);

         for (int i=0; i < SupportedImageFormats.Length; i++) {        
           if (theImage.RawFormat.Equals(SupportedImageFormats[i])) {
             ...
             break;
           }
         }
         ...

       }
       catch (System.ArgumentException) {  // not an image
         ...
       }

As soon as we confirm that the file is an image and it is also one of our expected formats, we can simply use the FileUpload object SaveAs() method by passing the absolute pathname. Let's say the directory to save is called Uploads. The statement may look something like below:

   FileUpload1.SaveAs(Server.MapPath("~/Uploads/") + FileUpload1.FileName);
Up to here, our mission is accomplished from extracting the file extension, checking image format to saving the file. The complete code snippets are presented in the next section.

Final Code Snippets [top]

The followings are two pieces of code snippets summarized for the above discussions. The difference between these two pieces of code is: one is using non-named capture to extract the file extension while the other is named capture. Other than that, everything is identical.

Using non-named capture to extract the file name [ Final Code Snippets | top ]

Note that
  1. the file upload control object is called FileUpload1, and
  2. the save directory is called Uploads and located at the root directory.
// declare the pattern for Requirement #1 and #2 to capture the file extension.
// the following pattern is using non-named capture.
String pattern = @"\.([^(\s|.)]+)$";        
String fileExt = null;

Regex r = new Regex(pattern);
Match m = r.Match(FileUpload1.PostedFile.FileName); 
if (m.Success) {
  // capture the file extension without the period
  // here we use non-named capture group
  fileExt = m.Groups[1].Value;

  // Requirement #4 - the supported file extensions
  String SupportedImageExtPatterns = "^(BMP|GIF|PNG|TIFF|JPE?G)$";

  if (Regex.Match(fileExt, 
                  SupportedImageExtPatterns,
                  RegexOptions.IgnoreCase).Success) {

    // Requirement #5 - the supported image formats 
    System.Drawing.Imaging.ImageFormat[] SupportedImageFormats = { 
          System.Drawing.Imaging.ImageFormat.Bmp,      
          System.Drawing.Imaging.ImageFormat.Gif,      
          System.Drawing.Imaging.ImageFormat.Png,
          System.Drawing.Imaging.ImageFormat.Tiff,
          System.Drawing.Imaging.ImageFormat.Jpeg      
    };

    System.Drawing.Image theImage = null;
    try {
      theImage = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
    
      for (int i=0; i < SupportedImageFormats.Length; i++) {        
        if (theImage.RawFormat.Equals(SupportedImageFormats[i])) {
           // Requirement #3 - save the file only if it is our expected image format.
           FileUpload1.SaveAs(Server.MapPath("~/Uploads/") + FileUpload1.FileName);
           break;
        }
      }      
    }
    catch (System.ArgumentException) {  // not an image
      ...  
    }
  }
}

Using named capture to extract the file name [ Final Code Snippets | top ]

Note that
  1. the file upload object is called FileUpload1, and
  2. the save directory is called Uploads and located at the root directory.
// declare the pattern for Requirement #1 and #2 to capture the file extension.
// the following pattern is using named capture.
String pattern = @"\.(?<ext>[^(\s|.)]+)$";        
String fileExt = null;

Regex r = new Regex(pattern);
Match m = r.Match(FileUpload1.PostedFile.FileName);
if (m.Success) {
  // capture the file extension without the period
  // here we use named capture group
  fileExt = m.Groups["ext"].Value;

  // Requirement #4 - the supported file extensions
  String SupportedImageExtPatterns = "^(BMP|GIF|PNG|TIFF|JPE?G)$";

  if (Regex.Match(fileExt, 
                  SupportedImageExtPatterns,
                  RegexOptions.IgnoreCase).Success) {

    // Requirement #5 - the supported image formats 
    System.Drawing.Imaging.ImageFormat[] SupportedImageFormats = { 
          System.Drawing.Imaging.ImageFormat.Bmp,      
          System.Drawing.Imaging.ImageFormat.Gif,      
          System.Drawing.Imaging.ImageFormat.Png,
          System.Drawing.Imaging.ImageFormat.Tiff,
          System.Drawing.Imaging.ImageFormat.Jpeg      
    };

    System.Drawing.Image theImage = null;
    try {
      theImage = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
    
      for (int i=0; i < SupportedImageFormats.Length; i++) {        
        if (theImage.RawFormat.Equals(SupportedImageFormats[i])) {
           // Requirement #3 - save the file only if it is our expected image format.
           FileUpload1.SaveAs(Server.MapPath("~/Uploads/") + FileUpload1.FileName);
           break;
        }
      }      
    }
    catch (System.ArgumentException) {  // not an image
      ...  
    }
  }
}

Wednesday, July 22, 2009

Data Binding Expressions and Their Symbols

All data Binding Expressions are evaluated at runtime. There are three ways I know to include data binding expressions in ASP.NET. I don't find that Microsoft has defined any specific terms to distinguish them. For clarify and easy discussion, I would define ones here so that I can discuss and compare them.

These three (3) ways data binding expressions are:


Page-Level Data Binding
<%#  ...  %>

Example:

 <%# Request.MapPath("mytext.txt") %>
 <%# GetUserName() %>
 <%# MyAddress %>
 <%# 1 + 2 * 3 %>

The expression will be evaluated when you call DataBind() of the Page class or any other controls that support it such as the GridView, DetailsView, and FormView.  This expression can be applied to a reference to another control's property, a value of an object property, a member variable or a return value of a function. It can be placed anywhere in the ASPX file whenever it fits. For example,

  <title>
    <%# PageTitle %>
  </title>

  <img src="<%# GetImageFile() %>" alt="" />

  <asp:TextBox ID="txtFirstName" 
               runat="server" Text="<%# GetFirstName() %>" />

  <asp:HyperLink ID="lnkExample" 
                 NavigateUrl="<%# Example.Link.Value %>" 
                 Text="Example" runat="server" />

Page-level data binding is very common and easy to use. It also comes with two methods Eval and Bind. Eval provides readonly capability on data while data with Bind is updatable.

 <%# Eval("LastName") %>
 <%# Bind("FirstName") %>

For the detail how to use them, you can read more on your own.

Control-Level Data Binding
<%$  ...  %>

Example:

 <%$ ConnectionStrings:Northwind %>
 <%$ AppSettings:MyVariable %>

The expression will be evaluated when the page is rendered. There is no need to call DataBind(), unlike the page-level.

In addition, control-level data binding cannot be placed anywhere in the page by itself. Instead, it must be wrapped inside a control tag. The result of the expression is used to set that control's property. For example,

  <asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:Northwind %>"  ... /%>
where the <%$ and %> is used to extract the custom connection string from web.config.

Currently, there are only two build-in expressions available. One is to extract connection string from the web.config (see the above example) and the other is to extract application settings from web.config.

  <asp:Literal Text="<%$ AppSettings:MyVariable %>"  ... /%>

Although you can always make your own custom expressions through CodeDOM (Code Document Object Model), creating a custom expression to use is not an easy task.

Script-Level Data Binding
<%=  ...  %>

Example:

 <%= Request.MapPath("mytext.txt") %>
 <%= GetUserName() %>
 <%= MyAddress %>
 <%= 1 + 2 * 3 %>
 <%= myClass.Name %>
 <%= myClass.Execute %>

  <script language="javascript">
     location.href = <%= MyForwardPageUrl %>;
     ...
  </script>

Similar to the control-level, the expression will be evaluated when the page is rendered. Then, ASP.NET automatically inserts the value of the expression. There is no need to make any call to any DataBind() method either including Page.DataBind(). Similar to page-level, it can be placed anywhere in the markup page.

Monday, July 20, 2009

WebpartManager.ConnectWebparts Error

When executing the WebpartManager.ConnectWebparts() statement, I got the following error:

The ConnectWebParts method cannot be called after connections have already been activated (in WebPartManager.PreRender).

This problem occurred because I connected WebParts in Page_PreRender event.
     this.WebPartManager1.ConnectWebParts(provider, providerConnectionPoint,
                                          consumer, consumerConnectionPoint);

Moving it back to Page_Load event, everything works fine.

Sunday, July 12, 2009

Verify who is ASP.NET Logon User

Usually I use Request.LogonUserIdentity.Name to check ASP.NET Logon User. It works for all types of users.

      System.Web.HttpContext.Current.User.Identity.Name
or
      Request.ServerVariables["AUTH_USER"]

are only for Windows Authenticated user. For Internet users (anonymous guest), empty string is expected.

Request.LogonUserIdentity.Name will show you if the user is anonymous.

Sunday, June 21, 2009

Common ASP.NET problems related to IIS

The page cannot be found - return 404 for ASP.NET pages
OK button is grayed out while adding an IIS file mapping
Missing ASP.NET tab on IIS Manager
Parser Error: Could not load type

The page cannot be found - return 404 for ASP.NET pages

Make sure IIS is accepting the correct ASP.NET version. ASP.NET tab on IIS
On Windows 2003, you also need to ensure ASP.NET version is set to Allow for that ASP.NET version in Web Service Extensions. If you don't see ASP.NET extension, follow "Missing ASP.NET tab on IIS Manager" to install and enable it. After that, if you're running into the following error, your ASP.NET page probably has to run some shell command that requires additional permission.
   The compiler failed with error code 128.
   ...
   c:\windows\system32\inetsrv> "C:\WINDOWS\Microsoft.NET\Framework\v3.5\csc.exe" ...
In this case, go to Administrative Tools and select Services:
  • In the Services pane, locate World Wide Web Publishing Service.
  • Right-click World Wide Web Publishing Service, and then click Properties.
  • Click the Log On tab.
  • Click to clear the Allow service to interact with desktop checkbox.
  • Click OK.
Be sure to start the IIS and kill the browser before running the application again.

OK button is grayed out while adding an IIS file mapping

It is a small bug on IIS 5.1 with Windows XP.

To work around this:

After selecting the executable via the Browse... button, click on the textbox itself and the path will then be fully expanded. It in turn enables the OK button. [ref]



Missing ASP.NET tab on IIS Manager

Please ensure you have installed .NET framework first. For ASP.NET 2.0 or later, at the command prompt, do the following to install and enable ASP.NET on IIS:

%WinDir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -i -enable


Parser Error: Could not load type

You may experience the following error on IIS after you've published your ASP.NET application. But everything works fine in the Visual Studio. For example,

Parser Error Message: Could not load type 'SysAdmin.RunBatch'.

  • Check the Application Settings of your Web site or virtual directory, and then make sure there is Application name for it.
    • On IIS, right click the Web site or virtual directory, and then select Properties.
    • At Home Directory of Directory tab, click Create button to create the Application Name if it doesn't exist.
    • Execute Permissions must be at least set to Scripts only.
    • Click Apply and then OK to exit.
  • Check and ensure that the associated bin directory is resided with your aspx pages and Web.config. It is similar to the directory structure when you developed your application.

Friday, June 19, 2009

Add a file extension mapping on IIS for ASP.NET handler

  • Right click the Web site or the virtual directory and then select Properties.
  • Select Configuration button on Home Directory tab (for Web site) or Directory (for virtual directory).
  • On Mappings tab, click Add.
  • For ASP.NET 2.0 or later,
    Executable C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll
    Extension the file extension you want to map, e.g., .simple

    Here is an example.
    Add File Extension to IIS
  • Click OK, then Apply or OK.
  • Exit the wizard

Friday, April 10, 2009

How to enable script debugging on Internet Explorer

If you are debugging your code with Internet Explorer, be sure to enable your setting of script debugging.

On Internet Explorer, at the menu bar,

  • Choose Tools -> Internet Options
  • Click Advanced
  • Ensure to uncheck Disable script debugging (Internet Explorer) in the Browsing category.

How to enable script debugging on Internet Explorer

Windows Firewall Settings and IIS for ASP.NET

If you are using the built-in internal development/test server in Visual Web Developer Express or VS.NET for development, testing and debugging, there is nothing you should worry about the Windows Firewall settings. However, if you would like to test your Web application over the network on a local IIS Web server, you need to have the following setting changed on Windows Firewall setting:

On Windows XP,

  • Go Control Panel -> Windows Firewall
  • Select Advanced tab
  • On the Network Connection Services selection list, select one of the connection item, e.g., Local Area Connection, Wireless Network Connection, ... and etc.
  • Then click Settings...
  • Ensure that Web Server (HTTP) is checked.

On Windows Vista,

  • Go Windows Control Panel
  • Select the Exception tab
  • Ensure that World Wide Web Services (HTTP) is checked.