webcam porn

Configuration Handling Reloaded

Tuesday, February 15th, 2011 | .NET | 1 Comment

Configuration handling of web projects is a well discussed topic. There are lots of examples on how to configure web.config for different environments; using configSections, naming conventions, T4 transformations, web deployment projects etc.

Until now, this have been quite painful. Visual Studio 2010, however, has a new feature which opens up a lot of new possibilities; Config Transformations. This is a very cool feature and triggers when you publish your web application within Visual Studio.

Here is an example on how to handle advanced configurations and make them available locally too for testing and debugging purposes.

The challenge:

  • I want different config files for different environments.
  • I want to test different configurations locally and be able to debug them on my machine with a simple change. This means I must be able to compile my web.config file dynamically when building
  • I want my own settings which does not affect the configurations for my teammates.

XmlTransformation task to the rescue!

With the new XmlTransformation task for MSBuild, it is possible to manually trigger config transformations. This is great news because then we can control which files will be transformed and when they will be transformed. I can make more complex configurations and also have my own transformations which are personal and not checked into the version control system.

First, I would like to be able to test the different configurations. Lets say I have a web application which will behave different in different environments. This could be controlled in a database or it could be controlled in a config file.

As an example, I have created a simple solution with 2 themes, one red and one blue theme. Changing the configuration, should also change the theme on the web site. In order to achieve this I have created 2 themes in my solutions with a stylesheet for each theme that will set the background color of the header for the default ASP.NET site that comes with Visual Studio:


2 themes, one red and one blue


In order to be able to change this, I create some configurations in the Configuration manager in Visual Studio:

With the configurations, I am able to create additional transformation files for web.config:


Transformations files


Also notice that I have a Web.master.config file and a Web.mysettings.config file. The master file is the base file that will be used for all transformations. This should contain the settings which is most common for the different configurations. The mysettings file is my personal config file which I use for my personal configurations. For instance, I like to use Fiddler and this contains transformations for adding Fiddler proxy to the web.config file.

The content of the Web.mysettings.config file:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.net>
        <defaultProxy xdt:Transform='Insert'>
            <proxy proxyaddress="http://127.0.0.1:8888"/>
        </defaultProxy>
    </system.net>
</configuration>

Selecting the debug – blue configuration should result in the standard blue color for the default ASP.NET site when running/debugging the web application:

Selecting the debug – red configuration should result in having a red header in the web site:

In real life, a lot of different appsettings could be different for the different configurations.  In this example, the Web.debug – red.config file only contains

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.web>
        <pages xdt:Transform="SetAttributes" theme="Red" />
    </system.web>
</configuration>

which will change the theme of the pages element.

Now, here comes the real magic. This is the code you have put into the project file of the web application to be able to modify the Web.config file. Edit the project file and paste this before the </Project> closing element

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <!-- This is a hack to perform the master => transform without mysettings of web.config when publishing the website. It will only trigger on -->
  <!-- publish within Visual Studio. It actually overrides the TransformWebConfig Target in the original Microsoft.Web.publishing.targets file, -->
  <!-- but since it is empty by default, it should work fine! -->
  <Target Name="TransformWebConfig">
    <Message Text="%09 ------------- Transforming web.config.master =&gt; web.config with $(Configuration) transformations --------------" />
    <TransformXml Source="web.master.config" Transform="web.$(Configuration).config" Destination="web.config" />
  </Target>
  <Target Name="BeforeBuild">
    <Message Text="%09 ------------- Transforming web.config with $(Configuration) transformations --------------" />
    <TransformXml Condition="Exists('web.mysettings.config')" Source="web.master.config" Transform="web.$(Configuration).config" Destination="web.transformed.config" />
    <TransformXml Condition="Exists('web.mysettings.config')" Source="web.transformed.config" Transform="web.mysettings.config" Destination="web.config" />
    <TransformXml Condition="!Exists('web.mysettings.config')" Source="web.master.config" Transform="web.$(Configuration).config" Destination="web.config" />
  </Target>
  <Target Name="AfterBuild">
    <!--<Delete Condition="Exists('web.mysettings.config')" FiThe BeforeBuoilles="web.transformed.config" />-->
  </Target>

Some comments on the code:

  • The TransformXml task comes with Visual Studio 2010, so all you have to do is make a reference to it with the using statement.
  • In the BeforeBuild Target,  this is where the transformations take place. This makes it possible to dynamically create Web.config every time a build triggers.
  • Using Source and Destination, it is possible to do transformations to all kind of XML file types, not only Web.config.- You could have appSettings.config, connectionsTrings.config etc. It would also be possible to make more hierarchical transformations by doing more than one transformation. Lets say there are some common settings for the red configuration which should be transformed in all environments, it would be possible to have this in a separate config file that will be transformed into the final web.config file.
  • The AfterBuild target should clean up the temporary config files. However, there seems to be a bug with the TransformXml task locking the files, so lets hope Microsoft fixes this in a future version.
  • The Web.mysettings.config transformation only triggers if there is a mysettings file available. This means not all teammembers have to create this file if they don't need to.
  • The target TransformWebConfig is a minor hack. In order to prevent the mysettings transformation when doing a Publish… within Visual Studio, I had to find a target in the Publish… event which triggers only when publishing. This target actually does nothing in the default Microsoft.Web.Publishing.targets file, so that's the reason for overriding this particular target. I wish it would be possible to actually hook into the publish event in Visual Studio through MSBuild, but that seems impossible. And using a target in MSBuild also overrides the target without having the option to call the base target which is overridden, so anything you do in that target will not be continued in the Microsoft.Web.Publishing.targets file. Lets hope MS don't put anything into that target in the future. I also tried to use DependsOnTargets, but that seems to trigger the target depending on, not listening to wheter the target has been run. That's a big difference.

Conclusion

Using the TransformXml task is a pretty simple solution to a complex problem. It comes with Visual Studio 2010 and makes environmental and application specific configurations much simpler to handle in real life. For Visual Studio 2008 and earlier, you still need to think different. Have a look at Andreas post on how to make complex transformations using T4 templates.

You can download the sample solution here: ConfigExample.zip.

True dynamic controls

Thursday, February 3rd, 2011 | .NET | No Comments

This is something I have been struggeling with so many times, and there are a lot of examples on how to programatically add controls to a page. In this example I add dynamically created controls which remembers their state on postbacks.

The problem:

  • I want to add new controls to a page. Clicking a button adds a new control to the page.
  • The new control should remember its state through ViewState and postback events should work as normal.

The solution:

  • I can add the controls to a Panel or Placeholder and I have to do it in an early stage in the page lifecycle.
  • Some experiments and thoughts
    • The dynamically added controls needs to be added to the page on every postback. It is not possible to add a new control and forget it. This means I need to have a loop where the controls are added to the page.
    • The ID of the control need to be the same on every postback in order for the control to remember its state through ViewState.
    • Doing some testing, I tried adding the controls in PreInit. This is where Microsoft recommends to add dynamically created controls. The only problem here is that the ViewState is not available at this stage. So I am not able to track how many controls that have been added to the page. I have a property NumberOfDynamicControls which holds how many dynamically controls that have been added. The same goes with Init, no luck. The ViewState is loaded between Init and Load.
    • You can add controls to the page in almost any event (PreInit, Init, Load, postback event etc.) and it will render fine. However, the ViewState will not be tracked and it is not possible to add and render more than one control.
    • The only solution I found was to override the LoadViewState event and add the controls there. This seems like a hack, and probably is, but everything seems to work fine regarding ViewState tracking and postback events.
    • I need to have the dynamic control available as an invisible "ghost" control before it is "added" to the page. This is to keep track of the state of the control. When clicking the "Add" button, the ghost control is set visible, although it's already there.

Here is the code:

This is the HTML markup. I'm having a simple Panel and a button. Everytime I click the Add button, a new dynamically created button is added to the page.

<asp:Panel runat="server" ID="Panel1" >
 <asp:Button Text="Add" runat="server" OnClick="AddControlToPanel" />
 </asp:Panel>   

   

I have to initialize a "ghost" control. The dynamically created button is actually added to the page before it is visible. This is to track ViewState. Clicking the Add button makes the ghost control visible:

 protected void AddControlToPanel(object sender, EventArgs e)
        {
            Button newButton = Panel1.FindControl("ButtonDynamic" + (NumberOfDynamicControls - 1)) as Button;
            if (newButton != null)
            {
                newButton.Visible = true;
                newButton.Text = "New button";
                NumberOfDynamicControls++;
            }
        }

Here is the tracking of number of dynamically created controls added to the page. The value is stored in the ViewState.

 protected int NumberOfDynamicControls
        {
            get { return ViewState["numberOfDynamicControls"] == null ? 1 : (int)ViewState["numberOfDynamicControls"]; }
            set { ViewState["numberOfDynamicControls"] = value; }
        }

Here comes the real magic. By overriding the LoadViewState and rebuilding the dynamically added controls, everything works as expected.

 protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            if (IsPostBack)
            {
                InitializeDynamicButtons(NumberOfDynamicControls);
            }
        }

protected void InitializeDynamicButtons(int numberOfButtons)
        {
            for (int i = 0; i < numberOfButtons; i++)
            {
                Button dynamicButton = new Button();
                Panel1.Controls.Add(dynamicButton);
                dynamicButton.ID = "ButtonDynamic" + i;
                dynamicButton.Click += DynamicButton_Click;
                dynamicButton.Visible = false;
            }
        }

The dynamically created button also has a click event:

 void DynamicButton_Click(object sender, EventArgs e)
        {
            Button button = (Button) sender;
            button.Text = "Clicked!";
        }

Before:



The page before adding the dynamic buttons



 

After:


The added buttons. Notice I have clicked the middle button and the state is managed.



Here is the complete code:

DynamicControls

If you know some other good ways to achieve this, let me know!

Creating dynamic menus in EPiServer

Wednesday, February 10th, 2010 | .NET | 1 Comment

My first post in almost a year! What is going on! "Been busy, things are happening, blah blah blah"…no excuse, really. I signed up for twitter almost a year ago, and I think I lost some focus in the blogging sphere. Anyway, this first post in 2010 is about EPiServer, the best CMS out there today!

The challenge

I want to create a more dynamic page tree than the standard EPiServer PageTree. More like an Accordion panel which has 2 or 3 levels (doesn't matter) and all available nodes are expanded by default. The real challenge is to get the whole page tree with all nodes expanded (not only the nodes which are selected) and setting correct class on the expanded items. Whether this is an accordion or another cool menu script is all the same.

The Solution

Start out with the default PageTree control in EPiServer controls.

<EPiServer:PageTree ID="PageTreeLeftMenu" runat="server" ExpandAll="true" NumberOfLevels="2">

<HeaderTemplate>

<div class="leftmenu"> <!– Header –>

</HeaderTemplate>

<IndentTemplate>

<ul> <!– Indent –>

</IndentTemplate>

<ItemHeaderTemplate>

<li <%# GetExpandedClass(Container.DataItem) %>>

</ItemHeaderTemplate>

<ExpandedTopTemplate>

<EPiServer:Property PropertyName="PageLink" runat="server" /> <!– ExpandedTop –>

</ExpandedTopTemplate>

<SelectedExpandedTopTemplate>

<EPiServer:Property PropertyName="PageLink" runat="server" CssClass="selected" /> <!– SelectedExpandedTop –>

</SelectedExpandedTopTemplate>

<ExpandedItemTemplate>

<EPiServer:Property PropertyName="PageLink" runat="server" /> <!– ExpandedItem –>

</ExpandedItemTemplate>

<SelectedExpandedItemTemplate>

<EPiServer:Property PropertyName="PageLink" runat="server" CssClass="selected" /> <!– SelectedExpandedItem –>

</SelectedExpandedItemTemplate>

<ItemFooterTemplate>

</li>

</ItemFooterTemplate>

<UnindentTemplate>

</ul> <!– UnIndent –>

</UnindentTemplate>

<FooterTemplate>

</div> <!– Footer –>

</FooterTemplate>

</EPiServer:PageTree>


Things to notice:

  • "ExpandAll" is set to true. This will dump the whole tree, not just the nodes which are selected by the user.
  • Only the *Expanded* templates are in use for Top and Item (ie.ExpandedTopTemplate).  When using "ExpandAll" these are the templates used, not the regular Top Template and ItemTemplate.
  • <%# GetExpandedClass(Container.DataItem) %> – This is the magic for setting the correct style on the expanded items. In addition there is a "selected" class on the selected menu item

The Codebehind looks like this:

protected void Page_Load(object sender, EventArgs e)

{

PageTreeLeftMenu.PageLink = LeftMenuPageLink;

PageTreeLeftMenu.DataBind();

}

 

protected PageReference LeftMenuPageLink

{

get

{

PageReference leftMenuPageLink = CurrentPage["LeftMenuRoot"] as PageReference;

return leftMenuPageLink;

}

}

 

protected string GetExpandedClass(object dataItem)

{

PageData page = dataItem as PageData;

if (page != null && PageTreeLeftMenu.OpenPages.Contains(page.PageLink))

return "class=\"expanded\"";

return string.Empty;

 

}

Things to notice:

  • LeftmenuPageLink is just an example on how to set the start point for the left menu.
  • GetExpandedClass is the method that sets the correct class on the <li>. This is done by checking if the page in the tree is available in PageTree.OpenPages. This is what makes it possible to make the dynamic menu. If the OpenPages method was not available, it would not be possible to highlight the expanded nodes without traversing each node or doing some javascripting.

The output should look something like this

43 <div class="leftcolumn">

44 <div class="leftmenu">

45 <!– Header –>

46 <ul>

47 <!– Indent –>

48 <li class="expanded"><a href="/en/Consulting/">Consulting</a>

49 <!– ExpandedTop –>

50 <ul>

51 <!– Indent –>

52 <li class="expanded"><a class="selected" href="/en/Consulting/Business-Consulting-/">

53 Business Consulting </a>

54 <!– SelectedExpandedItem –>

55 </li>

56 <li><a href="/en/Consulting/Project-and-Test-Management/">Project and Test

57 Management</a>

58 <!– ExpandedItem –>

59 </li>

60 <li><a href="/en/Consulting/IT-Consulting/">IT Consulting</a>

61 <!– ExpandedItem –>

62 </li>

63 <li><a href="/en/Consulting/Application-Development/">Application Development</a>

64 <!– ExpandedItem –>

65 </li>

66 </ul>

67 <!– UnIndent –>

68 </li>

69 <li><a href="/en/Solutions/">Solutions</a>

70 <!– ExpandedTop –>

71 <ul>

72 <!– Indent –>

73 <li><a href="/en/Solutions/ERP/">ERP</a>

74 <!– ExpandedItem –>

75 </li>

76 <li><a href="/en/Solutions/Content-Management/">Content Management</a>

77 <!– ExpandedItem –>

78 </li>

79 <li><a href="/en/Solutions/Oil-and-Gas/">Oil and Gas</a>

80 <!– ExpandedItem –>

81 </li>

82 <li><a href="/en/Solutions/Industry/">Industry</a>

83 <!– ExpandedItem –>

84 </li>

85 <li><a href="/en/Solutions/E-Business/">E-Business</a>

86 <!– ExpandedItem –>

87 </li>

88 <li><a href="/en/Solutions/Banking–Finance-Suite/">Banking &amp; Finance

89 Suite</a>

90 <!– ExpandedItem –>

91 </li>

92 <li><a href="/en/Solutions/Public-Sector-Suite/">Public Sector Suite</a>

93 <!– ExpandedItem –>

94 </li>

95 </ul>

96 <!– UnIndent –>

97 </li>

98 <li><a href="/en/Outsourcing/">Outsourcing</a>

99 <!– ExpandedTop –>

100 <ul>

101 <!– Indent –>

102 <li><a href="/en/Outsourcing/ITO/">ITO</a>

103 <!– ExpandedItem –>

104 </li>

105 <li><a href="/en/Outsourcing/Applications-Management/">Applications Management</a>

106 <!– ExpandedItem –>

107 </li>

108 </ul>

109 <!– UnIndent –>

110 </li>

111 <li><a href="/en/TestTest/">TestTest</a>

112 <!– ExpandedTop –>

113 </li>

114 <li><a href="/en/TestTestTest/">TestTestTest</a>

115 <!– ExpandedTop –>

116 </li>

117 </ul>

118 <!– UnIndent –>

119 </div>

120 <!– Footer –>

121 </div>

The result will look something like this:

After adding the Accordion script, the Top items should collapse and only the expanded section should be visible. When moving the mouse over another section it should expand, but not highlight. The final result will look something like this.

Conclusion

Using dynamic menus could give the visitor a better experience. Whether its an Accordion panel or some other fancy scripted menu doesn't matter. Anyway you will have to dump the whole tree to a certain level (2 levels in this example) and set the correct classes on the elements to get the styling correct. The magic is the "PageTree.OpenPages" method which helps a lot in this scenario.

ie7 bug – Popup blocker prevents clicking dropdown lists.

Tuesday, February 24th, 2009 | General | 11 Comments

ie7I had a strange experience with IE 7. It was suddenly impossible to click dropdown lists. The popup blocker displayed the toolbar, saying it blocked a popup. The dropdown was from my own code running on localhost, so it was definitely not a popup defined in the event. I am really not sure when this happened. Yesterday I installed the Internet Explorer Collection, which is great for testing GUI in different versions of Internet Explorer. This could cause the strange behaviour, but I'm really not sure. The collection includes IE 8 Beta, and I have seen others with IE 8 Beta having this problem.

I soon found out other users having this problem and most referred to this page for a solution. I tried the suggestion on adding localhost to the "trusted sites" and setting security level to medium-low, but that didn't solve my problem. I then uninstalled the Internet Explorer Collection without any luck. I also tried resetting Internet Explorer; Tools->Internet options->Advanced->Reset… (button). But again, no luck. Also restarted windows just to be sure.

Only left solution was to remove or reinstall IE7. Removing will downgrade to IE 6, which is really not what I want. So I downloaded the IE 7 installer from Microsoft and installed IE7 again (no option in installer to "reinstall"). Restarting windows, and everything was working fine again. Since that was not one of the options in the guide I found (link above), I though it was worth mention it here.

Ok, back to work…

Tags: ,

Use regular expressions in Visual Studio to clean up code

Friday, February 20th, 2009 | .NET | No Comments

This is a reminder to myself.

Knut, remember that Regular Expressions are very handy to clean up a lot of messy code.

Here is an example:
The following function call results in a code analysis warning:

DBHelper.SetPropertyFromDB(m_City, dr("CITY"))

It's a helper function that returns the typed value from a DBValue. Not really useful these days with NHibernate or Typed Datasets, but it's code from an old application. Here is the signature of the code:

Shared Sub SetPropertyFromDB(ByRef pProperty As Object, ByVal value As Object)

The warning reported is:

"Warning: Implicit conversion from 'Object' to 'String' in copying the value of 'ByRef' parameter 'pProperty' back to the matching argument."

To fix this, I created a new method that returns the correct typed value instead of returning the referenced parameter and marked the old method "Obsolete":

Public Shared Function GetDBValue(ByVal pProperty As Object, ByVal dbValue As Object) As Object

Now, I had to rewrite all the calls to the function (several hundred calls). This included returning the typed value into the same variable as the first parameter in the function call, like this:

m_City = DBHelper.GetDBValue(m_City, dr("CITY"))

This is easily achieved by using Regular Expressions in the "Find and Replace" dialog in Visual Studio:

Find What:

DBHelper.SetPropertyFromDB\({.*},

(note: the \ escapes the ( and the expression group is marked by a {})

Replace with:

\1 = DBHelper.GetDBValue(\1,

(note: the \1 will represent the expression group)

Pretty simple, and very powerful :-)

Tags: ,

Extend the GridView

Thursday, February 19th, 2009 | .NET | 1 Comment

The default GridView class has by default a lot of great features. However, some important features are missing. One of the most important is the ability to display the grid even if it is empty.
Here is a great class extending the GridView with some additional features.

http://forums.asp.net/p/1012442/2951765.aspx#2951765

Tags: ,

XBOX – be quiet!

Tuesday, February 3rd, 2009 | General | 2 Comments

I have 3 Xbox 360's at home. Seems a bit too much, but they have really come down in price, and I use 2 of them as extenders for my Vista Media Center. The biggest problem with the Xbox is the noise it produce. The Media Center box is virtually silent using a mCubed hfx classic, so I want my extenders to be as quiet as possible. I could of course buy some Linksys DMA 2100 extenders, but they do not support VGA out, which is the only input option on my LCD monitor.

I'm using one of the Xboxes in the kitchen, connected to a 15" LCD monitor. The LCD is mounted above the fridge and serves as a kitchen TV. The Xbox is hidden behind a shelf placed above the refrigerator. This is almost in ear height when standing up and makes the noise come out pretty loud.

I read some reviews on the Lian Li PC XB01 case and decided to give it a try. Opening the Xbox will void the warranty, so I decided to modify the oldest one, as it no longer has a warranty.

The Lian Li case is pretty large as you can see in the video below.

This is mainly because of the large 120mm fan in the back. But it also gives some opportunities regarding further modding and better controlling the noise. You can even put a water cooling system in there. There are dedicated holes in the case for the water tubes.

It was quite tricky to dismount the Xbox, and you need a set of Torx tools (6, 8 and 10) to be able to do the work. Mounting the mainboard and DVD drive in the Lian case was straight forward.

The result

As this mod is only used as a Media Center Extender and not used for playing games at all, I didn't need the Xbox harddrive. The only noise coming from the case will be the fan. The standard fan which comes with the case is not very silent, but far better than the Xbox fans. I guess I will order a Papst fan to replace the standard fan.

Standard Xbox 360 Arcade (Falcon chipset)

Xbox 360 inside Lian Li PC XB01using oem fan (Zephyr chipset)

I also found a more extreme cooling solution for even more silent mods. Check out this site, which has an awesome mod: http://www.silentxbox.com/xbox_eng.php

Tags:

Web application absolute path

Wednesday, December 17th, 2008 | .NET | No Comments

Just a reminder on how to get the absolute path for the webapplication in ASP.NET

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +        VirtualPathUtility.ToAbsolute(HttpContext.Current.Request.ApplicationPath)

This will return http://subdomain.domain.com/applicationname

You can drop those AppSettings with ApplicationPath :)

Tags:

Using log4net in Web Applications – a real-life example

Friday, December 12th, 2008 | .NET | 14 Comments

I have seen many different configurations for Log4Net. Log4Net is a very simple, but flexible framework and there are lot of ways to configure it. Here is a real-life example on how we are using in the applications I am working on.

First off, I won't say that this is the one and only way you should use Log4Net, but it handles most of the scenarios I can think of.  Some people think that one should not write wrappers for the loggers and use the logging framework directly in the class, but to be honest I like the wrapper because it makes it very simple to use the logging framework without too much knowledge on how it works. I would say that 95% of what is being logged, is typically errors and debug/useful information. I can't see any problem using a wrapper as I get the information I need from the loggers.

Goals with this log configuration

  • Most important is of course logging errors. All errors should be logged.
  • Errors should be logged in a global file on the server that will role once a day.
  • Errors should be sent by email.
  • It should be possible to notify important information by email
  • It should be easy for the developers to use the logging framework
  • It should be possible to change log-level without restarting the application

Configuration and setup

Log4Net consists of only one DLL. Get the latest version and put it in your bin folder. Make a reference to it in the Web Application Project.

Log4net.config

Create a new config file in the root of your Web Application. Name it Log4Net.config and paste the following code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" 
        type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    <log4net>
        <appender name="RollingLogFileAppender"
            type="log4net.Appender.RollingFileAppender">
            <threshold value="INFO" />
            <file value="Log\[applicationname].log" />
            <appendToFile value="true" />
            <rollingStyle value="Date" />
            <datePattern value="'.'yyyyMMdd'.log'" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level
                  %logger %X{user} %X{url} - %message%newline" />
            </layout>
        </appender>
        <appender name="SmtpAppenderError" 
                  type="log4net.Appender.SmtpAppender">
            <!--Set threshold for this appender-->
            <threshold value="ERROR" />
            <to value="[someone]@[somewhere.com]" />
            <from value="[someone]@[somewhere.com]" />
            <subject value="Error from [applicationname]" />
            <smtpHost value="[100.100.100.100]" />
            <bufferSize value="1" />
            <lossy value="false" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date %-5level
                %logger %X{user} %X{url} - %message%newline" />
            </layout>
        </appender>
        <appender name="SmtpAppenderNotify"
                  type="log4net.Appender.SmtpAppender">
            <!--Set threshold for this appender-->
            <threshold value="INFO" />
            <to value="[someone]@[somewhere.com]" />
            <from value="[someone]@[somewhere.com]" />
            <subject value="Error from [applicationname]" />
            <smtpHost value="[100.100.100.100]" />
            <bufferSize value="1" />
            <lossy value="false" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date - %message%newline" />
            </layout>
        </appender>
        <root>
            <level value="Error" />        
        </root>
        <logger name="Application">
            <!--Set level for this logger-->
            <level value="INFO" />
            <appender-ref ref="RollingLogFileAppender" />
            <appender-ref ref="SmtpAppenderError" />
        </logger>
        <logger name="Notify">
            <!--Set level for this logger-->
            <level value="INFO" />
            <appender-ref ref="RollingLogFileAppender" />
            <appender-ref ref="SmtpAppenderNotify" />
        </logger>
    </log4net>
</configuration>

Some comments on the Log4net.config file:

  • The RollingFileAppender is great for rolling the logfile once a day.
    • It has a threshold of INFO, meaning it will log anything from the application except debug information
    • The logfiles are created in a subdirectory of web root. This should be changed on the production server to not expose information about the application.
    • The datePattern is specifying how the rolling files are named. The current day will be named "applicationname.log" and yesterdays file will be named "applicationname.log.20081211.log". The rolling file extension (.log)  makes it easy to open the file in the same editor as the current log. All files will be sorted correctly when using the ISO style date in the filename.
    • In the conversionPattern you will see two speacial entries with the following format: %X{name}. These are custom formats which can be used for special purposes. This configuration adds the authenticated username and the url which fails if there is an error. This is useful information.
  • The SmtpAppenders are used for sending emails. It's really not my favourite configuration, spamming the developers or some other people with emails when some errors occur, but some like it.
    • The threshold is different for the two SmtpAppenders, as is the subject of the email.
    • The buffersize is set to 1 in the example, meaning that the email is sent right away when an error occur. Increasing the buffer will hold the email until the buffer is reached. This can be useful on the production server, especially for the Notify appender as it is probably not that important to notify right away.
    • Lossy is set to false, also to send the email right away. It is possible to hold the email until an evaluator is triggered, for instance when a error occurs. Setting lossy to true requires an evaluator.
    • It is possible to add filters to the appenders to determine which emails should be sent and which to drop.
  • There are two specific loggers that the application will use. The root logger can be used to log 3.party libraries also using Log4Net. I like to use specific loggers in the application and enabling the root logger if I am tracing an error where I need more information from 3.party libraries, ie. NHibernate or other frameworks using Log4net. Remember to set the level for the logger. If not set, the default level is WARN, which means INFO messages will not be logged.

To be able to use the Log4Net.config file instead of putting everything into web.config, you will need to add the following line to AssemblyInfo.vb:

<Assembly: log4net.Config.XmlConfigurator(ConfigFile:="Log4Net.config", Watch:=True)>

The advantage of separating the Log4Net configuration is that it is possible to change the configuration of the logging without restarting the application by changing web.config.  It also gives an better overview of the configuration, not having to browse through web.config to find the logging configuration.

Logging unhandled errors

All unhandled errors should be logged, which is pretty easy to achieve in web applications. Here is the Global.asax file:

Imports System.Web
Imports log4net
Imports MainLib
Public Class [Global]
    Inherits System.Web.HttpApplication
    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application is started
        ' Initialize the logger in this context.
        LogManager.GetLogger(Me.GetType)
        LogHandler.LogInfo("============================", LogHandler.LogType.General)
        LogHandler.LogInfo("    Starting application", LogHandler.LogType.General)
        LogHandler.LogInfo("============================", LogHandler.LogType.General)
    End Sub
    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session is started
    End Sub
    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires at the beginning of each request
    End Sub
    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires upon attempting to authenticate the use
    End Sub
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when an error occurs
        LogHandler.LogError("Unhandled exception occured!",
        HttpContext.Current.User, HttpContext.Current.Request.Url,
        HttpContext.Current.Server.GetLastError())
    End Sub
    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the session ends
    End Sub
    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application ends
    End Sub
End Class

Comments on Global.asax

  • I have added some information logging in the Application_Start event. This will trigger every time the applications starts or recycles. If this occurs often you probably have some problems with resources on the server, ie. too little memory available for the application.
  • Application_Error occurs every time an unhandled error occurs. Use this to log all errors not logged elsewhere.
  • I have to initialize the logging framework in Application_Start by calling

    LogManager.GetLogger(Me.GetType).  I'm not sure whether this is a bug or by design. It is not possible to let the LogHandler do the initialization. LogHandler is a wrapper class located in another assembly, maybe that is a problem, without really knowing why. LogManager is a class in Log4Net.

The LogHandler class

Imports System.Security.Principal
Imports log4net

Public Class LogHandler
    Const _defaultApplicationLogger As String = "Application"

    Public Enum LogType
        General
        Notify
    End Enum

    Public Shared Sub LogError(ByVal message As String, ByVal [error] As Exception)

        Dim logger As ILog = LogManager.GetLogger(_defaultApplicationLogger)
        If Not [error].InnerException Is Nothing Then
            [error] = [error].InnerException
        End If

        If logger.IsErrorEnabled Then
            logger.Error(message, [error])
        End If
    End Sub

    Public Shared Sub LogError(ByVal message As String, _
                                ByVal user As IPrincipal, ByVal url As Uri, _
                                ByVal [error] As Exception)
        SetOptionalParametersOnLogger(user, url)
        LogError(message, [error])
    End Sub

    Public Shared Sub LogInfo(ByVal message As String, ByVal type As LogType)
        Dim logger As ILog = Nothing
        If type = LogType.Notify Then
            logger = LogManager.GetLogger(LogType.Notify.ToString)
        Else
            logger = LogManager.GetLogger(_defaultApplicationLogger)
        End If
        If logger.IsInfoEnabled Then
            logger.Info(message)
        End If
    End Sub

    Public Shared Sub LogWarning(ByVal message As String, ByVal [error] As Exception)
        Dim logger As ILog = LogManager.GetLogger(_defaultApplicationLogger)
        If Not [error].InnerException Is Nothing Then
            [error] = [error].InnerException
        End If
        If logger.IsWarnEnabled Then
            logger.Warn(message, [error])
        End If
    End Sub

    Public Shared Sub LogWarning(ByVal message As String, _
                                 ByVal user As IPrincipal, ByVal url As Uri, _
                                 ByVal [error] As Exception)
        SetOptionalParametersOnLogger(user, url)
        LogWarning(message, [error])
    End Sub

    Private Shared Sub SetOptionalParametersOnLogger(ByVal user As IPrincipal, ByVal url As Uri)
        'set user to log4net context, so we can use %X{user} in the appenders
        If Not user Is Nothing AndAlso user.Identity.IsAuthenticated Then
            MDC.[Set]("user", user.Identity.Name)
        End If

        'set url to log4net context, so we can use %X{url} in the appenders
        MDC.[Set]("url", url.ToString())
    End Sub
End Class

Comments on LogHandler

  • It's a pretty simple class which is easy to use. I could have added more wrapper methods with overload
  • The LogType enum defines whether the message should be notified (emailed) or not.
  • If I forget to set the level on the logger in the Log4Net.config, the logger.IsInfoEnabled will return false.
  • I am using the MDC class in the Log4Net framework to add the custom entries in the logged message for user and url (see Log4Net.config above)

Handling an error and notifying with success

Sometimes when you know what could go wrong and you want to display a nice error message to the user, you could handle the error and display an errormessage to the user.

Example:

Private Function CreateUser() As User
    Dim userName As String = TextBoxUserName.Text
    Dim password As String = TextBoxPassword.Text
    Try
        Dim user As New User(userName, password)
        LogHandler.LogInfo("Yahoo! User with username " & userName & " created.",
                           LogHandler.LogType.Notify)
        Return user
    Catch iunex As InvalidUserNameException
        PageTools.DisplayError(Page, iunex)
        LogHandler.LogWarning("Error creating user with username " & userName, iunex)
    Catch ipex As InvalidPasswordException
        PageTools.DisplayError(Page, ipex)
        LogHandler.LogWarning("Error creating user with password " & password, ipex)
    End Try
    Return Nothing
End Function

Comments on CreateUser:

  • If successful, a notification is sent by email by using the LogInfo method and using LogHandler.Logtype.Notify
  • The User class will throw InvalidUserNameException or InvalidPasswordException in the credentials are invalid. I wish to display the errors to the user instead of displaying a general error page. In real life I would probably use some validation before calling the User constructor, but this is only an example. ;-)
  • In addition to displaying the error to the user, the error is logged as a warning.This means it will be logged, but no email will be sent to the mailbox as this is not an error in the application.
  • All other exceptions raised when creating the user will be caught in Application_Error in Global.asax and logged there.

Loginformation

Ok, now I have all the code I need to do decent logging. So what do I expect to see in the logfiles?

When building the application in DEBUG mode I will see the following in the logfile:

2008-12-11 16:56:24,453 [14] INFO  Application (null) (null) - ============================
2008-12-11 16:56:24,468 [14] INFO  Application (null) (null) -     Starting application
2008-12-11 16:56:24,468 [14] INFO  Application (null) (null) - ============================
2008-12-11 16:56:25,937 [14] WARN Application 3DX5G3J\knuth http://localhost/fdb/default.aspx -
                                  Error creating user with username Knut Hamang
DAL.InvalidUserNameException: Username is already in use! Please select another username.
   at DAL.User..ctor(String username, String password) in C:\Knut\code\Repository\Internal_Systems\fdb\trunk\DAL\User.vb:line 97
   at fdb.default.CreateUser() in C:\Knut\code\Repository\Internal_Systems\fdb\trunk\Web\default.aspx.vb:line 69

Building in RELEASE  mode I get the following information:

2008-12-11 16:59:21,406 [14] INFO  Application (null) (null) - ============================
2008-12-11 16:59:21,421 [14] INFO  Application (null) (null) -     Starting application
2008-12-11 16:59:21,421 [14] INFO  Application (null) (null) - ============================
2008-12-11 16:59:22,812 [14] WARN Application 3DX5G3J\knuth http://localhost/fdb/default.aspx -
                             Error creating user with username Knut Hamang
DAL.InvalidUserNameException: Username is already in use! Please select another username.
   at DAL.User..ctor(String username, String password)
   at fdb.default.CreateUser()

The difference is the stacktrace. I get the stacktrace in both cases, but I also get the line numbers in DEBUG mode. I can still read the trace and locate the method in the file that throws the error. The conclusion is that I get enough information to trace and fix the error, if there is one.

Please leave any comments on the configuration, and feel free to discuss different logging strategies for Web Applications.

Tags: ,

bug: VS 2008 – Web Application Project opened as Web Site

Monday, November 3rd, 2008 | .NET | 6 Comments

I just bumped into a weird Visual Studio (aka. Vicious Studio)  bug. Not the first, but this is a pretty annoying one. I have taken an old .NET 1.1 Web application and converted it to .NET 3.5 using the VS Conversion Wizard. Everything seems ok, and I convert to Web Site to a Web Application Project. No problems so far. I fix some issues, close the solution, do some other stuff. Some days later I open the solution again. I then have about 200 errors and the Web Application Project is opened as a Web Site. Also the designer and resx files are not connected to the asp and codebehind files:

It's not possible to change the project type in Visual Studio, as the project does not have a "properties" context menu item. The only option in the context menu is "property pages" as with regular web sites. Visual Studio actually thinks it's a Web Site and not a Web Application project anymore. The other missing context menu option is the "Convert to Web Application". So Visual Studio thinks it's a Web Site that cannot be converted to a Web Application Project. Not surprisingly as I converted the Web Site to a Web Application Project right after the Conversion Wizard.

Ok, I have to start digging into the project and solution files. Comparing them to other solutions using Web Application project files, I can't seem to find anything suspicious. After some googling with no result, I decide to stare at the screen for a while and use WinMerge to determine what the difference might be. Suddenly I find one minor difference:

The solution file that works:

Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "Clock", "Clock.vbproj", "{3B3D0F02-D310-4BFB-83AD-F62758BB8624}"

The one that fails:

Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "Calendar", "Calendar\", "{7B411329-B1CB-457F-A954-898DX16B85A6}"

That's it. The Calendar project reference is missing the whole path to the project file. When i change it to:

Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "Calendar", "Calendar\Calendar.vbproj", "{7B411329-B1CB-457F-A954-898DX16B85A6}"

it opens as a Web Application Project, and now the resx and designer files are properly connected:

There might be other issues causing this behaviour, but at least this solved my problem. This is just the everyday life using Visual Studio. Actually I think it's a great IDE, but there are some strange behaviours now and then.
Update - In some occasions you might wan't to remove the .webinfo file. This file can be causing this behaviour.  Just remove it and instead set the startup path for your application in properties for the Web Application project.

Tags: ,

pornos porno deutsch frei porno porno gratis porno free porno porno gratis porno free deutsche pornos pornos video>