Archive for the ‘.NET’ Category
Windows 2008 & Visual Studio Web Setup: The installer was interrupted before ApplicationName could be installed
Although how much I hate creating setup packages, I had to create a few setups for some of my projects recently. While I was working on setup projects, I found that, the capabilities of Visual Studio Setup & Deployment projects are shockingly limited, and not to mention I faced a lot of issues while creating setup projects in Visual Studio. Few people suggested me to use WiX. WiX certainly is good and far more flexible solution for building Windows Installer Setup Packages, but it has got a very steep learning curve.
I will be making few posts in future about the problems, that I faced during my experience creating setup packages using Visual Studio. So, here you go. Here is the first problem.
The Problem
I was working on a simple Web Setup project in Visual Studio 2008. The setup worked fine in XP & Windows 2003 server. But, when I tried installing the setup in Windows Server 2008, I got this nice error message that said. “The installer was interrupted before <MyApplicationName> could be installed. You need to restart the installer to try again.”
Having faced many problems earlier with msi packages, I at least knew how to start the msi package in verbose mode to create the log files.
Launch your msi in verbose mode:
msiexec /i yoursetup.msi /lv "C:\yourdirectory\logfile.txt"
I searched for terms like “ERROR” & “FATAL” in the log file
. I got this.
Action ended 15:57:43: WEBCA_MYSETUPTARGETVDIR. Return value 1. MSI (c) (8C:20) [15:57:43:204]: Doing action: WEBCA_SetTARGETSITE Action start 15:57:43: WEBCA_SetTARGETSITE. MSI (c) (8C:20) [15:57:43:206]: Note: 1: 2235 2: 3: ExtendedType 4: SELECT `Action`,`Type`,`Source`,`Target`, NULL, `ExtendedType` FROM `CustomAction` WHERE `Action` = 'WEBCA_SetTARGETSITE' MSI (c) (8C:A0) [15:57:43:226]: Invoking remote custom action. DLL: C:\Users\ADMINI~1\AppData\Local\Temp\1\MSI4225.tmp, Entrypoint: SetTARGETSITE INFO : [03/31/2010 15:57:43:286] [SetTARGETSITE ]: Custom Action is starting... INFO : [03/31/2010 15:57:43:287] [SetTARGETSITE ]: CoInitializeEx - COM initialization Apartment Threaded... ERROR : [03/31/2010 15:57:43:290] [SetTARGETSITE ]: FAILED: -2147221164 ERROR : [03/31/2010 15:57:43:291] [SetTARGETSITE ]: Custom Action failed with code: '340' INFO : [03/31/2010 15:57:43:293] [SetTARGETSITE ]: Custom Action completed with return code: '340' Action ended 15:57:43: WEBCA_SetTARGETSITE. Return value 3. MSI (c) (8C:20) [15:57:43:297]: Doing action: FatalErrorForm Action start 15:57:43: FatalErrorForm.
I could see that the action WEBCA_SetTARGETSITE was failing. But I had not idea what was wrong, except that the term itself said Set Target Site failed. So I turned up to Google and landed on this blog post.
So the real problem is that my setup is unable to get the “Default Web Site” from IIS7.
The Solution
I installed the “IIS6 Metabase Compatibility” role using Role Manager as mentioned in the blog post and my setup started working. Existing software & scripts can interface with IIS7 only if the Metabase compatibility component is installed in IIS7.
Thanks to Galin Iliev.
.NET Type Forwarding – Moving Types Between Assemblies
I learned about this really cool feature in the .NET framework while reading an MS certification book, and could not stop blogging about it. Type forwarding in .NET allows you to move type from one assembly to another without recompiling applications that use the old assembly.
Important Notes:
- Microsoft Visual Basic 2005 does not support the use of the TypeForwardedToAttribute attribute to forward types written in Visual Basic 2005. Applications written in Visual Basic 2005 can use forwarded types written in other languages.
- The compilers do not support forwarding generic types in .NET 2.0, 3.0 and 3.5. Support for this was added in .NET 4.0.
For this example, I would write one assembly called Animal that would contain a class called Dog, which would be consumed by an application called Consumer1. Later, I would move the Dog class to a new assembly called Canine, and we would see how we can make the Consumer1 application still work using .NET type forwarding feature.
Animal (Class Library)
As discussed here is the Dog class that would reside inside the Animal assembly.
Dog.cs
namespace Animal
{
using System;
public class Dog
{
/// <summary>
/// Make the dog bark.
/// </summary>
public void Bark()
{
Console.WriteLine("Arrgh.... Woof Woof!");
}
}
}
It’s a very simple class that contains a public method called Bark, which would output "Arrgh…. Woof Woof!" to the console when invoked.
Consumer1 (Console Application)
I would now write our first application that would consume the animal assembly. Its a simple console application that has reference to the Animal assembly.
namespace Consumer1
{
using System;
using Animal;
/// <summary>
/// The program.
/// </summary>
internal class Program
{
#region Methods
/// <summary>
/// The entry point.
/// </summary>
/// <param name="args">
/// The command line arguments.
/// </param>
private static void Main(string[] args)
{
Console.WriteLine("Consumer 1 Application");
Dog dog = new Dog();
dog.Bark();
Console.ReadKey();
}
#endregion
}
}
In the main method of the Consumer1 application I have created an instance of the Dog class and then called its Bark method. When we run this application we would get the following output.
Output:
Consumer 1 Application
Arrgh…. Woof Woof!
Canine (Class Library)
I moved the Dog class from Animal assembly to the new assembly called Canine.
namespace Animal
{
using System;
public class Dog
{
/// <summary>
/// Make the dog bark.
/// </summary>
public void Bark()
{
Console.WriteLine("Arrgh.... Woof Woof! (Inside New Assembly)");
}
}
}
The only difference in the class definition here, is the text that I output to the console when the Bark method is invoked. I have changed it so that we can easily spot out that our old application (Consumer1) is accessing the Dog class from the new Canine assembly.
Also you might wonder, if the assembly name is Canine then why is the namespace for the Dog class still Animal? It’s necessary to keep the old namespaces while moving types between assemblies for the old applications to find the type in the new assembly.
If we deploy the Animal assembly without the Dog class then existing installed applications that were compiled against the old Animal assembly would break. Unless, we use type forwarding in the modified Animal assembly and let it know where to look for the Dog class when its requested. To enable type forwarding we need to do the following things:
- Add a reference of the new Canine assembly to the Animal assembly.
- Add the TypeForwardedToAttribute attribute to the animal assembly and specify the type to be forwarded.
Normally we add all assembly attributes to the AssemblyInfo.cs file. The TypeForwardedToAttribute attribute resides in the System.Runtime.CompilerServices namespace. Add the following line to the AssemblyInfo.cs.
using System.Runtime.CompilerServices; // Type forward the dog class to the Canine assembly [assembly: TypeForwardedTo(typeof(Animal.Dog))]
When any application would look for the Dog class in the Animal assembly it would be forwarded to the Canine assembly. Now when we deploy the new Animal & Canine assembly though the Consumer1 application does not have a reference to the Canine assembly, it would still find the Dog class and produce the following output.
Output:
Consumer 1 Application
Arrgh…. Woof Woof! (Inside New Assembly)
Deploying both the assemblies are important. Otherwise the Consumer1 application will not find the Dog class, and would crash.
Source Code:
C# – Change log4net Log Path and Level Programmatically
Log4Net makes it incredibly easy to implement logging functionality in your application. Log4Net configuration can be little bit tricky, but its easy to learn.
Most of the time when I am working on a project the application configurations including log path and level are fetched from the database.
Log4Net doesn’t provide any straight forward way of fetching log file path or level from database (because its not necessary). To change the log file path and level programmatically we have to write our own log file appender.
For this demonstration I will write one rolling file appender. The custom file appender class should inherit from the log4net’s RollingFileAppender class. We have to override the File property of the appender and change the log path. My rolling file appender class looks like this:
My Rolling File Appender:
namespace MyLog4Net.LogAppenders
{
using System;
using log4net;
using log4net.Appender;
using MyLog4Net.Interfaces;
using MyLog4Net.Services;
/// <summary>
/// My log4net Rolling file appender.
/// </summary>
public class MyLog4NetFileAppender : RollingFileAppender
{
#region Constants and Fields
/// <summary>
/// Component parameter business layer
/// </summary>
private static IConfigService service;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="MyLog4NetFileAppender"/> class.
/// </summary>
public MyLog4NetFileAppender()
: this(new ConfigService())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MyLog4NetFileAppender"/> class.
/// </summary>
/// <param name="configService">
/// The config service.
/// </param>
public MyLog4NetFileAppender(IConfigService configService)
{
service = configService;
// get the log level
// must be a proper log4net Threshold
string logLevel = service.GetLogLevel();
// set the log level
LogManager.GetRepository().Threshold = LogManager.GetRepository().LevelMap[logLevel];
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the log file name.
/// </summary>
/// <value>The log file name.</value>
public override string File
{
get
{
return base.File;
}
set
{
try
{
// get the log directory
string logDirectory = service.GetLogPath();
// get the log file name from the config file.
string logFileName = value.Substring(value.LastIndexOf('\\') + 1);
// build the new log path
if (!logDirectory.EndsWith("\\") || !logDirectory.EndsWith("/"))
{
logDirectory += "\\";
}
// replace the new log file path
base.File = logDirectory + logFileName;
}
catch (Exception ex)
{
// TODO: Log the error
// use the default
base.File = value;
}
}
}
#endregion
}
}
Setting The Log Level (Threshold):
public MyLog4NetFileAppender(IConfigService configService)
{
// Service layer that will be used to fetch config data
service = configService;
// get the log level
// must be a proper log4net Threshold
string logLevel = service.GetLogLevel();
// set the log level
LogManager.GetRepository().Threshold = LogManager.GetRepository().LevelMap[logLevel];
}
In the constructor of this class I fetch the log threshold configured in the database using the service.GetLogLevel() method. The LogManager.GetRepository() returns the default log4net repository of the calling assembly. LogManager.GetRepository().LevelMap gives us a set of default log4net levels. We change the log level by pasing the value fetched from the database to the current repositories Threshold property.
Setting The Log Path:
public override string File
{
get
{
return base.File;
}
set
{
try
{
// get the log directory
string logDirectory = service.GetLogPath();
// get the log file name from the config file.
string logFileName = value.Substring(value.LastIndexOf('\\') + 1);
// build the new log path
if (!logDirectory.EndsWith("\\") || !logDirectory.EndsWith("/"))
{
logDirectory += "\\";
}
// replace the new log file path
base.File = logDirectory + logFileName;
}
catch (Exception ex)
{
// TODO: Log the error
// use the default
base.File = value;
}
}
}
When log4net is initializing the File property of the file appender would be called. Here the value would be the file name that was set in the log4net configuration file. In this property we extract the file name and then append the log path that we fetched from the database.
Using Our Custom Appender:
To use our custom appender we would create a log4net appender section in the config file and use our appender in the appender type. I like placing my log4net configuration is a different file. My log4net configuration file looks like:
Log4Net Configuration File:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<!-- log4net -->
<log4net>
<!-- Define some output appenders -->
<appender name="MyRollingFileAppender" type="MyLog4Net.LogAppenders.MyLog4NetFileAppender">
<param name="File" value="..\\Log\\MyApplication-log-file.txt" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Size" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header] " />
<param name="Footer" value="[Footer] " />
<param name="ConversionPattern" value="%d [%t] %-5p %C %M - %m%n" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<!-- Setup the root category, add the appenders and set the default level
ALL
DEBUG
INFO
WARN
ERROR
FATAL
OFF
For example, setting the threshold of an appender to DEBUG will also allow INFO,
WARN, ERROR and FATAL messages to log along with DEBUG messages. (DEBUG is the
lowest level). This is usually acceptable as there is little use for DEBUG
messages without the surrounding INFO, WARN, ERROR and FATAL messages.
Similarly, setting the threshold of an appender to ERROR will filter out DEBUG,
INFO and ERROR messages but not FATAL messages.
-->
<root>
<level value="ALL" />
<appender-ref ref="MyRollingFileAppender" />
</root>
</log4net>
</configuration>
Notice that instead of using log4net’s RollingFileAppender class I am using our MyLog4NetFileAppender class.
Initializing Log4Net:
To initialize log4net put the following code in the AssemblyInfo.cs file.
/* Configure log4net log4net configuration will be searched in the .config file*/ [assembly: XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
The above code tells log4net to look for log4net.config file in the application and initialize itself.
Now everything is ready you can now run your application. To check if the code works or not you can put breakpoints in the constructor and File property of the appender.
Source:
Download the source code for this article MyLog4Net.zip
Visual Studio 2010 Beta 2 Now Out For Public
Finally Visual Studio 2010 Beta 2 is out for public (and not just subscribers). To download visit this link or download the ISO from here. Make sure you completely uninstall Visual Studio 2010 Beta 1 before installing Beta 2.
Visual Studio 2010 brings many new features that we were only able to achieve using 3rd party add-ins like CodeRush/Resharper.
Please visit the below links to learn more about VS 2010 and .NET 4.0 features:
MSBuild Context Menu: Build .NET Project/Solution From Explorer
Sometimes I don’t like opening visual studio just for building the latest source code from the repository. I don’t remember who wrote the original registry tweak for this, but the credit goes to the original author.
The original tweak allowed to compile Visual Studio 2005 solutions as I use Visual Studio 2008 I had to modify the original tweak to make it work with VS2008. Click Here to download the modified files.

Unzip the files and you will see two folders. VS2005 is the original one and VS2008 is the modified version. Each folder contains two registry files. One to add the commands to windows explorer and another to remove them. If you have both VS2005 and VS2008 installed on your machine you can add both the versions to the registry or you can add either of them.
Once you have merged the files in your windows registry you can see two commands added to your explorer context menu when you right click on any solution or project file. One for Debug build and one for Release build.
When you click on either of the commands a command window will open and you can see you build status.
Credit goes to the original author.

