C# This operation requires IIS integrated pipeline mode.

When trying to add Http Headers to your Response object you may get the error “This operation requires IIS integrated pipeline mode.” This is what looks like a bug in the .net framework. In order to work around this issue you should add the Http Headers to the Response using the following format.

HttpContext.Current.Response.AddHeader("ContentType", "application/x-www-form-urlencoded");

JavaScript: Locate ASP.net Controls in HTML Markup

In ASP.net all controls are assigned a Unique Identifier (ID) so they can be referenced within your C# or VB code with ease. Most of use would, at least at first, assume we can use those very same ID’s in our JavaScript to manipulate those controls client side as well. Unfortunately not!

This is because ASP.net pages are made up of 10’s possibly 100’s of controls and any of those controls might be found embedded within other controls and its really hard to come up with unique ID’s for 100+ controls specially when you don’t the names used in 3rd party controls or the controls that come built into ASP.net. In order to handle these situations and in order to guarantee that each and every control has a unique ID within the HTML markup that gets generated .Net uses what are known as Naming Containers.

Naming Containers define a unique Namespace for all control ID’s within itself. There can be multiple Naming Containers on a page each with their own unique id, and each of these can then contain controls each with a unique id. But what is cool about it all is the unique ID’s can be reused across all the Naming Containers on a page. So a control named txtName can exist in more than one Naming container, but it has to remain unique within each of the containers.

Because of this Namespacing there becomes a need to guarantee that each control has a unique name in the rendered HTML. In order to accomplish this ASP.net pre-pends each unique control ID with each of its preceding Naming Containers up the chain. When you look for your control ID’s within the rendered markup you will see something like this ‘dnn_ctr8143_CrudImage_fuImage’.

This of course makes it very difficult to get a hold of your controls from within JavaScript. As long as your JavaScript is being rendered with the page by ASP.net there is a solution. You simply need to add a tag to your JavaScript on in your page or control markup which will give you the id of the control as it will appear within the final rendered markup. Or if you are adding scripts dynamically from within your C# or VB you can use a property of the control to get the id. The methods are as follows:

Within ASP.net Markup

Hide this content!
<div onclick="HideControl();return false;">

Dynamically C#

btnHide.OnClientClick("HideControl(" + pnlContent.ClientID + ");return false;");

ASPNET Membership: Remove Users and Their Data

To remove inactive users or trouble users from your ASP.net Memebership tables use the following SQL script.

DECLARE @UserName nvarchar
SET @UserName = ‘USER NAME HERE’

DECLARE @UserId uniqueidentifier
SET @UserId = (SELECT UserId FROM aspnet_Users WHERE UserName = ‘Admin2017’)

DELETE FROM aspnet_Profile WHERE UserID = @UserId
DELETE FROM aspnet_UsersInRoles WHERE UserID = @UserId
DELETE FROM aspnet_PersonalizationPerUser WHERE UserID = @UserId
DELETE FROM aspnet_Membership WHERE UserID = @UserId
DELETE FROM aspnet_users WHERE UserID = @UserId

ASP.net Retrieving Embedded Resources with WebResource.axd

Say we are building a ASP.net Server Control which contains a lot of images, style sheets and its own .htm help files which also reference several images of their own. This can create a lot of clutter when it comes to packaging and deploying the Server Control. Also due to the many files and folders which categorize and hold all of those images, style sheets and help files there is always the possibility a curios developer using your Server Control might try to rearrange things or substitute content of their own thus breaking the control or maliciously altering the control. In order to clean all this up and solve a lot of these issues in a single blow we can simply embed all these resources right into our assembly (.dll). By doing this we tightly package all resources used by the Server Control and can potentially limit our deployment to just a single assembly (.dll).

So how do we do this? It’s quite easy just follow the steps outlined below.

Step 1: You need to decide which resources you want to have embedded in the assembly. In the example project I chose to embed the style sheet (FancyButtonStyle.css) which defines the way my FancyButton will look as well as the Solution Explorerbackground image (Thundercats.pnd) that is defined within the style sheet. You embed them into the assembly by selecting the file in the Solution Explorer and viewing the properties of the file. In the Properties window there is a property ‘Build Action’ set it to Embedded Resource.

Step 2: Next each of those embedded resources need to be declared in the AssemblyInfo.cs file. Using the WebResource keyword you place the fully qualified path to the resource you are embedding as the first parameter then as the second the mime-type. The third parameter defines whether or not substitution needs to take place within the newly defined resource. What this means is that within resources of mime-type “text” you can define script tags which also define that there are embedded resource url’s within the file. For example within the style sheet ‘FancyButtonStyle.css’ we defined a background-image which has a url property of another embedded resource, the Thundercats.png file. The PerformSubstitution tells .net to parse through the text resources after it is pulled from the assembly and look for script tags which hold the names of embedded resources which need to have their URL generated and inserted into the document. (see thumbnails: AssemblyInfo.cs, Stylesheet)

Step 3: Now write the code within your control’s RenderContents method which will pull out the embedded resources’ URL’s and use them within the HTML to be rendered for the control. (see thumbnail: Render Contents Method)

Solution Explorer
Solution Explorer
Render Contents Method
Render Contents Method

AssemblyInfo.cs
AssemblyInfo.cs
Stylesheet
Stylesheet

ASP.net Checking for an AJAX ScriptManager on the Current Page

Depending on the way in which you have designed your web application (Master Pages, Master Pages within Master Pages, Templates, Embedded Controls)  or if you are using a out of the box framework you may or may not know if an AJAX ScriptManager has been loaded on the current page. Lets say you have a custom control which uses the built in .Net AJAX library in order to function correctly. Instead of just assuming a ScriptManager has been placed on the page by the original page or framework developer and possibly experience exceptions caused by the lack of a ScriptManager or placing one within your control and possibly experiencing exceptions due to too many ScriptManagers on the page, you should simply check the page first. If no ScriptManager is available then add one dynamically from within your control.

A ScriptManager must be placed in the Page’s Form and there can only be one per page. The following code example checks the current page to see if a ScriptManager has been loaded, if so the control loads normally, if not a ScriptManager is instantiated and added to the current Page.Form.Controls collection and the control is then loaded.

You will also notice in this code block that I have set the AsyncPostBackTimeout to a large number. I have found on several occasions that when there are long running processes called through AJAX calls the default timeout is way too short. This timeout needs to be increased otherwise the call times out and your update panels never complete their update.

        protected void Page_Load(object sender, EventArgs e)
        {
            if (
ScriptManager.GetCurrent(this)
== null)
            {
                sManager = new ScriptManager();
                sManager.AsyncPostBackTimeout = 999999;
                Form.Controls.Add(sManager);
            }
        }

Work-Around Browser Cache when it comes to Profile Images

If you allow users to change their profile pictures or if there are images which are frequently updated by users and those images use a standard name you can work-around browser caching by adding a version number to the image name when it is saved to the disk and stored in a database.

      //Set the image path.
      if (fileUpload.HasFile)
      {
        try
        {
          string imageFilePath = PortalSettings.HomeDirectoryMapPath;
          string imageName = USER_IMAGE + "." + 0 + ".jpg";
          if (!string.IsNullOrEmpty(location.UserImagePath))
          {
            //Find out what version the current file is at
            string[] parts = location.UserImagePath.Split('.');
            if (parts.Length == 3)
            {
              int version = int.Parse(parts[1]);
              int nextVersion = version + 1;
              imageName = USER_IMAGE + "." + nextVersion + ".jpg";

              string oldImagePath = imageFilePath + location.UserImagePath.Remove(0, 1);
              if (System.IO.File.Exists(oldImagePath))
                System.IO.File.Delete(oldImagePath);
            }
          }

          fileUpload.SaveAs(imageFilePath + imageName);
          location.UserImagePath = "/" + imageName;
          imgUserImage.ImageUrl = "/" + imageName;
          imgUserImage.Visible = true;
          AddImageToCache(imageFilePath + imageName);
        }
        catch (Exception ex)
        {
          if (ExceptionHandler.ProcessException(ex, ExceptionPolicy.General, ModuleConfiguration))
            throw;
        }
      }