Log4net for .NET 4.0 & .NET 3.5/4.0 client

By DimitriC at January 19, 2012 08:26
Filed Under: General, log4net, tools & Utilities, Programming

Release 1.2.11 of log4net has these changes (source):

 

General:

 

log4net 1.2.11 is not only a bug fix release, it also adds support for Microsoft® .NET 4.0 as well as the client profiles of .NET 3.5 and .NET 4.0. … The binary distributions no longer contain assemblies built for the Compact Framework 1.0 or the Shared Source CLI - you can build those yourself using the source distribution.

NOTE: The signature of ILoggerFactory.CreateLogger has changed!

 

Some of the bug fixes:

- Visual Studio 2010 .NET 4.0 Application does not copy log4net lib to bin directory

- RemoteFileAppender Tests fail on Windows 7

- log4net doesn't log when running a .Net 4.0 Windows application built in Release mode

- EventLogAppender's ActivateOptions throws SecurityException on Vista/Win2k3 and later when not run as administrator

 

Some of the improvements:

 

- support .NET 2.0 connectionStrings configuration section

- IPAddressConverter improvement for .NET 2 or .NET 3

- Add Cc and Bcc support to SmtpAppender

 

Some new features:

 

- add the ability to roll files based on universal time (UTC).

- Support ASP.Net related PatternConverters to allow items from the HttpContext.Current.Session, Cache, Request, etc. to be captured.

- Build for Compact Framework 2.0

- Added ExceptionEvaluator

- Add TimeEvaluator

- New property ReplyTo address for the SmtpAppender required

- Buildable with VS 2008 and .NET FW 3.5

  • - Support .NET 4.0 including Client Profile

 

 

Previous articles:

 

- Logging: Log4Net Part I

- Logging: Log4Net Part II

- Logging: Log4Net Part III

- Logging: What/When to log?

- Logging: Log4Net Custom AdoNetAdapter and RollingFileAppender with XML

 

Links:

 

- Log4net web site

- Download Log4net

Visual Studio 11 Developer Preview

Found the MSDN newsletter in my mailbox this morning. First topic that caught my eye: Visual Studio 11 Dev Preview! Another one? Indeed!!! So here is some more information on the new kid on the block.

 

What's New in Visual Studio 11 Developer Preview

Visual Studio 11 Developer Preview Training Kit

 

.NET Framework 4.5 Developer Preview

Visual Studio SLN-file tools

By DimitriC at December 12, 2011 11:19
Filed Under: Programming, tools & Utilities, Visual Studio

On Hosam Kamel’s blog there is an interesting post on a tool that helps you finding your way in an SLN-file (Visual Studio Solution file).

 

“Tools for SLN File” is a tool that makes it easier for developers to compare, merge or filter the Solution (.Sln) Files generated by Visual Studio. (source)

Benefits and Features

Using the SLNTools provides the following advantages:

  • - Make it easier to compare SLN files versus a 'generic' file comparer. For more information on the compare function see SLNTools Compare.
  • - Make it easier to merge SLN files versus a 'generic' file merger. For more information on the merge function see SLNTools Merge.
  • - Make it possible to create filters for a SLN file. The way it work is that when the filter file is opened, a temporary solution is created dynamically. The created solution file contain only the projects that are specified in the filter, and all the dependencies of those projects. This make it possible to have a mega-solution that contain all the projects needed to build the complete system but still have the possibility to work efficiently on a subset of the system. As you might know, Visual Studio is a lot faster when you have a solution with 10-20 projects instead of one with 200+ projects (opening the solution, building, etc). For more information on the filter function see SLNTools Filter.

 

For downloading the tools or viewing the full article, please visit the original blog post.

Service Pack Collection for Visual Studio 2010, SQL Server 2008 and Microsoft Office 2007

By DimitriC at December 05, 2011 11:05
Filed Under: General, Microsoft, Visual Studio, tools & Utilities, SQL, Update, Office

Security Development Lifecycle resources

There are a bunch of new SDL resources available on the Microsoft Security Development Lifecycle page. For every step in the software development process (Requirements, Design, Implementation, Verification, Release) there are tools and/or training videos available. For a video giving an overview of the SDL tools, click here.

 

Source

 

Requirements

Templates:

- SDL Process Template for Visual Studio Team System 2008

- MSF-Agile + SDL Process Template for Visual Studio Team System 2010

- MSF-Agile + SDL Process Template for Visual Studio Team System 2008

 

Videos:

 

 

Design

 

SDL Threat Modeling Tool

 

For more information on the treat modeling tool, click here.

 

Implementation

 

FxCop 

 

FxCop analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements. For more information, click here. Watch the video here.

 

Anti-Cross Site Scripting Library

 

This is specifically designed to help mitigate the potential of Cross-Site Scripting (XSS) attacks in web-based applications. Watch the video here.

 

Microsoft Code Analysis Tool .NET

 

CAT.NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL Injection, and XPath Injection. Watch the video here.

 

 

Verification

BinScope Binary Analyzer

 

BinScope Binary Analyzer is a verification tool that analyzes binaries to ensure that they have been built in compliance with the SDL requirements and recommendations. Watch the video here.

 

SDL MiniFuzz File Fuzzer

 

MiniFuzz is a basic testing tool designed to help detect code flaws that may expose security vulnerabilities in file-handling code. Watch the video here.

 

AppVerifier

 

Application Verifier is a runtime verification tool for native code that assists in finding subtle programming errors that can be difficult to identify with normal application testing. For more information, click here.

 

SDL Regex Fuzzer

 

SDL Regex Fuzzer is a verification tool to help test regular expressions for potential denial of service vulnerabilities. Watch the video here.

 

Attack Surface Analyzer Beta

 

Attack Surface Analyzer is a tool that highlights the changes in system state, runtime parameters and securable objects on the Windows operating system.

 

 

Release

The release resources are the same templates and videos as the ones in the Requirements section.

Visual Studio LightSwitch

By DimitriC at August 31, 2011 17:07
Filed Under: Documentation, Microsoft, Programming, Visual Studio, Training, tools & Utilities

The first post I did about this was the announcement of it's beta release. The final version has been available for a while now, so here we go :)

 

What is Visual Studio LightSwitch?

Microsoft Visual Studio LightSwitch is a simplified self-service development tool that enables you to build business applications quickly and easily for the desktop and cloud. What can your business do with LightSwitch? Watch this brief introduction to find out.

 

Links & resources:

Visual Studio LightSwitch page
MSDN LightSwitch Development Center
Visual Studio LightSwitch Technical White Paper Series

 

LightSwitch videos:

 

Overview with Jason Zander
Build Custom Business Apps. Coding Optional.

Introductory videos

Creating Your First Business Application
Data, Queries and Code in LightSwitch 2011
Controlling Access to Your Business Application
Publishing Your LightSwitch Application

Advanced videos

Understanding the LightSwitch Architecture
Deploying Your Application to the Cloud
Advanced LightSwitch Customization
Advanced LightSwitch Extensions

Extension videos

DevExpress LightSwitch Extensions
Infragistics LightSwitch Extensions
RSSBus LightSwitch Extensions

Microsoft All-in-one code framework

Something I found that might come in handy:

 

The Microsoft All-In-One Code Framework is a free, centralized code sample library driven by developers' needs. Our goal is to provide typical code samples for all Microsoft development technologies, and reduce developers' efforts in solving typical programming tasks.

 

Codeplex page

Download (from Codeplex)

Request a code sample

 

For a full list of downloads (sorted by technology), please check the Codeplex download page. There are samples available for C++, ASP.NET, Silverlight, Azure, Office, Windows, WPF, Windows Security, and many more…

Team Foundation Server 2010 Resources

Here are some resources that might be useful when working with (or learning) Team Foundation Server 2010.

 

Team Foundation Installation Guide for Visual Studio 2010

Description:
Team Foundation Installation Guide 2010 includes instruction for installing Team Foundation Server, Team Foundation Server Proxy and Team Foundation Build Services.

Note: After you download the installation guide, you cannot view its contents unless you right-click the .chm file, click Properties, and then click Unblock.

 

Download

 

Administration Guide for Microsoft Visual Studio 2010 Team Foundation Server

Description: Effective administration of Team Foundation Server is important to the success of your team projects. You can use this downloadable version of the administration content available on MSDN for local review of critical administration concepts, procedures, and walkthroughs.

Download

 

Visual Studio 2010 Team Foundation Server Monitoring Management Pack

Description: The Team Foundation Server 2010 Monitoring Management Pack provides both proactive and reactive monitoring of Microsoft Team Foundation Server 2010. It monitors TFS components such as application tier server instances, team project collections, build servers, and proxy servers.

Download

 

Team Foundation Server Integration Tools (March 2011 Release)

Description: The TFS Integration Tools is a project developed by the Team Foundation Server (TFS) product group and the Visual Studio ALM Rangers to integrate Team Foundation Server with third party systems for migration and synchronization of data.  Although the tools can be used for many purposes, planning, thorough testing and honest evaluation of extra resources and cost that will be required should precede any decision to use the Integration Tools.  The Integration Tools are not intended to replace a server upgrade as a path to TFS2010 and this scenario should be avoided if possible.

The March 2011 release includes the following features:

  • Out of the box adapter to Team Foundation Server 2010
  • Out of the box adapter to Team Foundation Server 2008
  • Out of the box adapter to Rational ClearCase
  • Out of the box adapter to Rational ClearQuest
  • Out of the box adapter for File system based version control migrations
  • Updated documentation, guidance and case studies (readiness package)
  • Updated User Interface to configure and run integrations
  • Synchronization monitoring tools and reports

Download

 

Visual Studio 2010 Team Foundation Branching guide

Description: The purpose of this project is to build some insightful and practical guidance around branching and merging with Visual Studio Team Foundation Server 2010. The new release focuses on Hands on Labs and includes lots of lessons learnt from the community Q&A.

Download

 

Visual Studio 2010 Team Foundation Server Requirements Management

Description: This Ranger solution addresses the People, Process, and Technology guidance for Requirements Engineering (RE) using Team Foundation Server. The goal of this guidance is to provide formalized Microsoft field experience in the form of recommended procedures and processes, Visual Studio Team System and Team Foundation Server configurations, and skill development references for the Requirements Engineering discipline of your application lifecycle.

Download

 

Microsoft Visual Studio Team Explorer Everywhere 2010

Description: Eclipse plug-in and cross-platform command-line client for Visual Studio 2010 Team Foundation Server.

Download

 

Team Foundation Server Power Tools (March 2011)

Description: A plug-in to Visual Studio, Alerts Explorer provides a graphical user interface that supports flexible subscription of alerts based on check-in, work item change, or build completion.

Download

Microsoft Visual Studio 2010 Service Pack 1

By DimitriC at March 15, 2011 21:18
Filed Under: Microsoft, Update, Visual Studio, tools & Utilities

The Visual Studio 2010 SP1 is available for download here (Web Installer). The service pack is also available as ISO image (1.49GB)

 

From the download site:

 

This download installs Visual Studio 2010 Service Pack 1 (SP1). This service pack release addresses issues that were found through a combination of customer and partner feedback, as well as internal testing. These service packs offer Visual Studio users improvements in responsiveness and stability, as well as completes some high-impact scenarios requested by customers. The full list of updates included in this service pack can be found here.

The known bug with the WCF Service Configuration Editor

By DimitriC at January 21, 2011 22:43
Filed Under: Programming, Visual Studio, tips & tricks, tools & Utilities, WCF

In both Visual Studio 2008 and 2010 there is a bug when you try to use the WCF Service Configuration Editor. The editor should be reachable through the Tools-menu or by right clicking a configuration file (web.config / app.config). This appears to be a known bug. It’s not blocking, but it’s easier to access the editor directly from the configuration file (then the file is immediately loaded in the editor). 

When you just started Visual Studio, and right-click a configuration file, the editor is not visible as an option:

 

image

 

 

Now open the editor from the tools menu (Tools –> WCF Service Configuration Editor):

 

image

 

Now the editor will open. You can close it immediately and go back to the configuration file. When you right-click it now, you will see that the option to open the editor is available:

 

image

Free e-books on .NET and architecture

By DimitriC at October 12, 2010 08:07
Filed Under: Architecture, Books, Microsoft, Programming, tools & Utilities, Training

The new MSDN Flash arrived this morning, and it offered 7 free e-books (actually 6 e-books and some reference cards) on .NET and architecture. For the original article that was posted in the newsletter, click here.

 

The books:

 

- Foundations of programming (Karl Seguin)
- Microsoft Application Architecture Guide, 2nd Edition (Microsoft)

- Rob Miles C# Yellow Book 2010 (Rob Miles)

- Threading in C# (Joe Albahari)

- Improving .NET Application Performance and scalability (Microsoft)

- Applying Design Patterns (Anoop Madhusudanan)

 

And some References Cards (RefCardz) from DZone:

 

- Getting Started with WCF 4.0 (Scott Seely)

- Getting Started with Silverlight + Expression Blend (Victor Gaudioso)

- Essential F# (Chance Coble, Ted Neward)

SQL Server 2008 Service Pack 2 released

By DimitriC at October 06, 2010 18:24
Filed Under: SQL, tools & Utilities, Microsoft

SQL Server 2008 SP 2 is available for download.

 

From the TechNet Flash:

 

Both the Service Pack and Feature Pack updates are now ready for download on the Microsoft Download Center. Service Pack 2 for SQL Server 2008 includes new compatibility features with SQL Server 2008 R2, product improvements based on requests from the SQL Server community, and hotfix solutions provided in SQL Server 2008 SP1 Cumulative Update 1 to 8.

 

Log4Net logging framework, custom AdoNetAdapter and RollingFileAppender with XML

By DimitriC at October 04, 2010 10:00
Filed Under: Architecture, log4net, Programming, tips & tricks, tools & Utilities

Mike Bevers has done some cool work with log4net. Next to creating his own logging framework using L4N, he also implemented a custom AdoNetAdapter (logging to a database) and a RollingFileAppender with XML.

 

For more information, please check his blog, or the Log4Net posts:

 

- Logging Framework with Log4Net
- Log4Net: custom AdoNetAppender
- Log4Net: RollingFileAppender with XML

Microsoft Web Farm Framework beta

By DimitriC at September 16, 2010 07:41
Filed Under: Architecture, Beta, Microsoft, Technet, tools & Utilities

From Scott Guthrie’s blog:

 

Last month we released a beta of the Microsoft Web Farm Framework. The Microsoft Web Farm Framework is a free product we are shipping that enables you to easily provision and mange a farm of web servers.  It enables you to automate the installation and configuration of platform components across the server farm, and enables you to automatically synchronize and deploy ASP.NET applications across them.  It also supports integration with load balancers - and enables you to automate updates across your servers so that your site/application is never down or unavailable to customers (it can automatically pull servers one-at-a-time out of the load balancer rotation, update them, and then inject them back into rotation).

 

Downloads: X86 / X64

 

 

Features:

- One step provisioning of servers added to a farm
- Platform Provisioning using Web PI
- Application Provisioning using Web Deploy
- Policy-based Provisioning
- Installation of additional platform components and content
- Reduced down time with load balancing integration using ARR
- Up-to-date status and trace logs of server farm servers
- Extensible model that allows you to write additional providers

 

 

Resources:

- Microsoft Web Farm Framework web site

- Official post on Scott Guthrie’s blog (includes tutorial)

Microsoft Visual Studio LightSwitch beta 1

By DimitriC at September 02, 2010 08:11
Filed Under: Beta, Microsoft, Programming, tools & Utilities, Visual Studio

Introducing the newest member of the Visual Studio family:

 

Visual Studio LightSwitch is a new tool aimed at building data-driven applications, like an inventory system or a basic customer relationship management system incredibly easy.
LightSwitch automatically generates the user interface in Silverlight for a data source and, with no code, you can create, read, update and delete data.

 

Resources:

- Visual Studio LightSwitch Development Center

- Visual Studio LightSwitch Forums

- Jay Schmelzer: Introducing Visual Studio LightSwitch (Channel 9 video)

- Jason Zanders blog

- Beth Massi “How do I” videos

- Download Visual Studio LightSwitch

ODAC for Microsoft Visual Studio 2010 is Here

By DimitriC at August 31, 2010 07:58
Filed Under: Programming, tools & Utilities, Visual Studio, Oracle

I opened my mailbox this morning and found the new Oracle for .NET Developers newsletter in my mailbox.

 

Oracle has just released new versions of Oracle Developers Tools for Visual Studio, ODP.NET, Oracle Providers for ASP.NET, and .NET stored procedure support for Visual Studio 2010 and .NET Framework 4.

Downloads: 32-bit / 64-bit

 

Resources:

 

- Oracle Developer Tools for Visual Studio on MSDN

- List of new features

- Data sheet (PDF)

Introducing Microsoft WebMatrix beta

By DimitriC at July 07, 2010 09:35
Filed Under: ASP.NET, Microsoft, Programming, tools & Utilities, WebMatrix

ScottGu introduced Microsoft's WebMatrix which is a small IDE to make web sites (ASP.NET and PHP). It actually includes everything you need: IIS Developer Express (a development Web server), ASP.NET (a Web framework), and SQL Server Compact (an embedded database). This product is aimed at developers and students who want an easy way to develop web sites. It is emphasized that all the knowledge and skill you gain using Microsoft WebMatrix is applicable to Visual Studio. WebMatrix is a 15MB download (50MB if you don’t have .NET 4 installed) and is quick to install.

Microsoft WebMatrix page
Microsoft WebMatrix Learning page
Scott Guthrie's WebMatrix post
Scott Hanselman's WebMatrix how-to

The Managed Extensibility Framework (MEF)

By DimitriC at June 30, 2010 13:34
Filed Under: Microsoft, Programming, tools & Utilities

Microsoft's Managed Extensibility Framework provides a way to build very modular solutions. See it as a plug-in system where you have a shell which dynamically loads parts. A part is a functionality (or a set of functionalities). It is included in Visual Studio 2010 and Silverlight 4. For thos who are still working with Visual Studio 2008/2005, MEF is available as downloadable package (see links below).

 

MEF presents a simple solution for the runtime extensibility problem. Until now, any application that wanted to support a plugin model needed to create its own infrastructure from scratch. Those plugins would often be application-specific and could not be reused across multiple implementations.

- MEF provides a standard way for the host application to expose itself and consume external extensions. Extensions, by their nature, can be reused amongst different applications. However, an extension could still be implemented in a way that is application-specific. Extensions themselves can depend on one another and MEF will make sure they are wired together in the correct order (another thing you won't have to worry about).
- MEF offers a set of discovery approaches for your application to locate and load available extensions.
- MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering

 source

 

References:

The MEF project site (CodePlex) (includes webcasts)
Practical examples of products and solutions that use MEF
MEF Programming Guide
MEF Architecture

 

Microsoft Enterprise Library 5.0 released

By DimitriC at April 28, 2010 10:20
Filed Under: Architecture, Programming, tools & Utilities

patterns & practices Developer Center

 

Microsoft release version 5.0 of it’s famous Enterprise Library. This is a collection of application blocks designed to assist developers with common enterprise development challenges. Application blocks are a type of guidance, provided as source code that can be used "as is," extended, or modified by developers for use in enterprise development projects.

 

Microsoft Enterprise Library 5.0 – April 2010

Download Microsoft Enterprise Library 5.0

Microsoft Enterprise Library 5.0 Documentation

Microsoft Patterns & Practices

Microsoft Patterns & Practices – Enterprise Library on CodePlex

Logging: Log4Net – Part III

By DimitriC at April 27, 2010 11:48
Filed Under: Programming, tools & Utilities

The idea in Part III is to talk about the more advanced features/settings of Log4Net.

 

First of all, in Part II we saw how we can load the log4net configuration from code by first creating a logger object and then reading the App.config file. You can also use the AssemblyInfo file to do this:

 

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

 

The Watch-flag will tell log4net to keep an eye on the configuration file and reload it every time it has changed. Of course you can also specify your own configuration file by using the ConfigFile property:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "LoggingConfiguration.config", Watch = true)].

 

There is also a parameter you can use if you want to load configuration files based on the extension of the file. Do not that the name of the configuration file must be [NameOfYourApp].[ExtensionYouWant]. In my sample application, in the build output, it needs to be Log4NetSample.exe.log4net before I can use the following line in my AssemblyInfo.cs file. This property cannot be used in conjunction with the ConfigFile property.

 

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension="log4net",Watch=true)]

 

Do note that this attribute can only be used once per assembly. Also note that these attributes are passive, meaning that as long as your application doesn’t need logging, they won’t be read. It is therefore recommended to make a simple call to LogManager.GetLogger() to read and process the attributes(for example: an informational log-statement saying the application has started). And on recommendation of the log4net-people themselves:

 

Therefore it is imperative to make a logging call as early as possible during the application start-up, and certainly before any external assemblies have been loaded and invoked.

 

There is another way to load a configuration file. You can do this by using the DOMConfigurator located in the log4net.Config class. The DOMConfigurator takes a FileInfo parameter. Using this does exactly the same thing as loading a file using an attribute in the AssemblyInfo. Two methods are provided: Configure(…) and ConfigureAndWatch(…).

 

log4net.Config.DOMConfigurator.Configure(new FileInfo("Log4netSample.exe.config"));

log4net.Config.DOMConfigurator.ConfigureAndWatch(new FileInfo("Log4netSample.exe.config"));

 

 

Threading and Log4net

Since Log4net is thread-safe, you can use it in your multithreaded applications. Next to all the logging information described in the Part II you can also let log4net know on which thread your application has thrown an exception. If your application/component is accessed by multiple clients (which can also be other components), you would like to know what client caused the exception to fire. To get all this information, log4net uses a context. Since debugging a multithreaded application is really hard and inconvenient, logging can give you all the information you need to research an error. Contextual information can be contained in different scopes:

 

- Global (shared by all threads in the current AppDomain)

- Thread (visible only to the current managed thread)

- Logical Thread (a logical thread can jump from one managed thread to another)

- Event (only visible to the code generating the event itself)

 

This information can also be found on the log4net web site.

 

To support logging on multithreaded applications, Log4net provides a ThreadContext. This has a properties map (formerly the Mapped Diagnostic Context or MDC, which has been deprecated) and a stack (formerly the Nested Diagnostic Context or NDC, which has also been deprecated). The use of a context is very interesting when dealing with client server architectures. Here the typical configuration is that you have many clients and only a few servers. Each client will be served by a thread on a server.

 

The properties map (Mapped Diagnostic Context)

 

The properties map allows you to store thread-specific information. In the configuration file, you can access these properties and add them in the PatternLayout-section. For example, let’s say you want to register who’s thread is causing an exception, you can add the username to the log by first inserting it as a property in the context:

 

   1: ThreadContext.Properties["user"] = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

 

You can show it in the logging output by adapting the PatternLayout-section and calling the user-property in the App.config file:

 

<layout type="log4net.Layout.PatternLayout">

             <conversionPattern value="%date %-5level %logger (User: %property{user}): %message%newline" />

</layout>

 

Now, where is this information stored? As previously mentioned, the Mapped Diagnostic Context is deprecated and has been replaced with the Properties-collection. Keep in mind that when inserting your properties to this collection will override any properties with the same name in the GlobalContext class. Here is where all the global debugging information is stored. When your properties are read for use in the log-output (so when using the PatternLayout), they are read from the GlobalContext.

 

 

 

The stacks (Nested Diagnostic Context)

 

As the name might give away, this is a stack implementation. Meaning, you can push a stamp (which is preferably something unique like a clientID/ServerID/user/machine name/… or a combination of these kinds of information) on the stack and every log call (whether it’s a informational, error or warning call) is marked with the stamp you provided. This will ensure you that you can recognize the entries in the log by the stamps attached to it. And just like with the properties map, you can add the stamp to the log output by configuring the PatternLayout, and this time using the ndc-property to include the stamp to the message:

 

<layout type="log4net.Layout.PatternLayout">

                  <conversionPattern value="%date %-5level %logger %ndc : %message%newline" />

</layout>

 

You can add messages to the stack in two ways. These are actually the same, but syntactically different.  You can either first push your stamp to the stack, then log what you need to log and pop the messages back from the stack.

   1: ThreadContext.Stacks["NDC"].Push("RecognizableStampOnNDCStack")
   2: ...
   3: log.ERROR("something went wrong");
   4: ThreadContext.Stacks["NDC"].Pop();

Or you can accomplish the same behavior with a using-statement. At the end of the using-statement, the Pop()-method is called automatically.

   1: using (ThreadContext.Stacks["NDC"].Push("RecognizableStampOnNDCStack"))
   2: {
   3:     ...
   4:     log.Error("something went wrong");
   5: }

 

Hierarchical logging

 

You can define a hierarchy of logging. This means you first define a default level of logging and every definition of logging that is placed after it, gives a more narrowing definition. For example:

 

<root>
<level value="ERROR" />
</root>
<logger name="MyAssembly">
	<level value="WARN" />
</logger>

 

This piece of XML in the configuration file (placed inside the log4net-tags) will ensure that every error in your application is logged and all the warnings in the MyAssembly-namespace too. In the name property you can also provide a class name. If the name in the example above would be “MyAssembly.MyClass”, then all the warnings in MyClass will be logged.

Logging: Log4Net – Part II

By DimitriC at April 27, 2010 10:32
Filed Under: log4net, Programming, tools & Utilities

I’ve started an example-application which is a simple Console application. Using this application I will try to show you how to set up, configure and use log4net.

To use log4net in your application, add it as a reference (right-click on the References-folder, navigate to where you’ve extracted the log4net-DLL, select it and click ‘OK’ ). And in the code, add the following using-statement on top of the page:

using log4net;

 

Now we need to add a configuration file to the project. Here we will have the necessary configuration settings for log4net. So right-click on the project, Add, New Item and in the Add New Item window, select the “Application Configuration File”. Leave the default name (App.config) and click “Add”.

image

 

When you open up the App.config file, you will see an empty configuration section.

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

 

First of all we need to define a new configuration section for log4net. We also need to mention by what DLL the configuration section will be handled. We do this by adding a configSections-section in the configuration-section of the App.config:

 

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

 

Do note that we haven’t done any configuration for log4net. At this point, we’ve just told .NET that in the App.config-file there will be a section called “log4net” that will be handled by the Log4NetConfigurationSectionHandler found in the log4net assembly.

 

As said in Log4Net – Part I, log4net allows you to output log-information to several targets. This goes from obvious logging targets such as files, console- and trace-window, Windows Event log, database, email,… to less used output targets such as in memory buffers, Telnet sessions,… For a full list of output targets, check the “Output to multiple logging targets”-section on the features-page. Of course, it’s possible to define multiple output targets in the configuration (write a log-entry to a log-file and send an email to someone with the log-entry).

 

For this example I will log to both a flat file and the console-windows of my application. So now, in the App.config file I will configure log4net to do just that. The configuration will be placed in a section with the same name as I previously defined in the configSections-section (and still within the <configuration>-tags).

 

<log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString"
            value="Log4NetSampleApp-%appdomain_%property{log4net:HostName}.log"/>
      <rollingStyle value="Composite"/>
      <datePattern value="yyyyMMdd"/>
      <maxSizeRollBackups value="10"/>
      <maximumFileSize value="2MB"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level %logger: %message%newline" />
      </layout>
    </appender>

    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
     <threshold value="ERROR" />
     <layout type="log4net.Layout.PatternLayout">
       <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
     </layout>
    </appender>
  </log4net>

 

The RollingFileAppender


<appender>: Here I define the name and type (the library used in log4net to correctly interpret this configuration)

<file>: You can just set the value property to set the name and location of the log file like so:

<file value="C:\logfile.log" /> 
 

But it’s more interesting to define your own name using a pattern. Doing so allows you to add some information to the filename. In my case it will set the name to Log4NetSampleApp-Log4netSample.vshost.exe_DimitriPC.log. Of course, the HostName will always be my PC, but when developing applications that might run on several machines, it’s interesting to see which log file comes from which machine. Note that I haven’t set a path for the file, just a filename. The file will be dropped where the executable is: \Log4netSample\Log4netSample\bin\Debug


<rollingStyle>: This setting will tell log4net to roll files on a the date pattern defined in <datePattern>. This means that it create a new log file per day and append the date as described in the date pattern to the file. So log4net will detect that there isn’t a log file for today, and create one. If it sees that there was a log file for yesterday, it will append yesterday’s date to that file:

Log4NetSampleApp-Log4netSample.vshost.exe_DimitriPC.log20100202

 

Also, for each day it will only keep the last 2MB of log data (the amount of data is defined in the <maximumFileSize>-tag. The value defined in <maxSizeRollBackups> says how many files will be kept per day. In this configuration it will only keep the last 10 files (of max 2MB each).

 

<layout>: This is where we define the layout of the messages that are written to the log-target.  The type defines what log4net-class will interpret what we define in the <conversionPattern>-tag. Do note that every parameter starts with a % (percent sign).

- First we set a timestamp (to the milisecond) which will look something like this: 2010-02-04 07:40:37,624.

- After that comes the level of the logging event. When writing informational logs this will say INFO, when writing errors it will say ERROR. When we look at the code, we will see how to specify the level of the logging event.
The –[number] defines how many characters can be used to specify this information. Here the level can be 5 characters maximum.

- Now we set the logger which is the type of class that actually logs the event. In this case: Log4netSample.Program

- As final piece of information we set the message that we set in the code appended by a newline.

 

For an informational logging event, it gives something like this:


2010-02-04 07:40:37,624 INFO  Log4netSample.Program: test

 

For an error logging event (meaning that an exception was thrown in the code):

2010-02-04 07:41:11,995 ERROR Log4netSample.Program: Problem: System.Exception: something happened
   at Log4netSample.Program.Main(String[] args) in D:\projects\MyProjects\Log4netSample\Log4netSample\Program.cs:line 20

 

Here the stacktrace of the exception is also written to the log file.

 

For a complete overview of all the settings you can use to create your own layout, I refer to the PatternLayout documentation page.

 

The ConsoleAppender

 

<treshold>: This setting can be used to define what logging level you want for this appender. In this case, only the errors will be written to the console window.

Some of the predefined levels recognized by the system are: Off, Fatal, Error, Warn, Info, Debug, All.


The configuration is practically the same for the consoleAppender. The only thing different is the layout of the log message. In the console we will also see the thread number and the NDC-property which is the Nested Diagnostic Context associated with the thread (if any, else it will be null).

 

 

Now that the configuration is done, we can use log4net in our code. In my class I’ve defined a variable to hold the logger.

 

private static ILog log = LogManager.GetLogger(typeof(Program));
 
To make it easier, you can look up the type-parameter used by the GetLogger() method using reflection:
 
private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
 
In my Main method, I will let log4net know it needs to read the App.config to load my configuration:
 
log4net.Config.XmlConfigurator.Configure();

 

And now for some code that will use log4net:

 

try
{
    Console.WriteLine("program started");
    throw new Exception("something happened");
}
catch (Exception ex)
{
    log.Info("test");
    log.Error("Problem: ", ex);
//so we can check the output to the console Console.Read(); }

Logging: Log4Net – Part I

By DimitriC at April 26, 2010 09:01
Filed Under: tools & Utilities

This tool gives you the possibility to log whatever you want (not just errors or warnings but also informational logging) to whatever output target you want (database, flat-file, console window, Trace-window,…).  It’s an open-source tool (ported from log4j) and relatively simple to use so you can use it in all of your projects in which you want to use logging (from small/simple applications to huge/complex ones).

Key Features:

  • - Support for multiple frameworks
  • - Output to multiple logging targets
  • - Hierarchical logging architecture
  • - XML Configuration
  • - Dynamic Configuration
  • - Logging Context
  • - Proven architecture
  • - Modular and extensible design
  • - High performance with flexibility

  •  

     

    For a complete list of the possible output streams, I refer to the log4net feature-page.

    The first point on the key-features-list is interesting. There is not only support for the Microsoft .NET framework 1.0/1.1/2.0/… and it’s variations (.NET Compact Framework, SSCLI 1.0), but also for Mono 1.0/2.0. The website doesn’t mention anything about any Microsoft .NET framework higher than 2.0, but I’m using it in my .NET framework 3.5 project without any issues (since 3.5 is just 2.0 with some extra goodies :) ). For the full list of supported frameworks and framework specific notes, I refer to the log4net Supported Frameworks-page.

 

Concerning the recently released .NET 4 Framework and Visual Studio 2010 there were some minor issues reported. Since there aren’t that many releases of Log4Net, you can always download the source code and compile it yourself.

 

The main issue that i see reported today is that the compiler throws an error saying the log4net assembly reference could not be found:

The type or namespace name 'log4net' could not be found (are you missing a using directive or an assembly reference?)

 

Here you should check you should set the Target Framework to “.Net Framework 4” in your project’s properties.

  • Log4Net can be configured in 2 ways: you can do it in code (programmatically) or you can do it using a configuration file. The second one is most interesting since it will allow you to make modifications to the configuration without having to recompile your code. And it will also allow you to change the configuration while your program is running. In the following parts, the emphasis will be on the configuration by configuration file.

    Get log4net!

Visual Studio 2010 Released

By DimitriC at April 13, 2010 08:26
Filed Under: Microsoft, Programming, tools & Utilities, Visual Studio

VisualStudio2010_340x104

 

Download the trials:

 

- Visual Studio 2010 Professional Trial (ISO – 2.16GB)

- Visual Studio 2010 Premium Trial (ISO – 2.24GB)

- Visual Studio 2010 Ultimate Trial (ISO – 2.25 GB)

- Visual Studio Test Professional 2010 Trial (ISO – 408 MB)

- Visual Studio Team Foundation Server 2010 Trial (ISO – 1,56GB)

 

These trials last for 90 days. After the first 30 days you must register your trial version to obtain a free key so you can use it the additional 60 days.

 

For release notes, list of new features and improvements, I refer to Scott Guthrie's blog and Scott Hanselman's blog.

Microsoft Desktop Player

By DimitriC at April 09, 2010 08:57
Filed Under: Microsoft, Technet, tools & Utilities

TechNet Flash Feed reports:

 

Check out the Microsoft Desktop Player, now in beta, to find contextual content for IT professionals and developers based on your adoption lifecycle. The Desktop Player filters content by topic based on your role and where you are in your adoption lifecycle. It also surfaces local resources based on your zip code.

 

Find videos, webcasts, podcasts, whitepapers and relevant links based on your specific criteria. And get a feed of the latest news for IT pros.

 

You can also download the player directly to your desktop.

 

- Full Message & comments

- Subscribe to the TechNet Flash

Windows 7: tips & tricks e-book

By DimitriC at March 18, 2010 09:44
Filed Under: tools & Utilities, Windows 7

Vasu Jain created a 113-page free e-book containing 50 tips & tricks for Microsoft Windows 7. The content varies from very user-experience related topics such as changing the Windows logon screen and creating themes for Windows 7 to very technical tutorials such as using BitLocker encryption on your USB-drive and customizing your UAC.

 

Download: PDF (5.8MB) – XPS (6.4MB)