Archive for the ‘How To’ Category
ASP.NET WebApplication Fails To Load In Visual Studio 2008 After Upgrading In Visual Studio 2010
Today after upgrading a ASP.NET Web Application project in Visual Studio 2010 the project failed to load in Visual Studio 2008. If the machine has both VS2008 and VS2010 installed then the project loaded just fine. But, if a machine does not has VS2010 installed the Web Application failed to load.
After the upgrade Visual Studio 2010 modified the following:
<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" /> TO <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
Because the v10.0 (second) path is not present in machines that do not have V2010 installed, VS2008 was unable to load the project.
After googling I came across this post which tells to use MSBuild’s condition statements to specify the correct path based on the the Visual Studio version. His solution worked fine, the only problem that I faced was when I open the solution in VS2010, it again asked to upgrade the project file, doing which changed the v9.0 path to v10.0 path.
I had to make few minor changes to solve this problem:
Step1:
Add the V10.0 path before the V9.0 MSBuild extension path with a Condition property to check for the file based on the Solution Version.
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="'$(Solutions.VSVersion)' == '10.0'" /> <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" Condition="'$(Solutions.VSVersion)' == '9.0'" />
Here is we do not specify the Visual Studio 2010 MSBuild extension path first the Visual Studio will try to upgrade the project.
Step2:
After the project file upgrade VS2010 would have changed the FileUpgradeFlags tags value to 0, which would again trigger an upgrade. Remove the Zero from the tag.
<FileUpgradeFlags></FileUpgradeFlags>
Save the project file and reload. Now you will be able to load the project in VS2010 & VS2008 (Even if VS2010 is not installed) without any problem.
Hope it helps.
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
Building The E-TextEditor On Ubuntu 9.04 64 Bit
E-TextEditor a.k.a e is my favorite text editor on windows. AFAIK there is no text editor on linux that matches what e can do except for VIM. When I saw the post about making e open source I was pretty exited and wanted to try it out.
So I grabbed the source from GitHub and thought of building it. I am making this post to explain all the problems that I faced while building e. You may or may not face the same problem or you may face different problem altogether, so good luck.
Grab The Source
Download the latest source code from http://github.com/etexteditor/e/tree/master using the download button available or by using git tool to clone the repository.
Extract the source code somewhere and open the linux-notes.txt in your favorite text editor.
Downloading & Building E-TextEditor
I am a linux n00b so I choose the easiest way to build e according to linux-notes.txt
# The easiest way to build is to use the supplied scripts (example shows debug build): cd external sudo ./get-packages-ubuntu.sh bakefile ./get_externals_linux.sh ./build_externals_linux.sh debug cd .. cd src make DEBUG=1 ./e.debug
I face problem while getting external packages for linux and while building WebKit. The problem was get-packages-ubuntu.sh was unable to install libwxgtk2.8-dev due to header mismatch (Sorry but I don’t remember the exact error. I guess it includes wxWidgets header files) and the link to download tomcrypt and tommath libraries were not found.
I had to download wxWidget headers from their site. I downloaded the amd64 package because I am running Ubuntu 9.04 64 bit
http://apt.wxwidgets.org/dists/jaunty-wx/main/binary-amd64/wx2.8-headers_2.8.10.1-1_amd64.deb
The url’s mentioned in get-external-linux.sh to download tomcrypt and math libraries didn’t resolve because libtomcrypt.com is down at the moment.
wget -nc http://libtomcrypt.com/files/crypt-1.11.tar.bz2 wget -nc http://math.libtomcrypt.com/files/ltm-0.39.tar.bz2
So I had download the crypt-1.11.tar.bz2 and ltm-0.39.tar.bz2 files from http://safari.iki.fi/tom/. You need to be careful here download the exact version mentioned in the script or else it won’t compile.
Now that we have all the dependencies we are now ready to install them and then we can build e.
Install The Dependencies
Double click on the wx2.8-headers_2.8.10.1-1_amd64.deb file and then click on Install Package button to install the file.
Now its time to fix problems in get_external_linux.sh file. If you can write your own script after reading get_external_linux.sh its great, but I am lazy so I just created the arch directory inside the external directory and copied all the files that were supposed to be downloaded by the _download function.
_download()
{
# Download external libraries
echo "Downloading external libraries..."
echo
pushd arch
wget -nc http://libtomcrypt.com/files/crypt-1.11.tar.bz2
wget -nc http://math.libtomcrypt.com/files/ltm-0.39.tar.bz2
wget -nc http://www.equi4.com/pub/mk/metakit-2.4.9.7.tar.gz
wget -nc ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-7.6.tar.gz
wget -nc http://kent.dl.sourceforge.net/sourceforge/tinyxml/tinyxml_2_5_3.tar.gz
wget -nc http://biolpc22.york.ac.uk/pub/2.8.10/wxWidgets-2.8.10.tar.bz2
wget -nc http://builds.nightly.webkit.org/files/trunk/src/WebKit-r43163.tar.bz2
popd
}
I actually downloaded all the files mentioned in the _download function to some location to save me download time just in case if anything goes wrong. You may copy only the missing files and the script will download rest of the files.
Now run the get_external_linux.sh file again by issuing the command ./get_external_linux.sh.
Everything would work fine after this step (worked fine for me). Now issue rest of the commands
./build_externals_linux.sh debug cd .. cd src make DEBUG=1
It will take sometime to complete all these commands. If you get any error here that mean something is wrong with the code and you are missing a patch. All you need to do now is Google the error or fix it yourself or post it here and wait for somebody to answer.
If everything goes fine as expected you can now see e.debug. But as you can see the size of e.debug file is more than 200MB use the strip command to remove all debug information.
# source : http://fixnum.org/blog/2009/e_on_fedora strip e.debug -o e.stripped
Now you will have a e.stripped executable weighing approximately 26MB.
Getting Themes & Bundles
E-TextEditor will not run without the Themes & Bundles. So it needs to be downloaded and placed inside .e folder in your home directory. Issue the following commands to download and export e themes and bundles.
Install Subversion if you haven’t already.
sudo apt-get install subversion svn checkout http://ebundles.googlecode.com/svn/trunk/ ebundles-read-onlysvn export ebundles-read-only ~/.e/
You will see an message Export Complete. Now you can run the e.stripped or e.debug and e should run.

Though I was able to build and run E-TextEditor on my machine but its pretty much useless, it has got lots of bugs and it keeps crashing. I still have to download patches from e repository and rebuild my source.
Hope it helps

