Archive for the ‘Development’ Category.

Russian Government going Open Source…and the future

Well, I have seen governments claim they are going to open source before, but not from Russia, and not with such a realistic plan to migrate over a few years.

Here is a link to the article via Google translate:

Putin ordered the transfer of power on Linux

The now

Business drives software development.  Open Source communities help, but even today much of the ongoing development for Linux is driven by businesses such as Red Hat and Novell and others.  If you think your Linux code is being written by unpaid developers in their spare time, you are somewhat correct but only partially.  Most changes are made by developers who are paid.

While communities are nice, they can’t match the hours or output of experienced developers working forty to sixty hours a week.

Looking Ahead…the Apps…and C# (Mono)

The more open source is used in business, the more development power it will have.  But it is not the open source Operatings Systems that prevent people from moving to Linux or BSD.  Ubuntu, SUSE, Fedora, CentOS, PC-BSD, and numerous others are all very usable desktops that are user friendly.  It is the software that runs on them that everyone is waiting for.

The market is already there to make millions extra if you application runs cross platform, one Windows, MAC, Linux, and BSD.

But most the applications written for Windows, the business desktop of today, are using .NET Framework. So naturally those companies are going to want to make their code cross platform.  And they are going to find it is easier than they thought to move their applications between platforms using C#.  I have recently decided that C# is the future of applications on all platforms.

Some MAC and Linux users don’t like Microsoft and will fight off the idea of a Microsoft provided development platform such as C# (Mono) on their systems.  But when a corporation decides that you must run software X, and software X requires .NET, and you have to either give up your MAC or Linux box for a Windows box, or use C# (Mono), then users will come around.

If you are a company writing software for Windows only today and using C#, you need to take a look at Mono. Even if the return on investment of developing a C# (Mono) based version of your product is a slight loss to break even, it is an investment in the future.  Once written, maintenance costs will be less than the original development costs and that slight loss to break even margin will turn to a small profit.  And with the experience, you next app will migrate to C# (Mono) that much easier and soon, all you apps will run anywhere that C# (Mono) can run.

This is going to take off in a way Java hasn’t because developers for windows prefer and will continue to prefer .NET over Java.  And when it comes to business apps, Java just isn’t the language of choice.  Business applications are written in C#.

Quote’s and brackets (” < >) in code snippets are a little messed up on my site

Hey all,

It has come to my attention that all the quote’s and brackets (” < >) in code snippets are a little messed up on my site.

I am fixing it.

For now, just use your favorite text editor and do a replace all:

< should be < > should be >
” should be ”

I will try to get this fixed.

Update:
I think I have this fixed. However, I think I am in a state where if I edit and update a document, it breaks the code. This is a problem for me that I need to find a solution for.

VMWare, RDP (MSTSC), WPF, and DisableHWAcceleration

I don’t know if you, like me, have a development box running Visual Studio 2010 and VMWare workstation. I develop in C# and WPF, and test the product in a VM. Then sometimes, when I work from home, I remote desktop into my development box.

When I am using RDP to remote control a VMWare Workstation host, and I run a WPF Application inside a VM, the WPF application doesn’t display. The window opens, and you see the frame of your windows, but the inside is just blank or a white/gray box. None of the WPF Controls are visible.

I have found two ways to fix this. One is permanent and one is temporary.

Option 1 – (Permanent) Set this registry key. Read more about this here on MSDN: Graphics Rendering Registry Settings

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Avalon.Graphics]
"DisableHWAcceleration"=dword:00000001

Option 2 – (Temporary) Or just reboot the VM while connected to the VMWare Workstation host via RDP. It seems that the VM boots and the OS detects the lack of support and disabled hardware acceleration. However, once you reboot when you are not RDP’ed into the VMWare Workstation host, you have hardware acceleration back.

I took me a long time to figure this out, because there was little to nothing in a Google search. I came across this solution while looking for something else a month or so ago, and needed to use it again when working from home last night. I thought I would post it so I never have to look for it again.

Using CSS to make an html numbered list have text before the number

I often use lists that look as follows:

  • Is in the format of Step #
  • Doesn’t indent.

It is a little more complex than it needs to be to do this in HTML but still doable.  The below list is an example.

  1. The first thing to do.
  2. The second thing to do.
  3. The third thing to do.

So how is it done? Well, it is done with CSS.

  1. Add your CSS
    ol.Steps {
    	counter-reset: section; // Make sure each new list starts at 1.
    	list-style-type: none;     // Removes the standard numbers.
    	padding: 0;                   // Removes padding so there is no indent.
    	margin-left: 0;               // Removes margin so there is no indent.
    }
    
    ol.Steps li:before {
         counter-increment: section;                  // Defines the counter increment to use.
         content: "Step " counter(section) " - ";  // Adds content before your content.
    }
    
  2. Add your html
    <ol class="Steps">
    	<li>The first thing to do.</li>
    	<li>The second thing to do.</li>
    	<li>The third thing to do.</li>
    </ol>
    

Easy enough.

This is also good when you need any word in front of the number such as: Chapter, Section, Item, etc…

Checking for html errors in your website or blog

So in doing a new web site or blog site, an error can be problematic.  One browser might ignore it, but another can completely be messed up.

You may open your website in Firefox and everything looks fine.  But then you check Chrome, IE, Opera, Safari, and in one or more of them your website looks completed messed up.

How to find html errors in your site

Well, this is where http://validator.w3.org comes in.  This web site will “browse” your website for you and parse the html in your website and report back errors.

  1. Go to http://validator.w3.org.
  2. Enter your URL in the Address text field.
  3. Click Check.

If you have errors they will be displayed, as well as the line number in your html source where the error occurs.

If you don’t have errors you will get a “Congratulations” and also be provided with some code to put on your site to say that your site is checked and “valid”.

Valid XHTML 1.0 Transitional

Being Thorough

For a static website, this is easy.  Check your pages once and since they rarely change, you are good for a long time.

For a blog, this is more complex. To be thorough you would have to check every post. Or only check a post if it is a problem.

Understanding Conditions in Custom Actions and InstallExecuteSequence

If you have ever had to deal with Custom Actions and their Conditions in InstallExecuteSequence, you can get frustrated really quickly. This is not intuitive, though not hard to learn. It definitely is one area that Microsoft could have designed much better, but it is what it is.

The first problem with the design is that it is hard to just read a little bit, and understand. So take a moment and read this all, so you can understand it all.

What is a Feature? What is a Component?

A Feature is a usually a group of Components. The Feature is a part of a product you want to install, at a high level. A Component is a list of install tasks to implement a feature.

Lets look at a use case using a Client/Server application.

Think of an application that has a Server piece, a GUI to manage the server, and a client piece.  When you install, the MSI gives you a check box with those three items and you can install any of the three, or all three on the same machine.  You have three Features.

Feature_1_Server
Feature_2_User_Interface
Feature_3_Client

A Component is a lower lever.  A feature is a list of Components.  So Feature_1_Server might install a list of files and a web service.

C:\Program Files\MyApp\Server\Server.exe
C:\Program Files\MyApp\Common\Common.dll
C:\inetpub\wwwroot\MyApp\Server\WebService.asmx

A Component can only add files to a single path. So because we have two directories above, there will be at least three Components. But we also need to create the web service, so this one Feature has four Components.

Component_1_Server_Files
Component_2_Common_Files
Component_3_WebService_Files
Component_4_WebService

Now if you install Feature_2_User_Interface, you get these files:

C:\Program Files\MyApp\UI\Server.exe
C:\Program Files\MyApp\Common\Common.dll

Notice that the same files in Common are included.  You don’t need to create a new Component for that.

Component_2_Common
Component_5_User_Interface

Install the Feature_3_Client and you see it is similar in the files it installs.

C:\Program Files\MyApp\Client\Client.exe
C:\Program Files\MyApp\Common\Common.dll

Notice that the same files in Common are included.  You don’t need to create a new Component for that.

Component_2_Common
Component_6_Client

Ok, so you have three features, and six components.

What are Conditions?

A Condition is a boolean expression added to a Custom Action to make sure it only runs if the expression returns true.

Imagine you are installing software that has a Server and a Client Feature.  You have a Custom Action that should run for the Server but not for the client.  It needs a condition that follows the logic in the following sentence.

If I am installing the Server Feature, run this action, otherwise, don’t run this action.

Unfortunately MSI doesn’t speak English so while the above sentence helps you understand what needs to be done, the Condition syntax is quite different.

Condition Expression Syntax

The expression is usually in this syntax:

[$|?|&|!][Component|Feature] [bool operator] [-1|1|2|3|4]

Example: If I am installing the Server Feature, run this action, otherwise, don’t run this action.

&Feature_1_Server = 3

Wow, I bet that unless you have some serious experience with MSI Conditions, you are looking at that syntax and shaking your head in confusion. I must admit that I would never have designed this the way it is and I consider it poor design, but again, it is what it is and if we are going to use MSIs, we need to learn this.

Lets break this out into four understandable parts.

  1. [Feature/Component Operator]
  2. [Feature/Component Id]
  3. [Boolean Operator]
  4. [Integer representation of a State]

Let’s cover the four different parts of this syntax.

What is the Feature/Component Operator?

There are only four Feature/Component Operators, all show in the table below.  There are a pair of operators for Features and a pair of operators for Component. So while there are four operators, only three things are determined.

  1. Is this is a Feature of a Component
  2. What is the current *State of the Component or Feature.
  3. What will be the new *State of the Component of Feature when the install completes.

* State is discussed later as it is the fourth item in the Condition syntax but very quickly, State can basically be understood as installed or not installed.

Operator Type State or Action Description Where this syntax is valid How is this commonly used?
$ Component Component – Gets the action that will occur. This is used in front of a Component to get the State change that will occur to the component. Returns a the new State. In the Condition table, and in the sequence tables, after the CostFinalize action. Use this to see if a Component will be installed or uninstalled.
? Component Component – Gets the current state. This is used in front of a Component to get the current state of that Component. Returns the current State. In the Condition table, and in the sequence tables, after the CostFinalize action. Use this to see if a Component is already installed or has not been installed (absent) or was uninstalled (absent).
& Feature Feature – Gets the action that will occur. This is used in front of a Feature to get the State change that will occur to the Feature. Returns a the new State. In the Condition table, and in the sequence tables, after the CostFinalize action. Use this to see if a Feature will be installed or uninstalled.
! Feature Feature – Gets the current state. This is used in front of a feature to get the current State of that feature. Returns the current State. In the Condition table, and in the sequence tables, after the CostFinalize action. Use this to see if a Feature is already installed or has not been installed (absent) or was uninstalled (absent).

$ and & are doing the same task, only for $ is for Components and & is for Features.  These operators are used before a Feature/Component Id to determine the new State, or more clearly, is this Feature/Component going to be installed or uninstalled.

? and ! also do the same task, again the difference is that ? is for Components and ! is for Features.  These operators are used before a Feature/Component Id to determine the current State, or more clearly, is this Feature/Component already installed or not installed.

What is the Feature/Component ID?

The Feature or Component Id is a unique string. In WIX, you create the Features and Components, so you should easily know the ID.  I like to use understandable Feature/Component names, such as Feature_1_Server and Feature_3_Client or Component_1_Server_Files and Component_6_Client_Files.

What is the Boolean Operator?

The boolean operator is any operator that when used in an expression leads to returning true or false. There are quite a few boolean operators that can be used.

  • Comparative Operators
  • Substring Operators
  • Bitwise Numeric Operators

Comparative Operators

There are the basic boolean operators that all languages have.  One difference is that in most languages, = is an assignment operator and == is comparison, but since there is no assignment like that when dealing with Features/Components and States, the = is the comparison operator and == is never used.

Operator Return Value
= Returns TRUE if values on both sides are equals.
<> Returns TRUE if the value on the left side is not equal to the value on the right side.
> Returns TRUE if the value on the left side is greater than the value on the right side.
>= Returns TRUE if the value on the left side is greater than or equal to the value on the right side value.
< Returns TRUE if the value on the left side is less than the value on the right side.
<= Returns TRUE if the value on the left side is less than or equal to the value on the right side.

Substring Operators

Operator Meaning
>< TRUE if left string contains the right string.
<< TRUE if left string starts with the right string.
>> TRUE if left string ends with the right string.

Bitwise Numeric Operators

Operator Meaning
>< Bitwise AND, TRUE if the left and right integers have any bits in common.
<< True if the high 16-bits of the left integer are equal to the right integer.
>> True if the low 16-bits of the left integer are equal to the right integer.

Any of the above operators can be used.

What is a State?

Basically you can think of State was an integer represented Installed or Not Installed.  There are actually five options but the often only two are used:

  • INSTALLSTATE_ABSENT (2) – Means it is Not Installed.
  • and INSTALLSTATE_LOCAL (3) – Means it is Installed.
States Value Meaning
INSTALLSTATE_UNKNOWN -1 No action to be taken on the feature or component.
INSTALLSTATE_ADVERTISED 1 Advertised feature. This state is not available for components.
INSTALLSTATE_ABSENT 2 Feature or component is not present. It either has never been installed, or if it was once installed it has been uninstalled.
INSTALLSTATE_LOCAL 3 Feature or component on the local computer. This feature or component is currently installed on the local computer.
INSTALLSTATE_SOURCE 4 Feature or component run from the source. This feature or component is installed, but files are not local, but on the source. So running this feature may require a mapped drive to the original installation source.

Examples

So now that we understand the parts, lets put it all together with these Examples.

Condition Definition How is this commonly used?
!MyFeature = 2 If MyFeature is not there (Absent) Use this to check if a Feature is not currently installed. It may have never been installed, or it may have been once installed but is now uninstalled. Both never installed and uninstalled result in the term Absent.
!MyFeature = 3 If MyFeature is currently installed Use this on uninstall or upgrade or repair to see if a Feature is already installed.
&MyFeature = 2 If MyFeature is to not be installed (remain absent) Use this to check if a Component is not currently installed. It may have never been installed, or it may have been once installed but is now uninstalled. Both never installed and uninstalled result in the term Absent.
&MyFeature = 3 If MyFeature is to be installed Use this on uninstall or upgrade or repair to see if a Component is already installed.

Component examples would be similar to these Feature examples.

Now that you are this far.  Guess what.  You can combine these two Conditions. Maybe I will post about combining conditions later.

Resources

http://msdn.microsoft.com/en-us/library/aa368012%28v=VS.85%29.aspx

My Blog has moved to a hosted solution with Gigabit Networks

Hey all,

This blog is currently a simple wordpress blog hosted on WordPress.com. It will shortly change to a new website hosted at Gigabit Networks.

One of my goals is to move to a completely BSD or similar licensed solution. I have chosen to have my final site use FreeBSD (OS), Apache (Web Server), Postgresql (DB), Silverstripe (CMS and blog). This will take me a long time.

Step 1 (Complete) – Move my current wordpress blog to a hosted solution that uses FreeBSD. With my blog moving to Gigabit Networks, this step is complete.

Step 2 (Just starting) – Migrate the blog to Silverstripe and postgresql is already in progress, but I expect it will take a year (as I do this in my spare time).

A couple of things to note:

  1. This will come with a new design for my website, so don’t be surprised when you see it. Hopefully it will be a better look.
  2. A couple changes are that my posts will no longer dumped to the home page, but to a Posts page.
  3. Subscribers will have to subscribe again as I will use email subscription “Delivered by FeedBurner.”
    Subscribe to Rhyous by Email

Hopefully this is a smooth transition. If you have any questions, please comment on this post.

C# (Mono) on FreeBSD

Well, if you have read my blog at all, you will realize that I have a developer job writing in C# on Windows, but it is my personal hobby to use FreeBSD.

I am very excited about Mono. I love the C# language. I also love FreeBSD.

I am going to go ahead and say something bold. Few people now realize this yet, but the ability to code in C# on open source platforms is going to be the single most important feature in the coming years. It will eventually be a standard library that will exist or be one of the first items installed on every system.

For more information:

http://www.mono-project.com/Mono:FreeBSD
Packaging for Mono and related applications on FreeBSD (http://www.freebsd.org) is handled by the BSD# Project. The purpose of this project is to maintain the existing Mono/C# ports in the FreeBSD ports tree, port new applications, and work on resolving FreeBSD specific issues with Mono. BSD# is entirely user supported and is not an official FreeBSD or Mono project.

For Licensing information:

http://www.mono-project.com/Licensing

Installing Mono

Mono is a port and as always a port is easy to install on FreeBSD.

Note: The version of mono in ports is not necessarily the latest and greated. I recommend that you install the latest version of mono. See this article.
Installing the latest version of Mono on FreeBSD or How to install and use portshaker?

#
#
cd /usr/ports/lang/mono
make BATCH=yes install

Compiling Hello World in Mono

The mono compiler is gmcs. It is simple to compile C# code.

  1. Create a new file called hw.cs. C# class files end in .cs.
  2. Add this text to the file:
    using System;
    
    namespace HelloWorld
    {
         class HelloWorld
        {
            static void Main(string[] args)
            {
                System.Console.WriteLine("Hello World");
            }
        }
    }
    
  3. Save the file.
  4. Compile the code to create an hw.exe program.
    # gmcs hw.cs

Running a Mono Program

Mono programs must be run using the “mono” command.

# mono hw.exe
Hello World

A Mono IDE: MonoDevelop

There is an IDE for Mono called MonoDevelop. MonoDevelop is a port and as always a port is easy to install on FreeBSD.

#
#
cd /usr/ports/devel/monodevelop
make BATCH=yes install

The Mono Develop port integrated with KDE to add itself to the KDE menu under Applications | Development | MonoDevelop. So you can run it from there.

This IDE allows you to create C# solutions. It is possible to run compile them on FreeBSD and run them on Windows, or compile them on Windows and run them on FreeBSD.

Is It Really Cross Platform

C# and Mono are supposed to be cross platform. So I can write it in Windows using Visual Studio or I can write in FreeBSD using Mono Develop and either way it should run on both Windows and FreeBSD and any other platform that supports mono.

So here are the results of my quick tests:

Test 1 – Does the Hello World app run in Windows.

Yes. I copied the file to a Windows 7 64 bit box and ran it. It worked.

Test 2 – Does a GTK# 2.0 Project run in Windows

No. I created a GTK# 2.0 project on FreeBSD in Mono Develop, and didn’t add anything to it, I just compiled it. I copied the file to windows and ran it. However, it crashed.

Supposedly you have to install the GTK# for .NET on the windows box, but it still didn’t work.

Test 3 – Does a Windows Form Application compiled in Visual Studio 2010 in Window 7 run on FreeBSD

Not at first. I created a basic Windows Form application, and didn’t add anything to it, I just compiled it. I copied it to FreeBSD and ran it. It crashed. However, by default .NET 4.0 is used.

Yes, if compiled with .NET 3.5 or earlier. I changed the project to use .NET 3.5 and tried again. It ran flawlessly.

Test 4 – Does a Windows Presentation Foundation project compiled in Visual Studio 2010 in Window 7 run on FreeBSD

No. There is PresentationFramework assembly so the application crashes immediately. I tried multiple .NET versions.

Note: I didn’t really test much more than the basics. I just created new projects, left them as is and tried them. It would be interesting to see a more fully developed application tested and working on both platform and to know what issues were encountered in doing this.

No WPF

Unfortunately there is no WPF and no plans for it. Of course, WPF stand for Windows Presentation Foundation, and so the who “Windows” part of that might need to be changed to something like XPF, Xorg Presentation foundation.

However since there is Moonlight, which is to Silverlight as Mono is to C# and .NET, and Silverlight is a subset of WPF, I have to assume that WPF will arrive in mono eventually, even if it is by way of Moonlight first.

WPF databinding to methods encapsulated in an ICommand

Databinding in WPF allows binding the Command property to methods encapulated in an ICommand. By creating an ICommand object to hold an event function, the Command value can bind to the event function as an ICommand.

The goal of Model-View-ViewModel is to have zero code in the code behind of a WPF Control Instead, everything the WPF Control does happens using databinding.

While this article will show you how to do this, you be left a little fuzzy as to understanding of the implementation. It may take some time and research to fully understand everything this is doing. Understand that methods can be objects, and this is a process to turn a method object into an ICommand so it can be using in WPF for databinding.

Preparation and Prereqs

You should have Visual Studio 2008/2010.

In Visual Studio, create a new WPF Application project and give it a name.

Step 1 – Creating an new class that inherits from ICommand

  1. In your new project in Visual Studio, add a new class called RelayCommand.
    Note: It can be named anything, but since that is the name used by Microsoft when discussing MVVM, I will use the same name.
  2. Change the using statements to implement the following : System, System.Diagnostic, System.Windows.Input
  3. Make the new RelayComand class public.
  4. Make the new RelayCommand class implement ICommand.
    using System;
    using System.Windows.Input;
    
    namespace WpfDataBindingToICommand
    {
        public class RelayCommand : ICommand
        {
            #region Constructors
            public RelayCommand()
            {
            }
            #endregion
        }
    }
    
  5. Right-click on the ICommand text and choose Implement Interface | Implement Interface. This adds the following code to the bottom of your class.
            #region ICommand Members
    
            public bool CanExecute(object parameter)
            {
                throw new NotImplementedException();
            }
    
            public event EventHandler CanExecuteChanged;
    
            public void Execute(object parameter)
            {
                throw new NotImplementedException();
            }
    
            #endregion
    
  6. Create two member variables or fields that we will use to hep use inside the ICommand interface functions.
    1. Action
    2. Predicate

            #region Member Variables
            readonly Action<object> _ActionToExecute;
            readonly Predicate<object> __ActionCanExecute;
            #endregion
    
  7. Implement the CanExecute(object parameter) function.
            public bool CanExecute(object parameter)
            {
                return __ActionCanExecute== null ? true : __ActionCanExecute(parameter);
            }
    
  8. Implement the EventHandler CanExecuteChanged. In doing this the MVVM experts used the CommandManager, which might be worth reading about.
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
  9. Implement the Execute(object parameter) function.
            public void Execute(object parameter)
            {
                _ActionToExecute(parameter);
            }
    
  10. Create constructors that allow us to initialize the object by passing in the Action

The final class looks as follows:

using System;
using System.Windows.Input;

namespace WpfDataBindingToICommand
{
    /// <summary>
    /// This RelayCommand object is used to encapsulate function logic into an oject that inherits ICommand.
    /// </summary>
    public class RelayCommand : ICommand
    {
        #region Member Variables
        readonly Action<object> _ActionToExecute;
        readonly Predicate<object> _ActionCanExecute;
        #endregion

        #region Constructors
        /// <summary>
        /// This creates a new RelayCommand.
        /// </summary>
        /// <param name="inActionToExecute">This is the logic of the actin to execute. This objects is usually a method that returns void.</param>
        public RelayCommand(Action<object> inActionToExecute)
            : this(inActionToExecute, null)
        {
        }

        /// <summary>
        /// This creates a new RelayCommand.
        /// </summary>
        /// <param name="inActionToExecute">This is the logic of the actin to execute. This objects is usually a method that returns void.</param>
        /// <param name="inActionCanExecute">This is the logic for whether the action can execute.</param>
        public RelayCommand(Action<object> inActionToExecute, Predicate<Object> inActionCanExecute)
        {
            if (inActionToExecute == null)
                throw new ArgumentNullException("execute");

            _ActionToExecute = inActionToExecute;
            _ActionCanExecute = inActionCanExecute;
        }
        #endregion

        #region ICommand Members
        public bool CanExecute(object parameter)
        {
            return _ActionCanExecute == null ? true : _ActionCanExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _ActionToExecute(parameter);
        }
        #endregion
    }
}

Step 2 – Creating a ViewModelBase abstract base class

This object is used to create common logic for all objects that will be using in Binding. This object will implement INotifyPropertyChanged so it only has to be implemented once.

  1. Create a new class named ViewModelBase.
  2. Change the using statements to implement the following : System, System.CompenentModel
  3. Make the new ViewModelBase class public and abstract.
  4. Make the new ViewModelBase class implement INotifyPropertyChanged.
  5. Make the constructor protected.
    
    
  6. Right-click on the INotifyPropertyChanged text and choose Implement Interface | Implement Interface. This adds the following code to the bottom of your class. Yes, it is just a one line event handler object.
            #region INotifyPropertyChanged Members
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            #endregion
    
  7. Create a function called NotifyPropertyChanged to help implement the object. Make sure it has a permission level of at least protected.
            #region Functions
            protected void NotifyPropertyChanged(String inPropertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(inPropertyName));
                }
            }
            #endregion
    
  8. Make the new ViewModelBase class public and abstract.

The final object looks as follows:

using System;
using System.ComponentModel;

namespace WpfDataBindingToICommand
{
    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        #region Constructors
        public ViewModelBase()
        {
        }
        #endregion

        #region Functions
        protected void NotifyPropertyChanged(String inPropertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(inPropertyName));
            }
        }
        #endregion

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }
}

Note: You may also want to implement IDisposable.

Step 3 – Creating the ViewModel and Model

We are going to have the ViewModel and business in the same object for this example, but sometimes you will have a separate ViewModel object that represents your data/business.

  1. Create a new class named SampleViewModel.
  2. Change the using statements to implement the following : System, System.Windows, System.Windows.Input
  3. Make the new SampleViewModel class public.
  4. Make the new SampleViewModel class inherit ViewModelBase.
    using System;
    using System.Windows;
    using System.Windows.Input;
    
    namespace WpfDataBindingToICommand
    {
        public class SampleViewModel : ViewModelBase
        {
            #region Constructors
            public SampleViewModel()
            {
            }
            #endregion
        }
    }
    
  5. Create a string field and property and make sure to have the property’s set function call NotifyPropertyChanged.
        public class SampleViewModel : ViewModelBase
        {
            string _Message = "Hello. This is the default message.";
    
            public string Message
            {
                get { return _Message; }
                set
                {
                    _Message = value;
                    NotifyPropertyChanged("Message");
                }
            }
        }
    
  6. Create a simple function to show a MessageBox.
            public void ShowMessage(String inMessage)
            {
                MessageBox.Show(inMessage);
            }
    
  7. Create an ICommand field and property. Make sure the property returns a RelayCommand object that references the ShowMessage method. This is a read only property.
            RelayCommand _ShowMessageCommand;
    
            public ICommand ShowMessageCommand
            {
                get
                {
                    if (_ShowMessageCommand == null)
                    {
                        _ShowMessageCommand = new RelayCommand(param => this.ShowMessage(Message));
                    }
                    return _ShowMessageCommand;
                }
            }
    

    Note: Notice that in order to pass the ShowMessage method, instead of the return value of the function, into the RelayCommand objectwhich is void anyway, the param => syntax is used.

The final SampleViewModel looks as follows.

using System;
using System.Windows;
using System.Windows.Input;

namespace WpfDataBindingToICommand
{
    public class SampleViewModel : ViewModelBase
    {
        #region Member Variables
        string _Message = "Hello. This is the default message.";
        RelayCommand _ShowMessageCommand;
        #endregion

        #region Constructors
        public SampleViewModel()
        {
        }
        #endregion

        #region Properties
        public string Message
        {
            get { return _Message; }
            set
            {
                _Message = value;
                NotifyPropertyChanged("Message");
            }
        }

        public ICommand ShowMessageCommand
        {
            get
            {
                if (_ShowMessageCommand == null)
                {
                    _ShowMessageCommand = new RelayCommand(param => this.ShowMessage(Message));
                }
                return _ShowMessageCommand;
            }
        }
        #endregion

        #region Functions
        public void ShowMessage(String inMessage)
        {
            MessageBox.Show(inMessage);
        }
        #endregion

        #region Enums
        #endregion
    }
}

Step 4 – Using Databinding to Bind an ICommand to a WPF Control

Ok, so lets modify the XAML of the default MainWindow.xaml code that was auto-created with the project. We will keep it simple and have a text box and a button to pop up the message.

Note: For this simple program all the work we did to implement databinding for binding events to methods seems like an absurd burden. However, for large applications, this design will lead to a better way to manage your code. It will decouple your GUI from your code, making future refactoring of the GUI much easier. This also improves the ability to make minor changes to the GUI. It also makes the code more sustainable and more easily tested. Unit tests are more effective as the GUI layer is not required and most functions are in the business layer.

  1. Create a reference to the current namespace.
    <Window x:Class="WpfDataBindingToICommand.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfDataBindingToICommand"
            Title="MainWindow" Height="350" Width="525">
    
  2. Add a SampleViewModel StaticResource.
        <Window.Resources>
            <local:SampleViewModel x:Key="Sample" />
        </Window.Resources>
    
  3. Set the DataContext of the Grid to the SampleViewModel StaticResource.
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="50" />
            </Grid.RowDefinitions>
    
  4. Add two rows to the Grid.
        <Grid DataContext="{StaticResource ResourceKey=Sample}">
    
  5. Add a TextBox and remove the sizing and alignments. Set Margin to 5. Bind the Text property to Message.
            <TextBox Text="{Binding Message}" Name="textBoxMessage" Margin="5"/>
    
  6. Add a button. Set HorizontalAlignment to Right. Set the Width to Auto. Set Margin to 5. Bind the Command property to ShowMessageCommand.
    <Button Command="{Binding ShowMessageCommand}" Content="ShowMessage" Grid.Row="1" Height="23" Name="buttonShowMessage" HorizontalAlignment="Right" Width="Auto" Margin="5"/>
    

You are done. The final XAML is as follows:

<Window x:Class="WpfDataBindingToICommand.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfDataBindingToICommand"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:SampleViewModel x:Key="Sample" />
    </Window.Resources>
    <Grid DataContext="{StaticResource ResourceKey=Sample}">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="50" />
        </Grid.RowDefinitions>
        <TextBox Text="{Binding Message}" Name="textBoxMessage" Margin="5"/>
        <Button Command="{Binding ShowMessageCommand}" Content="ShowMessage" Grid.Row="1" Height="23" Name="buttonShowMessage" HorizontalAlignment="Right" Width="Auto" Margin="5"/>
    </Grid>
</Window>

Notice that we never touched the code behind of MainWindow. The GUI and the code are as decoupled as possible. Not event the event functions are needed in the code behind. This decoupling or GUI and code is our goal.

Resources

WPF Apps With The Model-View-ViewModel Design Pattern
Understanding Routed Events and Commands In WPF


Copyright ® Rhyous.com – Linking to this page is allowed without permission and as many as ten lines of this page can be used along with this link. Any other use of this page is allowed only by permission of Rhyous.com.

Tutorial – Binding to a member variable object

You have your WPF Window and you have an object that you don’t want to make a static resource. You want to declare it as a member variable in the code.

Example 1 – Binding two TextBox controls to a Person object

  1. Create a New WPF Application Visual Studio.
  2. Create a new Class named Person.cs.
  3. Give it FirstName and a LastName properties.
  4. Configure it to implement the INotifyPropertyChanged interface.
  5. Create a NotifyPropertyChanged function that all properties can share (to avoid duplicate code in every single property).
  6. Configure the properties to call the NotifyPropertyChanged function passing in a string that is the name of the property.

    Person.cs

    using System;
    using System.ComponentModel;
    
    namespace WPFPerson
    {
        public class Person : INotifyPropertyChanged
        {
            #region Member Variables
            String _FirstName;
            String _LastName;
            #endregion
    
            #region Constructors
            /*
    		 * The default constructor
     		 */
            public Person()
            {
            }
            #endregion
    
            #region Properties
            public String FirstName
            {
                get { return _FirstName; }
                set
                {
                    _FirstName = value;
                    NotifyPropertyChanged("FirstName");
                }
            }
    
            public String LastName
            {
                get { return _LastName; }
                set
                {
                    _LastName = value;
                    NotifyPropertyChanged("LastName");
                }
            }
            #endregion
    
            #region INotifyPropertyChanged Members
            public event PropertyChangedEventHandler PropertyChanged;
    
            private void NotifyPropertyChanged(String info)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(info));
                }
            }
            #endregion
        }
    }
    
  7. Go back tot he MainWindow.xaml.
  8. Add two labels, and two text boxes, and a button.
  9. Change the text boxes to be populated using binding by adding the following text:
    Text=”{Binding FirstName, Mode=TwoWay}”  

    MainWindow.xaml (WPF Window)

    <Window x:Class="WPFPerson.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525" >
        <Grid Name="PersonGrid" >
            <TextBox Height="23" HorizontalAlignment="Left" Margin="173,87,0,0" Name="textBoxFirstName" VerticalAlignment="Top" Width="234" Text="{Binding FirstName, Mode=TwoWay}" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="173,116,0,0" Name="textBoxLastName" VerticalAlignment="Top" Width="234" Text="{Binding LastName, Mode=TwoWay}"/>
            <Label Content="FirstName" Height="28" HorizontalAlignment="Left" Margin="103,85,0,0" Name="labelFirstName" VerticalAlignment="Top" />
            <Label Content="LastName" Height="28" HorizontalAlignment="Left" Margin="103,114,0,0" Name="labelLastName" VerticalAlignment="Top" />
            <Button Content="Defaults" Height="23" HorizontalAlignment="Left" Margin="337,199,0,0" Name="buttonDefaults" VerticalAlignment="Top" Width="75" Click="buttonDefaults_Click" />
        </Grid>
    </Window>
    
  10. Double-click the button to create the buttonDefaults_Click event function.
    This also conveniently takes you to the Code Behind of the MainWindow.cs file.
  11. Have the buttonDefaults_Click function update to properties of your _Person object.
    _Person.FirstName = “Jared”;
    _Person.LastName = “Barneck”;
  12. Create a field/member variable using the Person object.
    private readonly Person _Person;
  13. Now in the constructor initialize the object.
    _Person = new Person();
  14. Also in the constructor, make the DataContext for each TextBox the _Person object.
    textBoxFirstName.DataContext = _Person;
    textBoxLastName.DataContext = _Person;  

    MainWindow.cs (Code Behind)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Threading;
    
    namespace WPFPerson
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            private readonly Person _Person;
    
            public MainWindow()
            {
                _Person = new Person();
                InitializeComponent();
                textBoxFirstName.DataContext = _Person;
                textBoxLastName.DataContext = _Person;
            }
    
            private void buttonDefaults_Click(object sender, RoutedEventArgs e)
            {
                _Person.FirstName = "Jared";
                _Person.LastName = "Barneck";
            }
        }
    }
    
  15. Now Now compile and make sure you don’t have any errors.

Example 2 – Forthcoming…

Example 3 – Forthcoming…

Sources:
http://www.wrox.com/WileyCDA/Section/Windows-Presentation-Foundation-WPF-Data-Binding-with-C-2005.id-305562.html

Changing the prompt for csh on FreeBSD 8.1

The prompt by default for csh on FreeBSD is simply a sing percent symbol.

%

There is not space before or after this.  I don’t like it and it drives me crazy. I like a prompt to tell me three things:

  1. Who is logged in.
  2. The machine name.
  3. The current path.

This change is quite simple.  It can be made temporarily, permanently for all users, or permanently for a single user.

Temporary

Sometimes you don’t want to make a permanent change to the prompt.  Especially if you are on someone else’s system temporarily and using one of their shells.  In such a case, setting the prompt temporarily is desired.

To see the prompt temporarily, simply run this command:

set prompt = “[%n@%m %c]$ “

Your prompt should now look as follows:

[SomeUser@SomeComputer ~]$

This is only temporary. As soon as you close the shell, the settings is gone and any new shells will continue to have the old setting.

All Users

To make a change for all users, the file that needs to be edited is /etc/csh.cshrc.

By default the file is empty except for some comments.  Line that are comments begin with the # character.

Add these lines to empty file:

if ($?prompt) then
        # An interactive shell -- set some stuff up
        set prompt = "[%n@%m %c]$ "
endif

After making this change, your prompt should look as follows:

[SomeUser@SomeComputer ~]$

If the file is not empty then you probably have to search yourself if the prompt is being set and replace it with the above.

Be careful that the prompt is not set for a single user because if it is, the user’s setting overrides the global settings.

Single User

The prompt can be set on a user by user basis.  The user’s settings will override the global setting.

To make a change for a single user, the file that needs to be edited is ~/csh.cshrc.

By default the file looks as follows:

# .cshrc - csh resource script, read at beginning of execution by each shell
#
# see also csh(1), environ(7).
#

alias h         history 25
alias j         jobs -l
alias la        ls -a
alias lf        ls -FA
alias ll        ls -lA

# A righteous umask
umask 22

set path = (/sbin /bin /usr/sbin /usr/bin /usr/games /usr/local/sbin /usr/local/bin $HOME/bin)

setenv  EDITOR  vi
setenv  PAGER   more
setenv  BLOCKSIZE       K

if ($?prompt) then
        # An interactive shell -- set some stuff up
        set filec
        set history = 100
        set savehist = 100
        set mail = (/var/mail/$USER)
        if ( $?tcsh ) then
                bindkey "^W" backward-delete-word
                bindkey -k up history-search-backward
                bindkey -k down history-search-forward
        endif
endif

After modification, my /etc/csh.cshrc looks like this:

# $FreeBSD$
#
# .cshrc - csh resource script, read at beginning of execution by each shell
#
# see also csh(1), environ(7).
#

alias h         history 25
alias j         jobs -l
alias la        ls -a
alias lf        ls -FA
alias ll        ls -lA

# A righteous umask
umask 22

set path = (/sbin /bin /usr/sbin /usr/bin /usr/games \
           /usr/local/sbin /usr/local/bin $HOME/bin \
           /usr/local/kde4/bin /usr/local/kde4/sbin \
           /usr/X11R6/kde4/bin /usr/X11R6/kde4/sbin \
           /usr/X11R6/kde4/lib/kde4/libexec)

setenv  EDITOR  vi
setenv  PAGER   more
setenv  BLOCKSIZE       K

if ($?prompt) then
        # An interactive shell -- set some stuff up
        set prompt = "[%n@%m %c]$ "
        set filec
        set history = 100
        set savehist = 100
        set mail = (/var/mail/$USER)
        if ( $?tcsh ) then
                bindkey "^W" backward-delete-word
                bindkey -k up history-search-backward
                bindkey -k down history-search-forward
        endif
endif

Your prompt should now look as follows:

[SomeUser@SomeComputer ~]$

Whatever you set the prompt to as a single user will override the global setting.

What is the equivalent of __FILE__ and __LINE__ in C#?

Where is __LINE__ and __FILE__ in C#?

In C++ and in PHP and other languages, a great logging feature is the ability to log the file and line number where the log occurs.

These unfortunately do not exist.  I have been searching even in the latest .NET 4.0 and haven’t found them.  If they are there, they are hidden. Having these two variables is an extremely useful feature in other languages and it appears to be a feature very overlooked by the C# developers. However, maybe they didn’t overlook it.  Maybe there is a good reason that it is not there.

Getting __LINE__ and __FILE__ in C# when in debugging mode

There were a couple of solutions floating around online but many of them only worked with debugging enabled (or in release if the pdb file is in the same directory).

Here is one example that only works in debugging (or in release if the pdb file is in the same directory).

StackHelper.cs

using System;
using System.Diagnostics;

namespace FileAndLineNumberInCSharpLog
{
    public static class StackHelper
    {

        public static String ReportError(string Message)
        {
            // Get the frame one step up the call tree
            StackFrame CallStack = new StackFrame(1, true);

            // These will now show the file and line number of the ReportError
            string SourceFile = CallStack.GetFileName();
            int SourceLine = CallStack.GetFileLineNumber();

            return "Error: " + Message + "\nFile: " + SourceFile + "\nLine: " + SourceLine.ToString();
        }

        public static int __LINE__
        {
            get
            {
                StackFrame CallStack = new StackFrame(1, true);
                int line = new int();
                line += CallStack.GetFileLineNumber();
                return line;
            }
        }

        public static string __FILE__
        {
            get
            {
                StackFrame CallStack = new StackFrame(1, true);
                string temp = CallStack.GetFileName();
                String file = String.Copy(String.IsNullOrEmpty(temp)?"":temp);
                return String.IsNullOrEmpty(file) ? "": file;
            }
        }
    }
}

Here is a little Program.cs that shows how to use it.

using System;

namespace FileAndLineNumberInCSharpLog
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 100;
            int y = 200;
            int z = x * y;
            Console.WriteLine(StackHelper.ReportError("New Error"));
        }
    }
}

Unfortunately if the above does only work in release if the pdb file is available.

Getting __LINE__ and __FILE__ in C# when in debugging mode

Well, according to this MSDN forum post, it simply cannot be done.
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/6a7b021c-ec81-47c5-8f6a-2e280d548f3f

If I ever find a way to do it, I will post it.

So for troubleshooting a production file at a customer’s site, you pretty much have to send out your pdb file to them when they need it.  There are a lot of benefits to C# and this lacking feature is one of the eye sores.

Tutorial – Binding to Resources.resx for strings in a WPF Application: A technique to prepare for localization

Update: This is no longer a recommended way to do localization in WPF.
Use this project from NuGET: WPFSharp.Globalizer
Also read this post: How to change language at run-time in WPF with loadable Resource Dictionaries and DynamicResource Binding

Introduction

Ok, so if you are going to have a string visible in your WPF application and your application can be in multiple languages, you are facing the localization problem.

Usually people as themselves two questions:

  • Do I localize or not?
  • How do I localize?

The answers are usually not now and I don’t know. So no localization work is done at first. Later, you wish you were more prepared for localization.

Well, I am here to tell you that you can at least prepare to be localized by doing a few simple steps:

  1. Centralize your strings in a publicized Resources.resx file.
  2. Add a reference to your Properties.
  3. Replacing any statically entered text with the name of the string resource.
  4. Do you best to use dynamic sizing.

Preparing your strings for localization

If you are going to have a string in your WPF application, it is a good idea to store those strings in a centralized place for localization purposes. Usually in Visual Studio, that is in Resources.resx.

Cialis is an additional impotence problems treatment, http://www.horizonhealthcareinc.com/ which is gaining interest at a faster pace. The reason for more popular at a faster pace is because of its effectiveness.

Often a string is entered directly into an the WPF XAML. This is not recommended. Maybe you are thinking that you don’t need to localize your application, so this is not important to you. Ok, really what you are thinking is:

“I don’t know how to do it and if I ever get big enough to need localization, at that point, I will figure it out.”

Well, what if I told you that using Resources.resx is extremely easy?

What if I told you that it hardly takes more time at all?

If it easy and hardly time consuming at all, you would do it, right? I would. Hence this post.

Step by step guide for Preparing your strings for locaization

I have a project called LicenseAgreementManager. Right now this only needs to display a license agreement in English, but maybe someday, this will need to display a license agreement in any language.

Preparation – Create a new project or use an existing project

In Visual Studio, create a new WPF Applcation project.

I named my project LicenseAgreementManager.

Right away, you already have at least one string statically entered into your XAML, the text for the window title.

Step 1 – Add all your strings to the Resources.resx file

  1. Double-click on Resources.resx in your WPF Project. This found under the ProjectName | Properties option in your Solution Explorer tree.
  2. Change the Access Modifier drop down menu from Internal to Public.
  3. Enter your strings in the Resources.resx by giving them a unique name and a value of the desired string. A comment is also optional.

You now have a publicized Resource.resx file and a few strings inside it.

Step 2 – Add a reference to your Properties

  1. In your project, open your MainWindow.xaml file.The XAML looks as follows:
    <Window x:Class="LicenseAgreementManager.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
    
        </Grid>
    </Window>
    
  2. Add a line to reference your Properties in the Windows element.
    <Window x:Class="LicenseAgreementManager.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:p="clr-namespace:LicenseAgreementManager.Properties"
            Title="MainWindow" Height="350" Width="525">
    

Step 3 – Replace static text with strings from the Resources.resx

  1. Change the Title attribute from static text to instead use access the string from your Resources.resx named EULA_Title.
    <Window x:Class="LicenseAgreementManager.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:p="clr-namespace:LicenseAgreementManager.Properties"
            Title="{x:Static p:Resources.EULA_Title}"
            Height="350" Width="525">
    

That was pretty easy, wasn’t it.

As you add elements that have strings, use the Resources.resx.

Step 4 – Try to use dynamic sizing

  1. As best as possible, remove any dynamic sizing.I have just added some items and removed the sizing as best as possible. Here is my XAML.
    <Window x:Class="LicenseAgreementManager.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:p="clr-namespace:LicenseAgreementManager.Properties"
            Title="{x:Static p:Resources.EULA_Title}"
            SizeToContent="WidthAndHeight"
            xml:lang="en-US">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
    
            <RichTextBox Name="_EulaTextBox" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch"/>
            <StackPanel Grid.Row="1" Margin="0,10,0,0" Name="stackPanel2" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch">
                <RadioButton Content="{x:Static p:Resources.EULA_Accept}" Margin="20,20,20,0" Name="radioButton1" />
                <RadioButton Content="{x:Static p:Resources.EULA_NotAccept}" Margin="20,20,20,0" Name="radioButton2" />
                <Button Content="{x:Static p:Resources.Next_Button}" Name="button1" Margin="20,20,35,20"  HorizontalAlignment="Right" />
            </StackPanel>
        </Grid>
    </Window>
    
  2. What changes did I make above that I couldn’t do through the Visual Studio GUI?
    1. I removed Height and size from almost every element.
    2. I added SizeToContent=”WidthAndHeight” to the Windows element.
    3. I added some extra size to the margins.

Conclusion

You don’t have to be localized to be prepared for easy localization. By doing the above simple steps, when it comes time to add localization, you will be ready.

If you want to go on an finish localization. You might want to read some of my sources.

Sources:

http://compositeextensions.codeplex.com/Thread/View.aspx?ThreadId=52910
http://msdn.microsoft.com/en-us/library/ms788718%28v=VS.90%29.aspx
http://msdn.microsoft.com/en-us/library/ms746621.aspx


Copyright ® Rhyous.com – Linking to this article is allowed without permission and as many as ten lines of this article can be used along with this link. Any other use of this article is allowed only by permission of Rhyous.com.

Adding an alias in Windows 7 or making ls = dir in a command prompt

Hey all,

I don’t know about you but I switch between FreeBSD and Windows a lot.  So it drives me crazy when I type the command ls on windows and get the error message.

C:\Windows\system32>ls
‘ls’ is not recognized as an internal or external command,
operable program or batch file.

So I want this to go away.

I looked for the alias command in Windows and couldn’t find one.  So I made a batch file that solves this.

Windows doesn’t seem to have the equivalent of a .shrc or .cshrc or .bashrc. I couldn’t find a .profile either.  So I decided to go with the batch file route.

Option 1 – Using doskey

I was tipped off to this idea from a comment, which led my mind to the Command Prompt autorun registry I already knew about. But once I wrote the batch file, the parameters were not working, so I searched around and found an example of exactly what I wanted to do here:
http://bork.hampshire.edu/~alan/code/UnixInWin2K/

  1. Create a batch file called autorun.bat and put it in your home directory:
    My home dir is: c:\users\jared
  2. Add the following to your autorun.bat.
    @ECHO OFF
    doskey ls=dir /b $*
    doskey ll=dir $*
    doskey cat=type $*
    doskey ..=cd..
    doskey grep=find "$1" $2
    doskey mv=ren $*
    doskey rm=del $*
    
  3. Add the following key to the registry:
    Key:  HKEY_CURRENT_USER\Software\Microsoft\Command Processor
    REG_SZ  (String): Autorun
    Value:  %USERPROFILE%\autorun.batOr as a .reg file:

    Windows Registry Editor Version 5.00
    
    [HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
    "Autorun"="%USERPROFILE%\\autorun.bat"
    

Now whenever you open a command prompt, the aliases will be there.

Option 2 – Creating a batch file as an alias

I created an.bat file that just forwards calls the original file and forwards all parameters passed when making the call.

Here is how it works.

Create a file called ls.bat. Add the following text.

ls.bat

@ECHO OFF
dir $*

Copy this batch file to your C:\Windows\System32 directory. Now you can type in ls on a windows box at the command prompt and it works.

How does this work to make your aliased command?

  1. Name the batch file the name of the alias.  I want to alias ls to dir, so my batch file is named ls.bat.
  2. In the batch file, set the RealCMDPath variable to the proper value, in my case it is dir.

So if you want to alias cp to copy, you do this:

  1. Copy the file and name it cp.bat.
  2. Edit the file and set this line:
    SET RealCMDPath=dir

Now you have an alias for both ls and cp.

Using different versions of msbuild.exe

You can also use this so you don’t have to add a path.

I need to use C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe but sometimes I want to use C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe. Both files are named the same. So I can easily use my alias command.

  1. Create two files in C:\Windows\System32: one named msbuild35.bat and one named msbuild40.bat.
  2. Change the line in each file to have the appropriate paths for the RealCMDPath.

Anyway, this is really a useful batch file.

WIX: Creating an MSI to deploy multiple files

In this example we are going to create a simple MSI that deploys a two files.  This is not that much different than one file, but there is an implementation decision you have to make here that is important to understand.

Prequisites

Step 1 – Create a WIX project in Visual Studio

Creating a new project is a very simple task once you have done it a few times. However, I try to make my walk-thrus newbie proof, so even some one who has never done this feels comfortable. So if you need help with this step, use my instructions below. If you don’t, skip them.

  1. Open Visual Studio if it is not already open.
  2. Got to File | New | Project.
  3. You should have an option under Installed Templates for Windows Install XML. Select it.
  4. Now you should see the option for Setup Project. Select it.
  5. Enter a Name for the project. I called the project I made for this walk-thru MultiFileProject.
  6. Change the directory to store the project if you want. It doesn’t matter what directory you choose, but it is nice to keep your learning projects organized.
  7. Click OK.

Your project should now be created. In solution explorer you should now have a solution, a project, a reference and the Product.wxs. See the image below.

Ok, I hope that was easy for you. Lets move on.

Step 2 – Add two files to the project

These steps are preformed in Visual Studio on the project you just created in the above step.

  1. Right-click on the project name, MultiFileProject, and from the drop down, choose Add | New Item.
  2. Select Text File.
  3. Name it whatever you want. I used the default value, TextFile1.txt for this example.
  4. Click Add.
  5. Repeat the steps above to create a second file. My second file is TextFile2.txt.

Your files are now added to the Visual Studio project. However, they are not automatically added into the Product.wxs as a file to be installed. This is done manually in the next step.

Step 3 – Take a moment to learn

We are going to change the Product.wxs file to include the file we just created.

The Product.wxs file has the following XML text in it. Take a moment to look at the XML nodes and their elements so are familiar with the syntax it is using.

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
	<Product Id="9a19f6ed-a7b2-4cfc-a429-7069066fbf2a" Name="MultiFileProject" Language="1033" Version="1.0.0.0" Manufacturer="MultiFileProject" UpgradeCode="c1bdcc4d-b249-4b36-97fd-32609a60f8b4">
		<Package InstallerVersion="200" Compressed="yes" />

		<Media Id="1" Cabinet="media1.cab" EmbedCab="yes" />

		<Directory Id="TARGETDIR" Name="SourceDir">
			<Directory Id="ProgramFilesFolder">
				<Directory Id="INSTALLLOCATION" Name="MultiFileProject">
					<!-- TODO: Remove the comments around this Component element and the ComponentRef below in order to add resources to this installer. -->
					<!-- <Component Id="ProductComponent" Guid="6263db4e-4c67-4adc-9ef1-e1caef798331"> -->
						<!-- TODO: Insert files, registry keys, and other resources here. -->
					<!-- </Component> -->
				</Directory>
			</Directory>
		</Directory>

		<Feature Id="ProductFeature" Title="MultiFileProject" Level="1">
			<!-- TODO: Remove the comments around this ComponentRef element and the Component above in order to add resources to this installer. -->
			<!-- <ComponentRef Id="ProductComponent" /> -->

			<!-- Note: The following ComponentGroupRef is required to pull in generated authoring from project references. -->
			<ComponentGroupRef Id="Product.Generated" />
		</Feature>
	</Product>
</Wix>

The text of the Xml gives us hints as to what we are supposed to do in its comments. Take a moment and read the comments.

Step 4 – Configure the WIX Xml file to deploy that file

Lets start editing that XML file.

Note: I am going to use the term “node’ to indicate and XML section. So and everything it contains is a node. If a node is inside it, I might call it a subnode.

  1. Uncomment the Component node the Directory nodes.
  2. Remove the two TODO: comments.
  3. Uncomment the ComponentRef node that is inside the Feature node.
  4. Remove the TODO: comment and the Note comment.
  5. Inside the Component node, at two File nodes for each of your two files as follows:
    <File Id='TextFile1.txt_id' Name='TextFile1.txt' Source='TextFile1.txt' KeyPath='yes' />
    <File Id='TextFile2.txt_id' Name='TextFile2.txt' Source='TextFile2.txt' />
    

    Notice that the second line is not marked with the KeyPath attribute. Only one file node (or maybe a registry node) can set KeyPath.

Ok, you are done.  Yes, that was all there is too it.   Feel free to add as many files as you want.

You XML syntax should now look as follows:

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="9a19f6ed-a7b2-4cfc-a429-7069066fbf2a" Name="MultiFileProject" Language="1033" Version="1.0.0.0" Manufacturer="MultiFileProject" UpgradeCode="c1bdcc4d-b249-4b36-97fd-32609a60f8b4">
    <Package InstallerVersion="200" Compressed="yes" />

    <Media Id="1" Cabinet="media1.cab" EmbedCab="yes" />

    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="ProgramFilesFolder">
        <Directory Id="INSTALLLOCATION" Name="MultiFileProject">
          <Component Id="ProductComponent" Guid="6263db4e-4c67-4adc-9ef1-e1caef798331">
            <File Id='TextFile1.txt_id' Name='TextFile1.txt' Source='TextFile1.txt' KeyPath='yes' />
            <File Id='TextFile2.txt_id' Name='TextFile2.txt' Source='TextFile2.txt' />
          </Component>
        </Directory>
      </Directory>
    </Directory>

    <Feature Id="ProductFeature" Title="MultiFileProject" Level="1">
      <ComponentRef Id="ProductComponent" />
      <ComponentGroupRef Id="Product.Generated" />
    </Feature>
  </Product>
</Wix>

Ok, you are ready to build.

Step 4 – Build the project

Well, there really isn’t much to debug, so we are only going to build a release version here.

  1. In the Visual Studio 2010 tool bar, there should be a drop down box that either says Debug or Release. Change it to Release if it is not already at Release.
  2. Select Build | Build Solution or use the shortcut key.

You should now have an MSI built in the project’s bin\release directory.

Step 5 – Test the MSI

Let’s go get the MSI and test it.

  1. Right-click on the project, MultiFileProject, and choose, Open Folder in Windows Explorer.
  2. In Explorer, navigate into the bin\release directory.
  3. You will see two files:
    MultiFileProject.msi – This is the MSI and is all you need.
    MultiFileProject.wixpdb – This is a file for debugging only. You may never use it unless you need to debug.
  4. You may or may not want to test the MSI on you development box. If you do, just double-click the MSI. Otherwise, copy it to a test box and run the MSI there.
  5. Verify that the file installed.
    Note: If on a 64 bit system, it will by default install as an x86 app, so look in c:\program files (x86)\ for a folder called MultiFileProject.
  6. Check Add / Remove Programs to make sure the install shows up there and that the uninstall works.

Congratulations. You just use WIX to create an MSI that deploys multiple files.