Success in entrepreneurship is for the one who is prepared

January 19, 2010 nnish Leave a comment

Everyone say “Entrepreneurship isn’t easy and not meant for all”. As an experienced kid I do agree. But why isn’t it easy for all? When college drop outs like Bill Gates, Steve Jobs and Mark Zuckerberg can do it then why can’t others? I looked back to see what went wrong in my case. I am writing this down so that, I don’t forget these in my next venture. If this helps you do let me know.

Have A Great Idea, But Sellable –
Just because you have a great idea, it doesn’t mean that you have customers for it.It is important to have a market. Identify the need, make sure your solution is unique and deliver with quality.

Have A Vision -
Vision is the key. If you have an idea and a market you are sure shot to go. But will you sustain? Can you resist the change? Vision is not just a statement you need to add it to your about us page. It should be the one which you strictly follow at every stage. Have milestones and look back if you are aligned to the vision.Make sure every one in the company values the vision and follows it. Write down your vision on the paper and put it into a the board discussion. Remember how Microsoft is committed to its vision “Computer on every desk and in every home”. Today almost every one has a computer which is personal and running a Windows in it.

Choose Right Partners -
Your best friend is not always a right business partner for you. Because you care for your relationship you shouldn’t bring him/her into your business- That’s why they say “Mind Your Own Business”. Money plays a major role in business and but in relationships it is negative. So if you care for them then DO NOT. Your partner is one who stays by you during success as well as failure. Usually it happens the other way when you have your friend in business – He stays with you during success but blames you when you fail. Your partner should think like you, have passion like yours, should be committed like you and should have his/her own capability to make things right. Things fall into place faster when you have partners in different domains like marketing, technology, human resource etc. As they say the Lions, Tigers and other animals constitute a Jungle :) .

Plan Your Capital, Have A Business Plan -
$$$$Money$$$$ Where is the money to invest? What if i loose? I am a family man. The fear – setback. “Money is everything” Money is not everything but money is needed for everything. Its not right to believe that only a rich kid can do a business. Anyone with a smart business plan can do. A business plan is a written description of your business’s future. It should have key inputs like:

1. Executive summary
2. Business description
3. Market strategies
4. Competitive analysis
5. Design and development plan
6. Operations and management plan
7. Financial factors
*source: entrepreneur.com
If you have the fear of investing but you believe in your idea you still can do a great business. I agree that you cannot bring in huge capital into your business, instead approach a venture capitalist with your business plan. Convince him on the Return On Investment(ROI), if it interests him; he will help. VCs just eat up your stake because they are the risk takers. Don’t be greedy just sell your idea and give returns.

Hire Smart People -
Hire smart people on board and give them your best – the Google way. You should have managers who understand your business, maintain business secrets and take right decisions for you. Do not get involved in micromanagement it spoils everything. If you have hired a smart guy, you should leave the decision to him. Make them feel special and motivated at every stage. They are not just your employees, they are the people who are committed to you and the company. They are the reason for your success and you are the reason for the failure.

Have A Process -
You need not be a CMM level company to have a process. If you define a process now, you don’t have to repent later. Your process need not be complicated, but simple enough to take care of everyday activity. In your process make sure you keep milestones and measure your progress.

Change is Constant
Keep changing with times. No business can last long everything has a saturation. Identify the change early and get ready for the future. Once you have the idea which is already in the market, a great vision, hired smart people, and put a process in place then whats your job? – Smell the future, plan, and get ready!

These are just few of the points I remembered when I looked back at my failure. May be this is just right to my situation. Let me know if you guys have some other key points that I should keep in mind.

Some resources:
5 Myths That Can Kill a Start-Up
Entrepreneur

Cheers!

Categories: Entrepreneurship

Animated Gif in WPF using Windows Forms Control

January 11, 2010 nnish Leave a comment

Loading an animated gif into WPF has been a challenge since the version 1 release. WPF does not support loading an animated gifs directly into an declarative <Image> or by code, and hence developers have come out with various workarounds. Some use a raw technique – writing few lines of code which extracts the frames of the GIF and animate them.  One other way to do is using the <MediaElement> FrameworkElement which is in the namespace System.Windows.Controls. <MediaElement> wraps the MediaPlayer class for declarative use and hence it supports both audio and video files. Using MediaElement you can load the animated gif the following way:

<MediaElement Source="file://D:\anim.gif"/>

Remember it is important to use “file://” and an absolute path for loading the gif. So you cannot embed the image to a resource file and now you know one of the limitations of it. Every approach does have advantages and limitations of its own, its important to use the right approach based on the project needs.

Another possible way is by making the working Jack do the trick – Yeah I meant lets go back to Win Forms picture box to do the magic. We know PictureBox seamlessly loaded the animated gifs in Win Form days. Wait a minute did I say lets change the project from WPF to Win Forms? No I didn’t. What I said is lets integrate the PictureBox alone to the WPF project. To use the right word, I should say that we need to host the Windows Forms Control in WPF. To host a Windows Forms Control you need to make use of the class WindowsFormsHost which appears in the System.Windows.Forms.Integration namespace in assembly WindowsFormsIntegration.dll.

Lets get to the code. The first step to do is add a reference to System.Windows.Forms.dll and WindowsFormsIntegration.dll to your WPF based project.

References

Add the following namespaces to your XAML Code.

<Window x:Class="WpfApplication2.Window1"
    xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
    xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

Now you can host the PictureBox inside the WindowsFormsHost and set its Name.

    <Grid>
        <wfi:WindowsFormsHost>
            <winForms:PictureBox x:Name="pictureBoxLoading">
            </winForms:PictureBox>
        </wfi:WindowsFormsHost>
    </Grid>

In your code behind(Window1.xaml.cs), add this code to the Window_Loaded Event:

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.pictureBoxLoading.Image = System.Drawing.Image.FromFile("anim.gif"); ;
        }

Key points before execution:

  1. Make sure you provide the right path to load the image
  2. You can also load it from a resource file.

Since Windows Forms has several interesting built in controls that WPF lacks, using this technique you can make your favorite Windows Forms control work in WPF.

Cheers!

Error: Not enough storage is available to process this command

October 31, 2009 nnish Leave a comment

Today afternoon I was on a mission to complete a long pending personal project and as part of it I was developing a windows service which extended the support of starting and stopping the service from a console window. After the completion it was time for me to start testing that out and then this weird thing happened. Whenever the system encountered a Console.ReadLine(), it gave me a strange error: “Not enough storage is available to process this command.”  But executing a Console.WriteLine() was not an issue. After playing around with it for a while I figured out the project I had selected was Windows Service and hence it’s output type was Windows Application. Changing the project type to a Console application did the trick. Hopefully this helps someone.

Cheers!

Categories: C#, ConsoleApp Tags:

Best blog award and me?

October 25, 2009 nnish 1 comment

This is really amazing. Blogging was one of the activities I thought I was never good at. My last experience at the tech-ed forced me to write one, and this is truly surprising – Won the best blog award for writing down my experiences at the event. I received a Windows Vista Ultimate licensed copy from Vic at Xperience 2009/ Microsoft Community Tech Days event. This is my first blog entry and what a great way to start – It inspires! Thanks to BDotnet and BITPro panel members. 

Thank you VJ(MSIGeek) for scheduling the prize giving session little earlier than it was planned. It will not be good on my part if I do not mention a special thanks to VJ for having this session clicked for me and for Vic’s patience.

BestBlogBdotnet

WindowsVistaUltimate

Cheers!

Custom Configuration Section in C#

September 17, 2009 nnish 1 comment

A very familiar way of implementing the frequently changing value in an application is by storing them in a configuration file’s <appSettings> section. When the project is big, storing too many values in application settings is not a suggested approach, as this can lead to confusions and many other integration problems. Many at times we have seen when the code is moved from a development environment to a production environment there is a mismatch in the the configuration or we loose out on some important values. These issues can be eliminated by simply using a custom configuration section. A project constitutes of many modules and each module will have configuration values specific to them. So it will be a good idea to group them to a single section, and every  module’s configuration values will reside in their respective section. This way by just looking at the configuration one can figure out which value relates to what module. It is also suggested to have a common section so that these values can be accessed by all the modules and will reduce duplication of values.

Going forward you will learn about creating custom configuration section, the corresponding value holder class, and properties to access them through out the application. I will make the demo simple to a console application, so that it is easy to understand.

Start a new Console application and add an application configuration file to it. Also reference System.Configuration.dll.

What’s in the Configuration?

  1. <?xml version=1.0 encoding=utf-8 ?>
  2. <configuration>
  3.     <configSections>
  4.         <section name=MyConfiguration type=ConfigurationC.MyConfiguration, ConfigurationC/>
  5.     </configSections>
  6.     <!– Configuration settings for MyConfiguration Starts –>
  7.     <MyConfiguration
  8.             To=support@nnish.com
  9.             From=sales@nnish.com>
  10.         <Messages>
  11.             <Message Name=Email Value=email/>
  12.             <Message Name=Sms Value=sms/>
  13.             <Message Name=Tweet Value=tweet />
  14.         </Messages>
  15.     </MyConfiguration>
  16.     <!– Configuration settings for MyConfiguration Ends –>
  17. </configuration>

Lets break this into bits and pieces. Notice the <configSections> element –this is where you register your custom configuration. To add a custom configuration – add an element <section name=”” type=””/>.

  • name – represents the name of the custom configuration
  • type – used as <namespace.Type>, <AssemblyName> (Type is the corresponding class which inherits ConfigurationSection)

And the <MyConfiguration>element is nothing but the custom configuration section which contains custom values stored.  I will explain multiple ways of storing in the config files and accessing them from the application. In the config, I store some values as the attribute of the main element, the main element has the sub element <Messages> and that in turn has the collection of <Messages> having attributes “Name” and “Value”. This can be easily related to <add> element in the <appSettings>.

What’s in the Code?

Now let us go ahead and build the classes for accessing these values in the application.

Remember these:

  • There should be a class in the application representing each element (including the sub elements) in the configuration file.
  • Class holding the custom Configuration Section should inherit from CustomSection
    • public class MyConfiguration : ConfigurationSection
  • The attributes/elements can be represented as a property which is of type ConfigurationProperty in the parent class.
  • Class representing an element collection should inherit from ConfigurationElementCollection
    • public class MessageCollection : ConfigurationElementCollection
  • Class representing an element should inherit from ConfigurationElement
    • public class MessageElement : ConfigurationElement

Since <Message> is the last child element, write the corresponding class for it first, and then <Messages> which is its parent and it holds the collection of <Messages> and finally the class for <MyConfiguration> which has attributes represented as properties in itself.

Element: <Message> – Class: MessageElement

  1. using System.Configuration;
  2. namespace ConfigurationC
  3. {
  4.     /// <summary>
  5.     /// Class holds the <Message> element
  6.     /// </summary>
  7.     public class MessageElement : ConfigurationElement
  8.     {
  9.         // Holds the Name attribute of the Message
  10.         private static readonly ConfigurationProperty messageName =
  11.             new ConfigurationProperty(“Name”, typeof(string), string.Empty, ConfigurationPropertyOptions.IsRequired);
  12.         // Holds the Value attribute value of Message.
  13.         private static readonly ConfigurationProperty messageValue =
  14.             new ConfigurationProperty(“Value”, typeof(string), string.Empty, ConfigurationPropertyOptions.IsRequired);
  15.         public MessageElement()
  16.         {
  17.             base.Properties.Add(messageName);
  18.             base.Properties.Add(messageValue);
  19.         }
  20.         /// <summary>
  21.         /// Name
  22.         /// </summary>
  23.         [ConfigurationProperty("Name", IsRequired = true)]
  24.         public string Name
  25.         {
  26.             get { return (string)this[messageName]; }
  27.         }
  28.         /// <summary>
  29.         /// Value
  30.         /// </summary>
  31.         [ConfigurationProperty("Value", IsRequired = true)]
  32.         public string Value
  33.         {
  34.             get { return (string)this[messageValue]; }
  35.         }
  36.     }
  37. }

Explanation:

  • <Message> element has attributes “name” and “value” which are represented as ConfigurationProperty and its initialization takes the following parameters
    • name: The name of the configuration entity.  
    • type: The type of the configuration entity.
    • defaultValue: The default value of the configuration entity.
    • options:  One of the System.Configuration.ConfigurationPropertyOptions enumeration values
  • In the constructor add these properties to the base class Property Collection
  • Expose them as public property

Element: <Messages> – Class: MessageCollection

  1. using System.Configuration;
  2. namespace ConfigurationC
  3. {
  4.     [ConfigurationCollection(typeof(MessageElement), AddItemName = "Message",
  5.          CollectionType = ConfigurationElementCollectionType.BasicMap)]
  6.     public class MessageCollection : ConfigurationElementCollection
  7.     {
  8.         protected override ConfigurationElement CreateNewElement()
  9.         {
  10.             return new MessageElement();
  11.         }
  12.         protected override object GetElementKey(ConfigurationElement element)
  13.         {
  14.             return ((MessageElement)element).Name;
  15.         }
  16.      
  17.         new public MessageElement this[string name]
  18.         {
  19.             get { return (MessageElement)BaseGet(name); }
  20.         }
  21.     }
  22. }

Explanation:

  • MessageCollection class is inherited from the abstract class ConfigurationElementCollection and two of its abstract methods CreateElement() and GetElementKey() needs to be overridden
  • CreateElement() creates the new instance of the MessageElement
  • GetElementKey() Gets the element key for a Message element (we define Name attribute as the key, so that the value can be retrieved using the name)
  • new public MessageElement this[string name] – add this to retrieve the value with the key name. For e.g: ConfigurationManager.AppSettings[“test”];

 

Element: <MyConfiguration> – Class: MyConfiguration (Putting them all together[ConfigurationSection ])

  1. using System.Configuration;
  2. namespace ConfigurationC
  3. {
  4.     public class MyConfiguration : ConfigurationSection
  5.     {
  6.         private static readonly ConfigurationProperty toAttribute =
  7.              new ConfigurationProperty(“To”, typeof(string), string.Empty, ConfigurationPropertyOptions.IsRequired);
  8.         
  9.         private static readonly ConfigurationProperty fromAttribute =
  10.              new ConfigurationProperty(“From”, typeof(string), string.Empty, ConfigurationPropertyOptions.IsRequired);
  11.         private static readonly ConfigurationProperty messagesElement =
  12.              new ConfigurationProperty(“Messages”, typeof(MessageCollection), null, ConfigurationPropertyOptions.IsRequired);
  13.         public MyConfiguration()
  14.         {
  15.             base.Properties.Add(toAttribute);
  16.             base.Properties.Add(fromAttribute);
  17.             base.Properties.Add(messagesElement);
  18.         }
  19.         /// <summary>
  20.         /// To
  21.         /// </summary>
  22.         [ConfigurationProperty("To", IsRequired = true)]
  23.         public string To
  24.         {
  25.             get { return (string)this[toAttribute]; }
  26.         }
  27.         
  28.         /// <summary>
  29.         /// From
  30.         /// </summary>
  31.         [ConfigurationProperty("From", IsRequired = true)]
  32.         public string From
  33.         {
  34.             get { return (string)this[fromAttribute]; }
  35.         }
  36.         /// <summary>
  37.         /// Messages Collection
  38.         /// </summary>
  39.         [ConfigurationProperty("Messages", IsRequired = true)]
  40.         public MessageCollection Messages
  41.         {
  42.             get { return (MessageCollection)this[messagesElement]; }
  43.         }
  44.     }
  45. }

Explanation:

  • Add all the Attributes and Elements as the ConfigurationProperty of corresponding type.

And the Program.cs

  1. using System;
  2. using System.Configuration;
  3. namespace ConfigurationC
  4. {
  5.    public class Program
  6.     {
  7.         public static MyConfiguration MyConfig;
  8.         static void Main(string[] args)
  9.         {
  10.             MyConfig = GetConfiguration();
  11.             Console.WriteLine(“This program comes with no warranty!”);
  12.             Console.WriteLine(“Values found in the configuration”);
  13.             Console.WriteLine(“To: “ + MyConfig.To);
  14.             Console.WriteLine(“From: “ + MyConfig.From);
  15.             Console.WriteLine(“Message Email: “ + MyConfig.Messages["Email"].Value);
  16.             Console.WriteLine(“Message Sme: “ + MyConfig.Messages["Sms"].Value);
  17.             Console.WriteLine(“Message Tweet: “ + MyConfig.Messages["Tweet"].Value);
  18.             Console.ReadLine();
  19.         }
  20.         private static MyConfiguration GetConfiguration()
  21.         {
  22.             return (MyConfiguration)ConfigurationManager.GetSection(“MyConfiguration”);
  23.         }
  24.     }
  25. }

Above code snippet is self explanatory.

I hope I was able to walk you through a step by step process of a developing hello world Custom Configuration section.

Download the code!

Cheers!

Internet Explorer 8 ViewSouce Viewer

July 30, 2009 nnish Leave a comment

When you hit the “View Source” command in IE, it opens in a refreshing viewer. I mentioned viewer because you are not allowed to edit :) .  Previous version used the notepad as an editor. If you still want to use the notepad as the default editor then press F12 to open developer tools Click File-> Customize Internet Explorer View Source –> select – Notepad. And one more thing to be mentioned – Developer tools Fantastic.

IE8ViewSource

Here is the developer tool screenshot:

image

Check out the Menu Items to know what you can do with this handy tool bundled with IE8.

 

Cheers!

Silverlight: What is inside a .xap?

July 24, 2009 nnish Leave a comment

Start a new silverlight application(File->New Project-> Silverlight Application), ensure “Host the Silverlight application in a new website” is checked. Now for time being just build the solution. After the build completion look for a file with.xap extension inside the “ClientBin” folder.
Ever wondered wat iteez? No – then here iteez: .xap is a package file and it is nothing but a compressed form of your silverlight dlls, which will be extracted at the runtime from the browser. So did that mean it is some form of .zip? Yeah – just rename the file’s extension to .zip and you should be able to extract it and see whats inside. Do let me know whats inside. iteezzzz ;)

Cheers!

Categories: Silverlight Tags:

Understanding Dependency Property

July 23, 2009 nnish Leave a comment

Everyone who get introduced to Windows Presentation Foundation(WPF) are familiar with this term. But lot many get confused on it or never get what it is. I will try and make this post very simple so that it is easier to understand. My intentions are not to provide the complete technical stuff behind the Dependency property, but to keep things simple to understand and to get started. You should probably work on this lot many times to understand it better.

If you are not new to .net or any other OOP language, you are not new to Property. Dependency property was introduced in .net 3.0 and it is all together new implementation of normal properties. Dependency property differ in terms of its storage mechanism, it uses Sparse Storage and its implementation saves per-instance memory compared to a typical .NET property. However benefits of dependency property is more than just storage. One of the significances of Dependency property is its support for notification change – that means any change in the value of the property is notified down the element tree in WPF. This point particularly becomes very important to understand this.

Before I completely get on with Dependency property, let me give a gist of what attached property is. Let me explain this in a way a lay man understands: Consider a “<Canvas></Canvas>” element in your XAML. Now if you want to add a child element “<TextBlock>” to it, how do you place them in the canvas? – Here it is:

<Canvas>
       <TextBlock Canvas.Top=”100″ Canvas.Left=”100″ Text=”Hello World”/>
</Canvas>

OR an example with a Grid

<Grid>
   <Grid.ColumnDefinitions>
      <ColumnDefinition/>
      <ColumnDefinition/>
   </Grid.ColumnDefinitions>
   <Grid.RowDefinitions>
      
<RowDefinition/>
      
<RowDefinition/>
   </Grid.RowDefinitions>
  
<TextBlock Grid.Column=”0″ Grid.Row=”0″ Text=”Hello World  1″/>
  
<TextBlock Grid.Column=”1″ Grid.Row=”0″ Text=”Hello World 2″/>
  
<TextBlock Grid.Column=”0″ Grid.Row=”1″ Text=”Hello World 3″/>
  
<TextBlock Grid.Column=”1″ Grid.Row=”1″ Text=”Hello World 4″/> 
 
</Grid>

So what we do is we set the Canvas’s Top and Left property in the TextBlock child element or even the Grid’s Column and Row property in the child elements. This is achieved using attached property.

So here is the MSDN explanation: “An attached property is intended to be used as a type of global property that is settable on any object. One purpose of an attached property is to allow different child elements to specify unique values for a property that is actually defined in a parent element.”

In the above example, we see the property element of a parent is changed by the child, and the same gets reflected throughout the child elements. I have explained this so that you don’t confuse attached property with dependency property.

Let us extend couple of lines of code more and now understand dependency property.

And here it is:

<Canvas>
<Slider Canvas.Top=”10″ Canvas.Left=”10″ Name=”MySlider” Minimum=”10″ Maximum=”1000″ Ticks=”100″ Width=”300″/>
 <Ellipse Canvas.Top=”130″ Canvas.Left=”150″ Width=”{Binding ElementName=MySlider, Path=Value}” Height=”{Binding ElementName=MySlider, Path=Value}” Fill=”Red”/>
 </Canvas>

The output of the above example is: When the slider is moved, automatically the ellipse gets larger or smaller based on the value of the slider. So what we understand from this is without writing event handlers or any code behind to handle the slider movement and the ellipse height and width setters – we achieve this. This is because the property “Value” of the slider is a dependency property and it notifies the change to all the elements in the XAML, and since the Ellipse’s width and height are bound to the “Slider.Value” it automatically reflects the change.

This was just an introduction, there are couple of more things I want to cover like – creating your own dependency properties for the custom controls etc, which will be updated in the next post.

Cheers!

Silverlight for the Newbie!

July 21, 2009 nnish Leave a comment

It is been really long I have worked on Web development – close to 2 years and I really miss every bit of it. I have moved on to a world where it is just business logic. Though this is more challenging – as it involves developing performance efficient and highly object oriented codes, I still miss the art of developing rich User Experience(UX).  Words “Ajax”,”Silverlight” and few others revolve around me every night, as I take lot of time reading about them and mostly few minutes before my nap. And hence I started to explore myself. Since I had worked on Asp.net Ajax and WPF before, it was not that difficult for me to understand. The intention of this post is to help the newbie get started with the Microsoft’s Magic Web Wand called Silverlight – “Light up the Web!”.

What is Silverlight?

When the internet was born, it was primarily used for sharing static content over the network with the help of a simple web browser. But things have changed over a period of time. Internet moved on from static content –to- dynamic content –to- rich user experience. Let it be shopping online, social networking, banking or any other web activities, user demands a rich Experience. And thus the Silverlight. Silverlight is a client runtime which provides rich user experience. It runs on user’s browser with limited capabilities on the user’s system resources. It is a free downloadable one time installer. It supports all the latest browsers like IE, Mozilla, Safari etc on Windows, Mac, and Linux platforms.

Let us tackle couple of questions to understand better:

  1. Why Silverlight?
    Think about developing a website for a multimedia company/ad-agency where you need to show a gist of their actual work, do you think their clients at their web page expect to see some static content and get impressed of their work? Of course no, they want to see things more lively. Now think of developing a dynamic web page, which should create less load on the server, perform better on the client, show animations, stream videos, etc. I am sure this is not an impossible task, with Javascript and any server side code this is very much possible. But think of the time it takes to develop one. One more important thing which comes to your mind the moment you think about Javascript is browser and platform compatibility. Think of writing “If-else” statements over and again. Silverlight solves all these problems. You don’t have to worry about the client platform or the browser, you don’t have to think of including different players for the video streaming, and most importantly you don’t need to know javascript. All you need to know is simple C# and XAML and you are good to light up the web.
  2. How is it different from Ajax?
    Imagine the lines of code you need to write in Ajax to make an animation, stream media, etc. Since Silverlight uses WPF’s Subset UI programming, you can use the markup language XAML to do things for you. At user point of view Silverlight only differs from the point of execution – Silverlight uses the runtime to execute whereas a Ajax executes inside the web browser. Both the technologies are given equal prominence by Microsoft. With all of these technologies in place we are closely bridging the gap between a web application and a stand alone desktop application.
  3. Why should one not use Flash instead of Silverlight?
    The answer is pretty simple – Do you want to learn flash, or depend on a flash programmer to finish your application? Or simply add few more lines of code in XAML and C# – you may land up doing things better than a designer.

Versions of Silverlight(Release):

  • Silverlight 1.0
  • Silverlight 2.0
  • Silverlight 3.0

Prerequisites for development:

  1. Make sure you have .net 3.5 SP1 and above
  2. If you are using Visual Studio 2008 (any edition) – make sure you have VS 2008 SP1 installed.
  3. Install the Visual Studio tools for  Microsoft Silverlight 3 and SDK

In this post I have limited to the introduction in simple terms.

More posts to come on Silverlight architecture, CLR usage, WPF Subset UI usage etc.

Cheers!

Categories: Silverlight Tags:

XMLPreprocess Getting Started

July 19, 2009 nnish Leave a comment

XMLPreprocess is a simple command line utility that can be used to deploy config files to multiple environments without having to maintain multiple copies. It can be used as a custom action in your MSI to transform the files as they are being deployed to different environments.

The goal of this tool was to minimize the maintenance of multiple configuration files for deployment and I should say it neatly meets the goal.  To understand it better – a single config file can be written and maintained as the source of truth, and it can be decorated with non-breaking comments that contain the instructions for the preprocessor.

Example:

<configuration>
<system.web>
 <!-- ifdef ${production} -->
 <!-- <compilation defaultLanguage="c#" debug="false"/> -->
 <!-- else -->
 <compilation defaultLanguage="c#" debug="true"/>
 <!-- endif -->
 </system.web>
</configuration>

Look carefully at the comments part of the above snippet. You can easily understand that we are trying to turn off the debug page compilation when in production. 

Now that is about the introduction, moving on to the actuals:

First thing first: Download the XMLPreproces from CodePlex, and extract the zip.

For this example, I will be using the spreadsheet(XML Spreadsheet 2003) as the storage of the environment specific variables. However you can also store it in a normal xml file.

I am using the sample files which came along with the download. I copied the sample.config and the SettingsSpreadSheet.xml into my xmpreprocess bin folder – I just did this to make the demo simpler – You can always provide the path for processing.

My folder looks like:

xmlprep1

Open the SettingsSpreadsheet.xml

xmlprep3

The columns represent the different environments you are targeting, and the values in the rows of Column A are the variables you will use in the config file. While preprocessing, the values of the variables are replaced with the corresponding value stored in the environment column.

For e.g. Let us say I want to generate a config file for testing environment, then I store the variable ServiceLocation in the column A, and then I provide the corresponding value in the column of “Test” – now when preprocessed “${ServiceLocation}” in the config file will be replaced with the corresponding value in the xml file.

Open the sample.config file;

xmlprep2

Look at the value in the comments section “${ServiceLocation}” – as mentioned above you should add this to the variable in the settings files – just add “ServiceLocation” (dollar and braces are not required in the settings file), and provide different values for different environments.

Now use this command to preprocess:

“XmlPreprocess.exe /v /q /nologo /i sample.config /x SettingsSpreadsheet.xml /e Test /o Processed.config /d test ”

Once you run the above command, it generates another config file named Processed.config and you will have the value ”testserver” instead of localhost, in the new config file.

Now think of adding this to your WIX setup, or calling the bat file with the preprocessing info as part of build scripts. This will reduce the work of maintaining different config files for different environments.

This tool is really simple to understand, and when used efficiently gets rid of maintenance problems.

Few other resources which may help:

Loren’s Blog

Scott Hanselman’s Blog

Cheers!

Categories: Deployment, XMLPreprocess