Below is a picture of the HTTP Request Pipeline and its three replaceable component types: HttpHandler, HttpApplication, and HttpModule. As requests come in, they are queued up and assigned to a worker thread that then processes the request by interacting with each of these component types. Figure 2-4: The HTTP Request Pipeline allows developers to replace components such as HttpHandler, HttpApplication, and HttpModule. The ultimate destination of any request is the endpoint, which is modeled in the HTTP Request Pipeline by using an HttpHandler class, which implements the IHttpHandler interface. As a developer, you can create a custom HttpHandler component and plug it into the HTTP Request Pipeline by adding configuration elements to the web.config file. The HTTP Request Pipeline places an HttpApplication component in front of the HttpHandler. On an application-wide basis, incoming requests are always routed through the HttpApplication before they reach the target HttpHandler, thus giving the HttpApplication the ability to pre-process any request no matter which HttpHandler it is being routed to. This preprocessing stage is handled through a series of events that are defined inside the HttpApplication class such as BeginRequest, AuthenticateRequest, and AuthorizeRequest. In situations when you don’t want to use a custom HttpApplication component, the ASP.NET Framework initializes the HTTP Request Pipeline with a standard HttpApplication object that provides default behavior. However, you can replace this standard component by creating a file named global.asax and placing it in the root directory of the hosting ASP.NET application. For example, you can create a global.asax that looks like the following: <%@ Application Language="C#" %>
<script runat="server">
protected void Application_AuthenticateRequest(object sender, EventArgs e) {
// your code goes here for request authentication
}
protected void Application_AuthorizeRequest(object sender, EventArgs e) {
// your code goes here for request authorization
}
</script>
The third replaceable component type in the HTTP Request Pipeline is the HttpModule. The HttpModule is similar to the HttpApplication component in that it is designed to handle events defined by the HttpApplication class and is processed before control is passed to any HttpHandler classes. For example, you can create a custom HttpModule component to handle request-level events such as BeginRequest, AuthenticateRequest, and AuthorizeRequest. As with the HttpHandler, an HttpModule class is defined with an interface. You can create a class that implements the IHttpModule interface and plug it into the HTTP Request Pipeline by adding configuration elements to the web.config file.
Whereas custom HttpApplication components can be defined as simple text files with an .asax extension, custom HttpModule components are always compiled as classes within assembly DLLs. To add a custom HttpModule component into the HTTP Request Pipeline, you then add entries into a web.config file.
While an HttpApplication component and an HttpModule component are similar in what they do, the HttpModule contains a few noteworthy differences. First, you are not limited to one HttpModule per application as you are with the HttpApplication components. The web.config file for an ASP.NET application can add in several different HttpModule components. Second, HttpModule components can be configured at the machine level. In fact, the ASP.NET Framework ships with several different HttpModule components that are automatically configured at the machine level to provide ASP.NET functionality for things such as Windows authentication, Forms authentication, and output caching.
The final component that we want to discuss with respect to the HTTP Request Pipeline is HttpContext. As ASP.NET initializes a request to send to the HTTP Request Pipeline, it creates an object from the HttpContext class and initializes it with important contextual information.
From a timing perspective, it’s important to see that ASP.NET creates this object before any custom code inside the HTTP Request Pipeline has a chance to begin execution. This means that you can always program against the HttpContext object and the child objects that it contains, such as Request, User, and Response. Whenever you are authoring a component that is to execute within the HTTP Request Pipeline, you can write code that looks like the following: HttpContext currentContext = HttpContext.Current;
string incomingUrl = currentContext.Request.Url;
string currentUser = currentContext.User.Identity.Name;
currentContext.Response.Write("Hello world");
Model-view-presenter (MVP) is a recent variation on MVC that’s designed to fit more easily with stateful GUI platforms such as Windows Forms or ASP.NET WebForms. You don’t need to know about MVP when you’re using ASP.NET MVC, but it’s worth explaining what it is so you can avoid confusion.
In this twist, the presenter has the same responsibilities as MVC’s controller, plus it also takes a more hands-on relationship to the stateful view, directly editing the values displayed in its UI widgets according to user input (instead of letting the view render itself from a template). There are two main flavors:
• Passive view, in which the view contains no logic, and merely has its UI widgets manipulated by the presenter.
• Supervising controller, in which the view may be responsible for certain presentation logic, such as data binding, having been given a reference to some data source in the model.
The difference between the two flavors is quite subjective and simply relates to how intelligent the view is allowed to be. Either way, the presenter is decoupled from the GUI technology, so its logic can be followed easily and is suitable for automated testing In this architecture, requests are routed to a controller class, which processes user input and works with the domain model to handle the request. While the domain model holds domain logic (i.e., business objects and rules), controllers hold application logic, such as navigation through a multistep process or technical details like authentication. When it’s time to produce a visible UI for the user, the controller prepares the data to be displayed (the presentation model, or ViewData in ASP.NET MVC, which for example might be a list of Product objects matching the requested category), selects a view, and leaves it to complete the job. Since controller classes aren’t coupled to the UI technology (HTML), they are just pure, testable application logic.
• WebForms takes the view that UIs should be stateful, and to that end adds a sophisticated abstraction layer on top of HTTP and HTML, using ViewState and postbacks to create the effect of statefulness. This makes it suitable for drag-and-drop Windows Forms–style development, in which you pull UI widgets onto a canvas and fill in code for their event handlers.
• MVC embraces HTTP’s true stateless nature, working with it rather than fighting against it. It requires you to understand how web applications actually work; but given that understanding, it provides a simple, powerful, and modern approach to writing web applications with tidy code that’s easy to test and maintain over time, free of bizarre complications and painful limitations.
There are certainly cases where WebForms is at least as good as, and probably better than, MVC. The obvious example is small, intranet-type applications that are largely about binding grids directly to database tables or stepping users through a wizard. Since you don’t need to worry about the bandwidth issues that come with ViewState, don’t need to be concerned with search engine optimization, and aren’t bothered about testability or long-term maintenance, WebForms’ drag-and-drop development strengths outweigh its weaknesses.
On the other hand, if you’re writing applications for the public Internet, or larger intranet applications (e.g., more than a few person-month’s work), you’ll be aiming for fast download speeds and cross-browser compatibility, built with higher-quality, well-architected code suitable for automated testing, in which case MVC will deliver significant advantages for you.
http://adamnoffie.blogspot.com/2007/03/aspnet-forms-authentication-strange.html the login.aspx page would be missing all of the style information from our CSS style sheet Solution - made a second Web.config and placed it in my App_Themes directory where my style sheet lives. <system.web> <authorization> <allow users="*"> </allow> </authorization> </system.web> or use <location path="App_Themes" allowOverride="false"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location>
http://www.4guysfromrolla.com/articles/052406-1.aspx http://www.ezzylearning.com/tutorial.aspx?tid=5187857 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
</asp:GridView><asp:GridView ID="FileList" runat="server"
AutoGenerateColumns="False" DataKeyNames="FullName">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="RowLevelCheckBox" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="CreationTime" HeaderText="Created On">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:BoundField DataField="Length" DataFormatString="{0:N0}"
HeaderText="File Size"
HtmlEncode="False">
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
</Columns>
</asp:GridView>
Protected Sub DeleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DeleteButton.Click
Summary.Text = "The following file would have been deleted:<ul>"
Dim currentRowsFilePath As String
'Enumerate the GridViewRows
For index As Integer = 0 To FileList.Rows.Count - 1
'Programmatically access the CheckBox from the TemplateField
Dim cb As CheckBox = CType(FileList.Rows(index).FindControl("RowLevelCheckBox"), CheckBox)
'If it's checked, delete it...
If cb.Checked Then
currentRowsFilePath = FileList.DataKeys(index).Value
Summary.Text &= String.Concat("<li>", currentRowsFilePath, "</li>")
End If
Next
Summary.Text &= "</ul>"
End Sub
http://learn.iis.net/page.aspx/140/understanding-the-built-in-user-and-group-accounts-in-iis-70/ In previous versions of IIS, we had a local account created at install time called IUSR_MachineName. The IUSR_MachineName account was the default identity used by IIS whenever anonymous authentication was enabled. This was used by both the FTP and HTTP services. There was also had a group called IIS_WPG, used as a container for all the application pool identities. We made sure all the appropriate resources on the system had the correct permissions set for the IIS_WPG group during IIS setup so that an administrator only needed to add their identity to that group when they created a new application pool account. This model worked well, but had its drawbacks: the IUSR_MachineName account and IIS_WPG group were both local to the system it was created on. Every account and group within Windows is given a unique number called a SID (security identifier) that distinguishes it from other accounts. When an ACL is created only the SID is used. As part of our design in previous versions of IIS, we had included the IUSR_MachineName in the metabase.xml file so that if you tried to copy the metabase.xml from one machine to another, it would not work--the account on the other machine would have a different name. In addition, you could not just 'xcopy /o' ACLs from one machine to another since the SIDs were different machine to machine. A work around was to use domain accounts--but that required adding an active directory to the infrastructure. The IIS_WPG group had similar issues with permissions. If you set ACLs on one machine's file system for IIS_WPG and tried to 'xcopy /o' those over to another machine, it would fail. The IIS team heard this feedback and improved this experience by using a built-in account and group in IIS 7.0. A built-in account and group are guaranteed by the operating system to always have a unique SID. IIS 7.0 has taken this further and ensured the actual names used by the new account and group will never be localized. For example, regardless of the language of Windows you install, the IIS account name will always be IUSR and the group name will be IIS_IUSRS. In summary, IIS 7.0 offers: - The IUSR built-in account replaces the IUSR_MachineName account
- The IIS_IUSRS built-in group replaces the IIS_WPG group
Since the IUSR account is a built in account, it no longer needs a password. Logically, think of it as being the same as NETWORKSERVICE or LOCALSERVICE accounts. Both the new IUSR account and IIS_IUSRS group are discussed in greater depth in the sections below.
HttpContext.Request.PhysicalApplicationPath + strYourImageFolderName\Image;
From http://www.codethinked.com/ Simone Chiaretta’s CodeClimber - A good friend, and a better blogger. Simone is an ASP.NET MVP and is co-writing the book “Beginning ASP.NET MVC 1.0” by Wrox. Simone blogs about all sorts of different ASP.NET MVC topics, and will certainly bring tons more content once he finishes his book. He is also an active developer on the Subtext project. Stephen Walther - Stephen is a Senior Program Manager at Microsoft where he creates much of the tutorial content on the www.asp.net/mvc website. Somehow he also finds time to put up tons of helpful posts on his personal blog. He is also authoring the book “ASP.NET MVC Framework Unleashed” by Sams. Kazi Manzur Rashid - Kazi is surprisingly the only person on this list who isn’t writing a book! He is also an ASP.NET MVP and his claim to fame is dotnetshoutout.com (which is a great site) and the open source Kigg project. He writes tons of posts on ASP.NET MVC, and has recently been on quite a run with many lengthy and in-depth articles. Maarten Balliauw - Maarten is authoring the book ASP.NET MVC 1.0 Quickly by Packt. I’m not sure how Maarten has time to write the book and his blog, because he has been pumping out quite a few awesome ASP.NET MVC posts recently. Steve Sanderson - Steve is the author of Pro ASP.NET MVC Framework by Apress and like these other guys, still finds time to write some good informative posts on his blog. He is also the author of the xVal validation framework which aims to help developers more easily tie domain validations to the front-end web application. Luis Abreau – This one is a bonus, and was added because of Marwan's comment below. I went and checked it out, and there are many great little ASP.NET MVC tidbits on this guys blog. Too bad there isn't much information about him at all. It looks like he might be a current or former MVP, I don't know. He has a linked in profile, but not too much info there other than the fact that he is in Portugal. So lots of good ASP.NET MVC information, but other than that, I don't know what to tell you about the guy!
http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx
App-Domain could not be created. Error: 0x80131902Mike Stone tonight came across an interesting issue, not with rainbow, but an issue nonetheless. When he downloaded and went to run Rainbow 2.0 He came accross the following message "Failed to execute request because the App-Domain could not be created. Error: 0x80131902" Basically, this happens on first time 2.0 runs sometimes, not sure why, but the following seems to fix the problem. My suspicions and research lead me to believe it has to do with web servies referenced. To fix it, try the following.... - With a command window, get to the latest version of .net under
- C:\Windows\Microsoft.Net\Framework\
- Now run the following command: "net stop w3svc" to stop web services.
- Then use "aspnet_regiis.exe -ua" to uninstall all instances of ASP.NET from IIS.
- Follow with "aspnet_regiis.exe -i" to install ASP.NET into IIS.
- Now restart web services with "net start w3svc".
Published venerdì 10 marzo 2006 4.52 by Jonathan
http://www.15seconds.com/issue/020417.htm ASP.NET request processing is based on a pipeline model in which ASP.NET passes http requests to all the modules in the pipeline. Each module receives the http request and has full control over it. The module can play with the request in any way it sees fit. Once the request passes through all of the HTTP modules, it is eventually served by an HTTP handler. The HTTP handler performs some processing on it, and the result again passes through the HTTP modules in the pipeline.  Notice that during the processing of an http request, only one HTTP handler will be called, whereas more than one HTTP modules can be called.
IIS 6 doesn't handle extensionless URLs. You'll need to change your routes to use the .mvc extension. For example, routes.Add(new Route("Links.mvc/{categoryName}",... Make sure that IIS 6 maps .mvc to the aspnet_isapi.dll.
<ItemTemplate>
<tr class='<%# (Container.DataItemIndex % 2 == 0)?"even":"odd" %>'> <td> <asp:LinkButton ID="EditButton" CommandName="Edit" runat="server" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="DeleteButton" OnClientClick="return confirm('Delete Record?');" CommandName="Delete" CommandArgument='<%# Eval("CustomerID")%>' runat="server" Text="Delete"></asp:LinkButton>
</td>
<td>
<%# Eval("CustomerID") %>
</td>
<td>
<%# Eval("CompanyName") %>
</td>
<td>
<%# Eval("ContactName") %>
</td>
<td>
<%# Eval("ContactTitle") %>
</td>
<td>
<%# Eval("Address") %>
</td>
<td>
<%# Eval("City") %>
</td>
<td>
<%# Eval("Country") %>
</td>
<td>
<asp:LinkButton ID="lbOrders" runat="server" Text="Orders" CommandName="ViewOrders" CommandArgument='<%# Eval("CustomerID") %>' />
</td>
</tr>
<tr id="trOrders" runat="server" visible="false">
<td> </td>
<td colspan="8">
<asp:GridView id="gvOrders" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black"
GridLines="Vertical" Width="500px" EnableViewState="false">
<FooterStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID"
SortExpression="OrderID" />
<asp:BoundField DataField="OrderDate" HeaderText="OrderDate"
SortExpression="OrderDate" HtmlEncode="false" DataFormatString="{0:d}" />
<asp:BoundField DataField="RequiredDate" HeaderText="RequiredDate"
SortExpression="RequiredDate" HtmlEncode="false" DataFormatString="{0:d}" />
<asp:BoundField DataField="ShippedDate" HeaderText="ShippedDate"
SortExpression="ShippedDate" HtmlEncode="false" DataFormatString="{0:d}" />
</Columns>
<AlternatingRowStyle BackColor="#eaeaea" />
</asp:GridView>
</td>
</tr>
</ItemTemplate>
Update: David Findley posted something that I hadn't thought of using that's even easier. Adding this to web.config will dump email messages sent from an ASP.NET application to the specified path: <system.net>
<mailSettings>
<!--
Production setting
<smtp deliveryMethod="Network">
<network host="localhost" port="25" />
</smtp>
-->
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\TestMessages" />
</smtp>
</mailSettings>
</system.net>
Top 10 Best Practices for Production ASP.NET Applications12 Feb, 2008. In no particular order, here are the top ten things I've learned to pay attention to when dealing with production ASP.NET applications. Hopefully they will help you save you some time and headaches. As always, your thoughts and additions are welcome. 1. Generate new encryption keys When moving an application to production for the first time it is a good idea to generate new encryption keys. This includes the machine validation key and decryption key as well as any other custom keys your application may be using. There is an article on CodeProject that talks about generating machineKeys specifically that should be helpful with this. 2. Encrypt sensitive sections of your web.config This includes both the connection string and machine key sections. See Scott Guthrie's post for some good references. Note that if your application runs in a clustered environment you will need to share a custom key using the RSA provider as described in an MSDN article. 3. Use trusted SQL connections Both Barry Dorrans and Alex Chang have articles which discuss this in detail. 4. Set retail="true" in your machine.config <configuration> <system.web> <deployment retail="true"/> </system.web> </configuration> This will kill three birds with one stone. It will force the 'debug' flag in the web.config to be false, it will disable page output tracing, and it will force the custom error page to be shown to remote users rather than the actual exception or error message. For more information you can read Scott Guthrie's post or the MSDN reference. 5. Create a new application pool for your site When setting up your new site for the first time do not share an existing application pool. Create a new application pool which will be used by only by the new web application. 6. Set the memory limit for your application pool When creating the application pool, specifically set the memory limit rather than the time limit which is set by default. Asp.net has a good whitepaper which explains the value of this: By default IIS 6.0 does not set a limit on the amount of memory that IIS is allowed to use. ASP.NET’s Cache feature relies on a limitation of memory so the Cache can proactively remove unused items from memory. It is recommended that you configure the memory recycling feature of IIS 6.0. 7. Create and appropriately use an app_Offline.htm file There are many benefits to using this file. It provides an easy way to take your application offline in a somewhat user friendly way (you can at least have a pretty explanation) while fixing critical issues or pushing a major update. It also forces an application restart in case you forget to do this for a deployment. Once again, ScottGu is the best source for more information on this. 8. Develop a repeatable deployment process and automate it It is way too easy to make mistakes when deploying any type of software. This is especially the case with software that uses configuration files that may be different between the development, staging, or production environments. I would argue that the process you come up with is not nearly as important as it being easily repeatable and automated. You can fine tune the process as needed, but you don't want a simple typo to bring a site down. 9. Build and reference release versions of all assemblies In addition to making sure ASP.NET is not configured in debug mode, also make sure that your assemblies are not debug assemblies. There are of course exceptions if you are trying to solve a unique issue in your production environment ... but in most cases you should always deploy with release builds for all assemblies. 10. Load test This goes without saying. Inevitably, good load testing will uncover threading and memory issues not otherwise considered.
http://blog.emanuelebartolesi.com/post/2007/12/Log4net-Simple-way-to-use-in-your-Aspnet-application.aspx Introduction Log the actions of your applications is very important especially when you develop new features or develop very difficult logical business. But it is also important when users use your applications to understand the critical issues or problems. To implement quickly the log operations Apache developed an opensource library for .Net developers. Download You can download the latest version of Log4net from this location. Add reference to your solution In Visual Studio 2005 select Project -> Add Reference. In the tab Browse, find and select the dll Log4net.dll in your local folder. Modify web.config Into web.config file add this code into the section Configuration->Configsections: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> Yet, add the section: <log4net> <appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> <file value="c:\temp\web.log" /> <appendToFile value="true" /> <maximumFileSize value="1024KB" /> <maxSizeRollBackups value="10" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %level %logger - %message%newline" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="RollingFile" /> </root> </log4net> In this configuration will create a log file into the folder "c:\temp\" until its size is 1024Kb. After this size the name of file will be web.log.1 until 10. At this link you can find another configurations. Global.asax In the event "Application_Start" of the file Global.asax add this line: log4net.Config.XmlConfigurator.Configure(); Begin to log In every page you want to log something, add the static variable like below: private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); This class has 5 levels of severity to log the operations: log.Debug("log something at this level") log.Info("log something at this level") log.Warn("log something at this level"); log.Error("log something at this level"); log.Fatal("log something at this level"); Simple and fast to use. You find the official documentation at this link.
http://msdn2.microsoft.com/en-us/library/dct97kc3.aspx Both master pages and content pages can contain event handlers for controls. For controls, events are handled locally—a control in a content page raises an event in the content page, and a control in the master page raises an event in the master page. Controls events are not sent from the content page to the master page. Similarly, you cannot handle an event from a master page control in a content page. In some cases, the same event is raised in both the content and the master page. For example, both pages raise Init and Load events. The general rule for how events are raised is that the initialization events are raised from the innermost control to the outermost one, and all other events are raised from the outermost control to the innermost one. It is helpful to remember that the master page is merged into the content page and treated as a control in the content page. The following is the sequence in which events occur when a master page is merged with a content page: -
Master page controls Init event. -
Content controls Init event. -
Master page Init event. -
Content page Init event. -
Content page Load event. -
Master page Load event. -
Content controls Load event. -
Content page PreRender event. -
Master page PreRender event. -
Master page controls PreRender event. -
Content controls PreRender event. The sequence of events in master and content pages rarely is important for you as page developer. However, if you are creating event handlers that depend on the availability of certain controls, you will find it helpful to understand the event sequence in master and content pages.
http://forums.asp.net/t/1127834.aspx you can use the following javascript function to set the active tab: function SetActiveTab(tabControl, tabNumber) { var ctrl = $find(tabControl); ctrl.set_activeTab(ctrl.get_tabs()[tabNumber]); } tabControl: ID from the TabContainer Controls tabNumber: Number of the new Tab (starting at 0) Or $find('<%=TabContainer1.ClientID%>').get_activeTabIndex(); and $find('<%=TabContainer1.ClientID%>').set_activeTabIndex(2);
http://blenitz.blogspot.com/2007/09/hidden-columns-with-values-aspgridview.html (If you don't want to show empty headtitle, put the hidden filed in with other field in one grid colomn) If you set Column Visible property to false, this column won't rendered. But if you want these values available, What will you do? My trick was, set HeaderText to empty, convert the BoundField in TemplateField, and use a HiddenField control. The effect the column won't be visible. Also you can use the controls array to access to value property. <Columns><asp:BoundField DataField="CompanyCode" HeaderText="Company" SortExpression="CompanyCode" /> ... <Columns> <asp:TemplateField><ItemTemplate><asp:HiddenField id="hf1" Value='<%# Bind("CompanyCode") %>' runat="server"></asp:HiddenField></ItemTemplate> ... // accesing the value property int tmpID = Convert.ToInt32(((HiddenField)GridView1.SelectedRow.Cells[3].Controls[1]).Value);
From: http://www.mikeduncan.com/3-hot-uses-for-httpcontextcurrentitems-they-wont-tell-you-about/ Generally, HttpContext.Current.Items doesn’t get all that much hot blog press, but let me tell you, I’m here to change all that. For those out of the know, System.Web.HttpContext.Current.Items is a sweet key-value pair collection you can use to pass objects around up and through all components that participate in a single HTTP request. What does this mean? This means that in a way similar to sticking something in the Session or cache, you can jam some values into the HttpContext.Current.Items for your request, say in a HttpModule way down low before you’ve even begun to fetch a page, and have those values readable/writable later from your page and all its usercontrols. The Items only persist through this one-night-stand of a single request and then supposedly “lose your number” but that’s ok, because we don’t really need all their drama after that anyway. 1) Preparing objects down low, on the down-low. As alluded to earlier, one sweet use of HCI (as we call in on the street) is in HttpModules. Let’s say you are doing some url-rewriting for user-friendliness or SEO reasons. While you’re at it, why not do a little preparation for your page? If you have a query param of state abbreviation that comes in commonly, populate an additional full state name display field ahead of time. Clean up your strings with proper casing, do whatever utils you think you can get away with while you have the request in your hand. I have a little object of getters and setters that I populate in the the HttpModule, and stick it in the Current.Items for its way up the stack. Now my pages and usercontrols can pull out my cleaned up custom object from the Context.Items and act accordingly, pass it down the line to methods, whatever. The vibe is maybe a hint at a smidgen of a wee bit Model View Controller-ish, but not really. 2) Making params and pages more unit-testable. With something like #1 in place, you can pull objects of params and prepared goodness out of the request and process them in your code behind, presenter, usercontrol, whatever strikes your pattern fancy. If this bundle of params is a in a nice little object that implements an interface, this makes unit testing logic that under normal circumstances relies upon getting info from the System.Web namespace (querystring params mostly) nice and easily decoupled. Pros of this are that your view calling your presenter can stay super lean and mean without having to populate a bunch info from query strings which will end up going through standard transformations you could have handled earlier on. A con is that the population of these params might be a bit mysterious to other devs who don’t see the HttpModule in action, sort of a like a table that gets populated from somewhere or other, but you don’t know what trigger where. I hate that. 3) Populating usercontrols without the hassle. If you know you have values in your hand at page on_load or earlier, it’s pretty damn convenient to stick them in the HttpContext.Current.Items and then just read them out from whatever usercontrols may or may not be dynamically included on the page. No finding child controls from the page, no finding parent info from the controls. No casting, scoping or otherwise thinking about precisely what order what will fire. If you have the data at page_load, your controls can get it. Don’t call me, and I won’t call you either. Ta-dow (does anyone say that anymore?). So there you have it, HttpContext.Current.Items, arcane enough to give you guru-cred to the mid-range noobs, simple enough that it can be leveraged for good and / or evil. Awesome.
<asp:GridView ID="GridViewYardSales" runat="server" CssClass="yui-datatable-theme" AutoGenerateColumns="false" DataSourceID="YardSaleDataSource" AllowSorting="true" OnRowCommand="GridViewYardSales_RowCommand" OnRowCreated="GridViewYardSales_RowCreated" DataKeyNames="ItemId"> <RowStyle CssClass="data-row" /> <AlternatingRowStyle CssClass="alt-data-row" /> <Columns> <asp:BoundField DataField="ItemId" HeaderText="ItemId" ReadOnly="True" SortExpression="ItemId" Visible="false"></asp:BoundField> <asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="20px"> <ItemTemplate> <asp:LinkButton ID="LinkButtonViewOnMap" runat="server" OnClientClick=<%# String.Format("javascript:ViewOnMapById('{0}');", Eval("ItemId")) %>> Map</asp:LinkButton><br /> <asp:LinkButton ID="LinkButtonItinerary" runat="server" CommandName="Command_Itinerary" CommandArgument='<%# Eval("ItemId") %>'>Itinerary </asp:LinkButton><br /> <asp:LinkButton ID="LinkButtonViewDetail" runat="server" CommandName="Command_ViewItemDetail" CommandArgument='<%# Eval("ItemId") %>'>Detail </asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Title"> <ItemTemplate> <%# Eval("Title") %><br /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Date"> <ItemTemplate> <%# Eval("Time") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> protected void GridViewYardSales_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { //Retrieve LinkButton control int m_RowIndex = e.Row.RowIndex; string id = GridViewYardSales.DataKeys[m_RowIndex].Value.ToString(); LinkButton lb = (LinkButton)e.Row.FindControl("LinkButtonItinerary"); if (IsItemAlreadyInItinerary(id)) { lb.Text = "Remove"; } else { lb.Text = "Add"; } } } protected void GridViewYardSales_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Command_Itinerary") { string id = e.CommandArgument.ToString(); GridViewRow selectedRow = (GridViewRow)(((Control)e.CommandSource).NamingContainer); LinkButton lb = (LinkButton)selectedRow.FindControl("LinkButtonItinerary"); if (!IsItemAlreadyInItinerary(id)) { AddItemToItinerary(id); lb.Text = "Remove"; } else { RemoveItemFromItinerary(id); lb.Text = "Add"; } } else if (e.CommandName == "Command_ViewItemDetail") { string id = e.CommandArgument.ToString(); Response.Redirect("ViewSale.aspx?id=" + id); } }
<asp:GridView ID="GridViewYardSales" runat="server" CssClass="yui-datatable-theme" AutoGenerateColumns="false" DataSourceID="YardSaleDataSource" AllowSorting="true" OnRowCommand="GridViewYardSales_RowCommand" OnRowCreated="GridViewYardSales_RowCreated" DataKeyNames="ItemId"> <RowStyle CssClass="data-row" /> <AlternatingRowStyle CssClass="alt-data-row" /> <Columns> <asp:BoundField DataField="ItemId" HeaderText="ItemId" ReadOnly="True" SortExpression="ItemId" Visible="false"></asp:BoundField> <asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="20px"> <ItemTemplate> <asp:LinkButton ID="LinkButtonViewOnMap" runat="server" OnClientClick=<%# String.Format("javascript:ViewOnMapById('{0}');", Eval("ItemId")) %>> Map</asp:LinkButton><br /> <asp:LinkButton ID="LinkButtonItinerary" runat="server" CommandName="Command_Itinerary" CommandArgument='<%# Eval("ItemId") %>'>Itinerary </asp:LinkButton><br /> <asp:LinkButton ID="LinkButtonViewDetail" runat="server" CommandName="Command_ViewItemDetail" CommandArgument='<%# Eval("ItemId") %>'>Detail </asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Title"> <ItemTemplate> <%# Eval("Title") %><br /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Date"> <ItemTemplate> <%# Eval("Time") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="20px"> <ItemTemplate> <%# Convert.ToInt32(DataBinder.Eval(Container, "DataItemIndex")) + 1 %>. </ItemTemplate> </asp:TemplateField>
http://support.microsoft.com/kb/312629/EN-US/ SYMPTOMS If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception. Back to the top
CAUSE The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed. This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally. Back to the top
RESOLUTION To work around this problem, use one of the following methods: For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example: Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Execute method instead.
http://aspalliance.com/774 Title: Repopulating checkboxes in GridView solution Name: Anonymous Date: 8/13/2006 8:30:45 PM Comment: This is a great solution! However, when I first tested I get the same problem as everyone where the checkboxes get reset after every page changed. In order to solve this problem, you need to add DataBound event to repopulate the checkboxes states. Below is the solution: protected void GridView1_DataBound(Object sender, EventArgs e) { RePopulateValues(); } protected void GridView1_PageIndexChanging(Object sender, GridViewPageEventArgs e) { RememberOldValues(); } Note: This is done in .Net 2.0 and the reason the author code doesn't work is because the databound event is called after pageindexchanging and pageindexchanged and therefore it clears the checkboxes states.
The Page class includes a property called the IsPostBack property, which you can use to detect whether the page has already been posted back to the server. Because of View State, when you initialize a control property, you do not want to initialize the property every time a page loads. Because View State saves the state of control properties across page posts, you typically initialize a control property only once, when the page first loads. In fact, many controls don't work correctly if you re-initialize the properties of the control with each page load. In these cases, you must use the IsPostBack property to detect whether or not the page has been posted. if(!Page.isPostBack)
{
//not postback means first time initiation.
}
Here is the sequence of events that are raised whenever you request a page: - PreInit
- Init
- InitComplete
- PreLoad
- Load
- LoadComplete
- PreRender
- PreRenderComplete
- SaveStateComplete
- Unload
Ninety-nine percent of the time, you won't handle any of these events except for the Load and the PreRender events. The difference between these two events is that the Load event happens before any control events and the PreRender event happens after any control events.
http://msdn2.microsoft.com/en-us/library/ms178116.aspx ApplicationPath Gets the root path of the current application, regardless of where in the application you request it. For the example, the property returns the following: / CurrentExecutionFilePath Gets the virtual path of the current request. Differs from the FilePath property in that CurrentExecutionFilePath is correct if the request has been redirected in server code. For the example, the property returns the following: /MyApplication/MyPages/Default.aspx If you get the property in code that is running as a result of a call to Transfer or Execute, the path reflects the location of the code. FilePath Gets the virtual path of the current request. For the example, the property returns the following: /MyApplication/MyPages/Default.aspx Unlike the CurrentExecutionFilePath property, FilePath does not reflect server-side transfers. Path Gets the virtual path of the current request. For the example, the property returns the following: /MyApplication/MyPages/default.aspx PhysicalApplicationPath Gets the physical file system path of the currently executing application's root directory. For the example, the property returns the following: C:\inetpub\wwwroot\ PhysicalPath Gets the physical file-system path that corresponds to the requested URL. For the example, the property returns the following: C:\inetpub\wwwroot\MyApplication\MyPages\default.aspx
|
Copyright © 2010 Kevin Mocha. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme:
|
|