Sladescross's Blog

Blogging about Sharepoint related stuff

ASP.NET Primer November 28, 2013

Filed under: ASP.NET,Cache,Default,Default Namespace,Namespace,Root,Tutorial — sladescross @ 7:08 pm

The default namespaces are listed inside the pages element in the root web configuration file 
located at the following path:


protected void Page_Load(object sender, EventArgs e)

13.1.1.Overview of Caching

The ASP.NET 3.5 Framework supports the following types of caching:

Page Output Caching caches an entire page.

Partial Page Caching caches only particular regions of a page.

DataSource Caching caches different ASP.NET DataSource controls such as the SqlDataSource and ObjectDataSource controls.

Data Caching caches arbitrary objects in memory.

<head runat=“server”>
    <title>Cached object data source</title>
    <form id=“form1″ runat=“server”>
        <asp:GridView ID=“_peopleGridView” runat=“server” 
            EnableViewState=“False” />
        <asp:ObjectDataSource ID=“_personObjectDataSource” runat=“server” 
            EnableCaching=“True” SelectMethod=“GetPeople” DataObjectTypeName=“Person”
            TypeName=“SampleData” />    


Debugging ASP.NET Pages November 18, 2013

Filed under: ASP.NET,Debug,Debugging,Trace — sladescross @ 10:26 pm

Trace forwarding

ASP.NET 2.0 introduced new attribute to Web.config <trace> element that allows you to route messages emitted by ASP.NET tracing to System.Diagnostics.Trace:writeToDiagnosticsTrace.

< trace enabled =”true” requestLimit =”20″ writeToDiagnosticsTrace =”true ” pageOutput =”true”/>

When you set writeToDiagnosticsTrace to true, all calls to System.Web.UI.Page.Trace.Write(the ASP.NET TraceContent)  also go to System.Diagnostics.Trace.Write, enabling you to use all the standard TraceListeners.  The simple writeToDiagnosticsTrace setting connects the ASP.NET tracing functionality with the rest of the base class library.

New Trace Listeners in ASP.NET 2.0

The new ASP.NET 2.0 WebPageTraceListener derives from System.Diagnostics.TraceListener  and automatically forwards tracing information from any component calls to System.Diagnostics.Trace.Write.  This enables you to write your components using the most generic trace provider and to see its tracing output in the context of your ASP.NET application.

The WebPageTraceListener is added to the web.config as shown below.

< system.diagnostics>     <trace autoflush =”false” indentsize =”4″>       <listeners>         <add name=”webListeners”              type=”System.Web.WebPageTraceListener,  System.Web” />          </listeners>     </trace>


This walkthrough illustrated how to work with ASP.NET and System.Diagnostics tracing features to route all trace messages a single output. You might want to experiment more with trace listeners and output and ASP.NET instrumentation features. For example, you might want to do the following:
There are several ways to find errors in an ASP.NET Web page. This includes using the debugger and tracing. Tracing displays messages about the actions that occur during page processing, and can include information that you choose to display. Tracing also gives you information about the data that is being exchanged by the server and browser. The data exchange includes control details, server variables, user name, cookies, and so on. This walkthrough illustrates how to use tracing.

Visual Studio provides you with tools to help track down errors in your ASP.NET Web pages. In this walkthrough, you will work with the debugger, which allows you to step through the page’s code line by line and examine the values of variables.

In the walkthrough, you will create a Web page that contains a simple calculator that squares a number. After creating the page (which will include a deliberate error), you will use the debugger to examine the page as it is running.

The Visual Studio debugger has the ability to attach to a process that is running outside of Visual Studio. You can use this attach capability to do the following:

  • Debug an application that was not created in Visual Studio.
  • Debug multiple processes simultaneously. You can also debug multiple processes by starting multiple projects within a single solution.
  • Debug a process running on a remote computer.
  • Debug a DLL that runs in a separate process that cannot easily be started from Visual Studio, for example, a service or an ISAPI DLL running with Internet Information Services.
  • Start the debugger automatically when a process crashes while running outside of Visual Studio. This is Just-In-Time debugging.

You can control whether tracing is enabled or disabled for individual pages. If tracing is enabled, when the page is requested, ASP.NET appends to the page a series of tables containing execution details about the page request. Tracing is disabled by default.

Instead of enabling tracing for individual pages, you can enable it for your entire application. In that case, every page in your application displays trace information. Application tracing is useful when you are developing an application because you can easily enable it and disable it without editing individual pages. When your application is complete, you can turn off tracing for all pages at once.

When you enable tracing for an application, ASP.NET collects trace information for each request to the application, up to the maximum number of requests you specify. The default number of requests is 10. You can view trace information with the trace viewer.

By default, when the trace viewer reaches its request limit, the application stops storing trace requests. However, you can configure application-level tracing to always store the most recent tracing data, discarding the oldest data when the maximum number of requests is reached. For more information, see Application-Level Tracing Overview.

If you have enabled tracing for your application, when any page is requested, the page gathers trace information and executes any trace statements that it contains. You can view the trace output in the trace viewer. The trace viewer enables you to choose a specific request from the pages that have been requested from your application.

When you enable tracing for an application, you can display trace output in any page in the application by setting the pageOutput attribute of the trace element to true in the Web.config file.

To view trace details for a specific request

Navigate to Trace.axd in the root of your application.

For example, if the URL for your application is http://localhost/SampleApplication, navigate to http://localhost/SampleApplication/trace.axd to view the trace information for that application.

Select the View Details link for the request that you want to investigate.

To enable tracing for the page

  1. Open the FirstWebPage.aspx page and switch to Design view.
  2. In Properties, in the list, click DOCUMENT.This displays properties for the page.
  3. Set Trace to true.The trace setting is actually made as part of the @ Page directive. You can see this by switching to Source view and looking at the first line in the page. The @ Page directive will look similar to the following:
    <%@ Page language="C#"      Trace="true" %>

To view tracing output in a separate browser window

Press CTRL+F5 to run the page.

Notice that the page no longer displays trace output. The page looks the way a user would see it.

In the box, enter a name, and then click Submit to confirm that the page works correctly.

Open a new browser window.

In the browser, in the Address box, type the URL of your site, substituting trace.axd for the name of the page that you are working with.

For example, if the URL for the page is the following:






ASP.NET Page Life Cycle Ajax and Controls

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend.

If you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run control behavior code. The life cycle of a control is based on the page life cycle, and the page raises many of the events that you need to handle in a custom control.

Partial-page rendering removes the need for the whole page to be refreshed as the result of a postback. Instead, only individual regions of the page that have changed are updated. As a result, users do not see the whole page reload with every postback, which makes user interaction with the Web page more seamless. ASP.NET enables you to add partial-page rendering to new or existing ASP.NET Web pages without writing client script.

Debugging and tracing AJAX applications.

Configuring Internet Explorer for Debugging

By default, Internet Explorer ignores problems that it encounters in JavaScript. You can enable debugging by using the following procedure.

To enable debugging in Internet Explorer

  1. In the Tools menu, click Internet Options.
  2. In the Advanced tab, clear the Disable Script Debugging (Internet Explorer) check box and the Disable Script Debugging (Other) check box.
  3. Select the Display a notification about every script error check box.
  4. To turn off “friendly” error messages, clear the Show friendly HTTP error messages check box.If “friendly” error message are enabled and if an HTTP 500 error response from the server is less than 513 bytes long, Internet Explorer masks the content. In place of the error information, Internet Explorer displays a message that is meant for end users, not developers.

Attaching the Visual Studio Debugger to Internet Explorer

To debug client script, you must attach a debugger to Internet Explorer. In Visual Studio, if you start your application for debugging (by pressing F5 or using the Start Debugging command in the Debug menu), the debugger is attached automatically.

You can also attach the Visual Studio debugger to Internet Explorer when the application is already running. To do so, in the Debug menu, click Attach to Process…. In the Attach to Process dialog box, select the instance of Internet Explorer (iexplore.exe) that you want to attach the debugger to.

If Internet Explorer is configured for debugging, the Type column for the relevant instance of Internet Explorer displays Script, x86. If you see only x86 in the Type column, make sure that Internet Explorer is configured for debugging.

If Internet Explorer encounters a script error and is configured for script debugging, but it is not currently attached to a debugger, the browser prompts you to select a debugger. You can either continue without debugging or attach a debugger and step through the code.

The following list describes typical scenarios in which you are likely to develop your own controls and provides links to other topics for further information.

  • You have created an ASP.NET page that provides a user interface that you want to reuse in another application. You want to create a server control that encapsulates the user interface (UI) but do not want to write additional code. ASP.NET allows you to save your page as a user control without writing a single additional line of code. For details, see Web Forms User Controls.
  • You want to develop a compiled control that combines the functionality of two or more existing controls. For example, you need a control that encapsulates a button and a text box. You can do this using control composition, as described in Developing a Composite Control.
  • An existing ASP.NET server control almost meets your requirements but lacks some required features. You can customize an existing control by deriving from it and overriding its properties, methods, or events.
  • None of the existing ASP.NET server controls (or their combinations) meet your requirements. In that case, you can create a custom control by deriving from one of the base control classes. These classes provide all the plumbing needed by an ASP.NET server control, thus allowing you to focus on programming the features you need. To get started, see Developing Custom Controls: Key Concepts and Developing a Simple ASP.NET Server Control.

Many custom controls involve a combination of scenarios, where you combine existing ASP.NET server controls with custom controls that you have designed.

Note   The authoring paradigm outlined in the first bullet (user controls) is very different from that for the other scenarios. User controls are written using the same programming model as ASP.NET pages, and they are ideal for rapid control development. The other scenarios involve object-oriented programming in languages that target the common language runtime, such as Visual Basic .NET and C#. A user control is saved as an .ascx page, which is a text file, while the other scenarios create controls that are compiled and persisted in assemblies. For a summary of differences, see Composite Control vs. User Control.



Async in 4.5: Enabling Progress and Cancellation in Async APIs – .NET Blog – Site Home – MSDN Blogs

Filed under: ASP.NET,Asynch,Asynchronous,Cancellation,Progress — sladescross @ 1:36 pm


ASP.NET Pipeline November 21, 2010

When you create a new IIS website, IIS registers the site with http.sys, which then receives all HTTP requests for any web application within the site. The http.sys functions as a forwarder, directing the HTTP requests to the User mode process that runs the web application. In this case, the User mode process is the worker process running the application pool which the web application runs under. The http.sys implements a queuing mechanism by creating as many queues as there are application pools in IIS.

Following up with our example, once the request reaches “myserver”, http.sys picks up the request. Let us say that “myapplication” is configured to run under the application pool “myapplicationpool”; in this case, http.sys inspects the request queue of “myapplicationpool” and forwards the request to the worker process under which “myapplicationpool” is running under.

OK, so now, the request is forwarded to the application pool as explained in the previous section. Each application pool is managed by an instance of the worker process “w3wp.exe”. The “w3wp.exe” runs, by default, under the “NetworkService” account. This can be changed as follows: right click on the application pool hosting your application–Properties–Identity tab. Recall that the application pool is run by the worker – the “w3wp.exe”. So now, the worker process takes over.

The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. The requested resource in the URL is “mypage.aspx”. So, what happens next? A full discussion of ISAPI extensions (and filters) is beyond the scope of this article, but in short, ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS. IIS maps various extensions to its ISAPI extensions. You can see the mappings in IIS as follows: right click on the website-Properties-Home Directory tab-Configuration button-Mappings tab. The figure below shows the mappings:

ISAPI extensions and filters.

ISAPI Extensions and Filters
Before ASP.NET, the only way to process custom file extensions was to write an ISAPI (Internet Service Application Programming Interface) extension or an ISAPI filter. However, writing ISAPI extensions and filters is difficult, requires strong C/C++ skills, and is considered “out of reach” for many programmers. ASP.NET improves the situation greatly. ASP.NET’s HttpExtensions and HttpModules provide functionality similar to ISAPI Extensions and ISAPI filters, respectively. Writing HttpHandlers and HttpModules is just a matter of implementing certain interfaces.

HttpExtensions let you process a particular extension (or a set of extensions) using custom code.

Similarly, HttpModules let you filter client requests. For example, you could use an HttpModule if you wanted to manipulate the requested URL by changing the file names before letting the ASP.NET engine handle the request—thus hiding the real file names from the clients. Unlike HttpExtensions, HttpModules execute for every request—irrespective of the file extension. You can create an HttpModule to tweak the request either before or after the appropriate handler processes it.

HttpModules intercept each request to Web application resources. The class that is to act as HttpModule must implement an interface called IHttpModule. Again, the interface is simple:


Page Life-Cycle October 21, 2010

Filed under: ASP.NET,Page Life-Cycle — sladescross @ 11:08 pm


Debugging ASP.NET Permissions June 8, 2010

Filed under: ASP.NET,Permissions Debugging — sladescross @ 10:49 am


Sharepoint How To Add ASP.NET Page To _layouts or site December 22, 2009

Filed under: ASP.NET,ASP.NET Sharepoint Integration,Sharepoint,_layouts — sladescross @ 10:35 am

HTTPModule and HTTPHandler.


Create a web application project that can be deployed to the SharePoint /_layouts virtual directory, so my code is executed in the context of a site.

The solution happens to be really easy:

Create a web application project, either directly in the /_layouts folder or somewhere else and copy over all files needed to run your application.

The *.dll and *.pdb files produced as build output must be places in the bin folder of your SharePoint web site. In my test situation this is the folder C:\Inetpub\wwwroot\wss\VirtualDirectories\3a938f6a-15f2-49ae-be78-328ad78974f5\bin. You can find this folder in your Internet Information Server Manager as follows:

•Right-click of the SharePoint web site
•Select properties
•Go to the Home Directory tab
The value in Local Path specifies the path to the virtual directory, and in this virtual directory you find a folder bin.


1.The SharePoint designer approach: This approach can be used if there are few aspx pages with little functionality.
2.Using web parts. This can be used in conjunction with SharePoint designer. But once again, developing many web parts is not feasible and also raises performance issues.
3._Layouts folder approach: This is the simplest of all. Just deploy the web application pages under the _layouts folder of SharePoint and the pages can be accessed from any SharePoint site. Cons: The pages don’t inherit the security and access rules from SharePoint. The pages can be accessed from any site existing on that server farm. Master Page integration is not possible. MSDN Article explains with a sample.
4.User controls using Smart Part: In this approach, the developer can develop web parts using the third party Smart Part control. In this way the developer can have the drag – drop functionality as he/she can develop it as a user control and drop it in the smart part. This method is similar to web parts but the developer has the privilege of drag-drop functionality but it still carries the negatives mentioned for the web parts approach.
5.Using features and WSP package: Following some steps as recommended by Andrew Connell (MOSS MVP). Here is the blog. I believe this is the standard approach users are using in the SharePoint developer community.
6.Using VSeWSS (Visual Studio extensions for WSS): This is yet another and latest solution. Microsoft recently released the VSeWSS 1.1 RTM. Using this, we can deploy all the asp .net pages into SharePoint by setting up a new project in Visual Studio. VSeWSS creates a solution package using features. Setup the project and hit ‘Deploy’ and it is done.


In native ASP.NET 2.0 sites, adding new pages involves dropping a new ASPX file into the desired folder in the site. In SharePoint, while it is possible to drop files within the webroot of the SharePoint site, it is not recommended. Rather, developers should create a template (just an ASP.NET 2.0 file) and then provision an instance of the file into the SharePoint site that points to the file on the file system. In both environments, the assembly containing the compiled code behind file of the ASP.NET 2.0 page is deployed to either the site’s \BIN directory or the server’s GAC.

There are two main differences in creating custom ASPX pages for use in a SharePoint site vs. an ASP.NET 2.0 site is that the file you create (ASPX) is used as a template for the real file (instance) within the SharePoint site. After creating the ASPX page, an instance needs to be provisioned into the SharePoint site. This is done using a SharePoint Feature.

Next, create the ASPX page that will be added to the SharePoint site and put it in the Feature folder: SharePointCodeBehindPage. With the file created, add whatever is necessary to implement the page the way you want it. The one thing to point out is you should use one of the four SharePoint master page tokens as the value in the MasterPageUrl attribute in the Page directive.

With the ASPX page and code behind created, now the two need to be linked together. Recall how Visual Studio does it… it adds an Inherits attribute to the Page directive in the ASPX automatically. So… we can do it manually! So what do we put in this attribute? The full name to the type, or class, of our page object. This is also known as the 5-part name. The five parts are: [full type name], [assembly name], [version], [culture], [public key token]. Everyone has different ways of getting this. One of the easiest is to build the project and then open the file using Lutz’s Reflector. This gives you the last four parts of the name, also called the assembly full name. Note that the type name needs to also include the namespace. For the code in Figure 3 above, here’s what my Inherits attribute is (note: don’t include the line breaks in the Inherits attribute as shown in the image… they are present just for readability):

If you look at the inheritance hierarchy for WebPartPage, it is inherited from System.Web.UI.Page (the one that is inherited from for ASP.NET pages).







ASP.NET Impersonation and Security October 2, 2009

Filed under: ASP.NET,Authentication,Impersonation — sladescross @ 9:56 am

Sharepoint security and ASP.NET impersonation.


To make Windows security integration possible, SharePoint utilizes .NET impersonation. .NET Impersonation allows an application to run under the context of the client accessing an application. With ASP.NET impersonation, IIS is responsible for authenticating users against the domain and passing to ASP.NET an authenticated token, which can then act on behalf of the client. ASP.NET impersonation can be defined implicitly through configuration settings, or, as covered later in this article, explicitly through code. A close look at the web.config file for a SharePoint site reveals the implicit impersonation configuration for a SharePoint installation running under Integrated Windows Authentication mode:

<identity impersonate="true" />

This setting instructs ASP.NET to implicitly act on the behalf of the client who is accessing SharePoint.

The Problem

The time will come during a SharePoint customization project where a developer will want .NET code to perform some action that all users of the SharePoint site do not have the permission to perform. For example, accessing and displaying data from lists on other SharePoint sites and virtual servers (through the SharePoint object model), accessing Active Directory, or pushing files to a non-public shared drive. A developer may even need to access data from a SQL Server instance that requires Windows Authentication. Some users will possess the necessary permissions to perform these operations while others won’t, and we certainly do not want to grant these permissions to everyone.

There are several steps involved with performing explicit impersonation, which I have wrapped up into a class called Impersonator (download here). The steps for impersonation are as follows:

  1. Authenticate a valid account which possesses the proper permissions to perform the necessary operations
  2. Create a new System.Security.Principal.WindowsIdentity instance that represents the account
  3. Begin impersonating the new Windows identity
  4. Perform actions that require higher permission level
  5. Stop impersonating and revert back to the client’s identity

The goal of wrapping these steps into one class is to write the following simple code to begin impersonation, execute code under the context of a different domain user account, and revert back to the original security context of the client:

Impersonator i = new Impersonator("SharePointRead", "MARINER", "password123").Impersonate();

With ASP.NET impersonation, the thread servicing the client request can optionally execute with the identity of the client. Let me explain it in detail.

IIS always maps a user request to some Windows account; in case of anonymous access, this is IUSR_machinename account or any other account that has been defined to be used with anonymous access; in the case of Windows authentication, this is the account whose credentials are provided by the Web site user. After successful authentication, IIS forwards this logged-in user’s identity to the ASP.NET worker thread. Now the ASP.NET worker thread has the following three options:

  • It can run under the identity defined by the <processModel> tag.
  • It can run under the client identity passed to it by IIS.
  • It can run under the identity of the user whose credentials have been listed for impersonation.

Now the decision depends on the impersonation settings for the ASP.NET application.

  • If impersonation is enabled and any specific Windows account has not been listed in the Web.config file for impersonation, then the ASP.NET worker thread runs under the client identity passed to it by IIS.
  • If impersonation is not enabled, then the ASP.NET worker thread runs under the identity of the ASP.NET worker process (which has been defined by using the <processModel> tag in the Web.config file)
  • If impersonation is enabled and a specific Windows account has been listed in the Web.config file for impersonation, then the ASP.NET worker thread runs under the identity generated using that account.

Impersonation for ASP.NET applications can be set up by using the <identity> tag in the Web.config file. We can specify impersonation in the following three ways: 

  • <identity impersonate=”true”/> This means impersonation for the ASP.NET worker thread is enabled.
  • <identity impersonate=”true” name=”username” password=”password”/> This means impersonation for the ASP.NET worker thread is enabled, but the worker thread will run under the identity that will be generated by using the credentials specified by username and password attributes.
  • <identity impersonate=”false”/> This means impersonation for the ASP.NET worker thread is not enabled.

ASP.NET works differently. It runs under the account that the process was started under originally. This means ASPNET or NETWORK SERVICE or if you’re using IIS 6 the account you have specifically configured for your Application Pool. So while ASP.NET provides different Authentication models to let you see who logged on to secure areas of your Web site via Forms or Windows Authentication, the underlying account in this scenario never changes. The Authentication is merely a tool for your application, but it doesn’t change the underlying security context.

This is a good thing and something that wasn’t really easily possible with classic ASP. You can however revert to the Impersonation model that works just like classic ASP by turning Impersonation on in web.config:


  <location path=”admin”>


      <identity impersonate=”true” />

      <!– WS: Allow only Authenticated users –>


        <!– allow users=”*”/ –>

        <deny users=”?” />





Really good article on ASP.NET Impersonation and Delegation.


ASP.NET Connection Strings In Web.Config September 23, 2009

Filed under: ASP.NET,Web.Config — sladescross @ 7:36 pm



     <add key=”ConnectionString”

          value=”server=localhost;uid=sa;pwd=;database=DBPerson” />





Get every new post delivered to your Inbox.

Join 63 other followers