Blog Home  Home Feed your aggregator (RSS 2.0)  
kevin Mocha - DotNet | ASP
Bookmarks collected from web.
 
 Friday, August 01, 2008

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.

Friday, August 01, 2008 2:27:51 PM UTC  #    Comments [0]    |  Trackback
 Thursday, April 17, 2008
Thursday, April 17, 2008 4:16:48 AM UTC  #    Comments [0]    |   |  Trackback
 Friday, April 04, 2008

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.

Friday, April 04, 2008 8:26:40 PM UTC  #    Comments [0]    |  |   |  Trackback
 Friday, February 22, 2008
<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>&nbsp;</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>
Friday, February 22, 2008 9:24:45 PM UTC  #    Comments [0]    |   |  Trackback

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>
Friday, February 22, 2008 9:02:18 PM UTC  #    Comments [0]    |   |  Trackback
 Tuesday, February 19, 2008

http://daptivate.com/archive/2008/02/12/top-10-best-practices-for-production-asp-net-applications.aspx

Top 10 Best Practices for Production ASP.NET Applications

12 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.

Tuesday, February 19, 2008 2:24:48 PM UTC  #    Comments [0]    |   |  Trackback
 Friday, January 11, 2008
 Monday, January 07, 2008

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.

Monday, January 07, 2008 10:28:47 PM UTC  #    Comments [0]    |   |  Trackback
 Thursday, December 20, 2007

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:

  1. Master page controls Init event.

  2. Content controls Init event.

  3. Master page Init event.

  4. Content page Init event.

  5. Content page Load event.

  6. Master page Load event.

  7. Content controls Load event.

  8. Content page PreRender event.

  9. Master page PreRender event.

  10. Master page controls PreRender event.

  11. 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.

Thursday, December 20, 2007 3:42:19 AM UTC  #    Comments [0]    |   |  Trackback
 Wednesday, November 28, 2007

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);

Wednesday, November 28, 2007 3:54:46 AM UTC  #    Comments [0]    |  |  |   |  Trackback
 Monday, November 12, 2007

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);
Monday, November 12, 2007 9:07:00 PM UTC  #    Comments [0]    |   |  Trackback
 Sunday, November 11, 2007

http://www.netomatix.com/development/GridViewRowSelectedEvent.aspx

How to raise gridview server side event when when row is selected

 

http://www.netomatix.com/development/GridViewRowSelectedStyle.aspx

How to highlight gridview when row is selected

 

http://www.netomatix.com/development/GridViewClientSideAccess.aspx

How to access gridview cell values on client side
Sunday, November 11, 2007 4:02:32 PM UTC  #    Comments [0]    |   |  Trackback
 Thursday, November 08, 2007

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.

Thursday, November 08, 2007 7:19:38 PM UTC  #    Comments [0]    |  Trackback
 Tuesday, November 06, 2007

<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);
            }
        }

Tuesday, November 06, 2007 9:42:39 PM UTC  #    Comments [0]    |   |  Trackback

<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>

Tuesday, November 06, 2007 9:37:14 PM UTC  #    Comments [0]    |   |  Trackback
Tuesday, November 06, 2007 4:38:17 AM UTC