Archive for the ‘IDEs’ Category.

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

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.

Avoiding the MSVCR100.dll, MSVCP100D.dll, or MSVCR100D.dll is missing error (Also MSVCR110.dll, MSVCR120.dll, MSVCR140.dll)

Note: This also applies to newer MSVCR110.dll, MSVCR120.dll and MSVCR140.dll.

MSVCR100.dll

This msvcr100.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2010. The dll letters spell this out.

MS = Microsoft
V = Visual
C = C program language
R = Run-time
100 = Version

If you create a C++ project in Visual Studio 2010, this file is probably needed.

MSVCP100.dll

This msvcp100.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2010. The dll letters spell this out.

MS = Microsoft
V = Visual
CP = C++
100 = version

If you create a C++ project in Visual Studio 2010, this file is probably needed.

MSVCR100D.dll

The MSVCR100D.dll is almost the exact same file only the D at the end stands for Debug. This file has debugging enabled and is not considered redistributable.

Why the error?

Ok, so recently I switched to Visual Studio 2010.  I had a C++ application that worked perfectly in Visual Studio 2008.  Once I compiled it with Visual Studio 2010 and ran it on a clean 2008 server (fully patched but otherwise clean), it failed to run with the following error.

TestWin32.exe – System Error

The program can’t start because MSVCR100.dll is missing from your computer. Try reinstalling the program to fix this problem.

Here is the screen shot:

msvcr100.dll

The same things happens with the debug version of the file, only it is a the debug version of the same DLL as noted by the fact that the DLL name ends with D.

Autorun – System Error

The program can’t start because MSVCR100.dll is missing from your computer. Try reinstalling the program to fix this problem.

The screen shot is identical except for the D in the dll name.

msvcr100d.dll

I create a new project in Visual Studio 2010 using the project type of C++ Win32 Project and without making a single change to the default project, I built the file and tested it on my clean machine and the same issue occurred.

So obviously that is not acceptable.  It seems like this should just not happen by default, but unfortunately it does.

Solution

It was actually really easy to resolve for my one project.

Here is what I did.

You can solve this any of the following ways:

  1. Statically link to the dll files so they are compiled into my executable instead of referenced as separate dll files.
  2. Included the dll in the same directory as the exe (I actually didn’t try this but I assume it would work).
  3. Forced everyone to install the VC++ Runtime Redistributable before running the app.

The first option seems the most stable and robust and easiest for a single executable. So that is the one I am going to use.

The second option doesn’t really make sense to me and I would probably never do it. Maybe if I had dozens of executable files that all required the same DLL and I didn’t have an installer, and I wanted to conserve size, which probably wouldn’t happen for me since I am pretty good at creating a quick installer. Though you might be in this a situation.

The third option would make sense if I was planning on running my executable after an install. During the install I could include the VC++ Runtime Redistributable and all would be fine.

Statically Linking the DLLs

Make sure you resolve it for both Release and Debug. The steps are slightly different.

Release

  1. In Visual Studio, I went to the project Properties.
  2. I changed my Configuration to Release.
  3. I went under Configuration Properties | C/C++ | Code Generation
  4. Look at the Runtime Library setting.  It is set to this: Multi-threaded DLL (/MD)
    Change it to this: Multi-threaded (/MT)
  5. Rebuild.

Debug

Almost exactly the same as release.

  1. In Visual Studio, I went to the project Properties.
  2. I changed my Configuration to Debug.
  3. I went under Configuration Properties | C/C++ | Code Generation
  4. Look at the Runtime Library setting. It is set to this: Multi-threaded Debug DLL (/MDd)
    Change it to this: Multi-threaded Debug (/MTd)
  5. Rebuild the debug

It might be a good idea for me to figure out how to change the project so when I create a new project of this type, those settings are the default.

Install the VC++ Runtime Redistributable

Release

Download the appropriate version of VC++ Runtime Redistributable:

File Version VC++ Runtime Version
MSVCR100.dll Microsoft Visual C++ 2010 Redistributable Package (x86)
MSVCR110.dll Microsoft Visual C++ 2012 Redistributable Package (x86)
MSVCR120.dll Microsoft Visual C++ 2013 Redistributable Package (x86)
MSVCR140.dll Microsoft Visual C++ 2015 Redistributable Package (x86)

Just google these and you will find the download links. Install the correct version and you are good to go.

Debug

If you are missing MSVCR100D.dll, then that is a debug dll and is not part of the free to download Visual C++ Redistributable package. So you pretty much are stuck with copying it from your dev box. Copy it to the C:\Windows\System32 directory. You need admin privileges to do this.

Note: You would never want to redistribute the debug dll anyway.

How to document a function so Visual Studio's Intellisense displays it?

So, when I code, I am usually in Visual Studio and I am used to writing documentation above my functions as follows:

        /*
         * The is SomeFunction that does some action.
         */
        private void SomeFunction(int inSomeValue)
        {
                // write code here
        }

However, it annoys me that this information doesn’t show up in Visual Studio’s Intellisense. So I took time to look up the proper way to make function documentation show up in Intellisense.

It turns out that you can type /// above a function and Visual Studio will automagically populate the markup needed to have your comments show up in intellisense.

        /// <summary>
        ///  The is SomeFunction that does some action.
        /// </summary>
        /// <param name="inSomeValue">Enter an integer as some value here.</param>
        private void SomeFunction(int inSomeValue)
        {
                // write code here
        }

So it seems if you use this syntax, the function documentation will now show up in Visual Studio’s Intellisense.

How to determine the project type of an existing Visual Studio project?

Ok, so I have an existing C++ Visual Studio project (at my new position here as a Developer at LANDesk) and who knows who created it or when it was created.  Anyway, I wanted to start a new project and use the same project type.

So how do I find out the project type.

In Visual Studio, I opened the ProjectName.vcproj file and found this information near the top:

<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
	ProjectType="Visual C++"
	Version="9.00"
	Name="MSICheckForPatch"
	ProjectGUID="{0793FB88-8BED-4297-8615-9408EA2FBE74}"
	Keyword="AtlProj"
	TargetFrameworkVersion="196613"
	>
	<Platforms>
		<Platform
			Name="Win32"
		/>
	</Platforms>
	...

So I noticed the Keyword was AtlProj, so that clued me in.

Looks like it was as easy as opening a text file and looking.

If there is a better or easier way, please comment and let me know.

Notepad++ and the XML Tools plugin

Ok, so I do a lot with Xml files.  Between working with my company’s product LDMS and all the Xmls it uses, to my own code using Serialization, I seem to always have an Xml file open.

I hate it when I open and Xml File and it is all on one line.  Or every element is a separate line but not a single line is indented.

Visual Studio can fix these for me rather easily.  But I have a lot of different machines in my lab and often work in other’s labs, or on customer’s computers while remote controlling them for support reasons. I can’t just quickly download an install Visual Studio. While yes, there is a free Express Edition version, it is just an overkill for the simple job of making an Xml file look pretty in text.  I need a small simple, quick to download and install tool.

The solution was right in front of me the whole time: Notepad++ and the XML Tools plugin

I always use Notepad++ as my random text editor on windows.  I already use its Compare plugin constantly, so I am very familiar with it.  It finally donned on me to check if it had an plugin that could help me with Xmls and sure enough, it did.

The XML Tools plugin, has almost all the features I wanted.

Notepad++ is just over 3 megabytes and download rather quickly.  The XML Tools plugin is not installed by default but can quickly be installed using the Plugin Manager.  Don’t worry about the additional download, the XML Tools plugin is only just over 300 kilobytes.

So I can now prettify my Xml files with a small, quick to download and install, windows tool.

Here is the menu this plugin provides, so you can see a list of some of the features.

So the Pretty pring (XML only – with line breaks) will take an Xml that is all on one single line, and expand it to have line breaks and also give it the proper indents.

There is also a tool to make sure the Syntax is correct.

The only feature I want that it doesn’t have is a tool to sort child elements and attributes.


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.

How to create a custom class template for Xml Serializable classes?

Ok, so you don’t always want a default class template for every type of class.  I have to create a bunch of classes that implement Serializable and if the class template assumed this, that would be great.  However, I don’t want my default class template to assume this.

So here is what I did broken down into four simple steps.

  1. Open or create a c# project.
  2. Create a class file.
  3. Add the text and the variables to replaced.
  4. Export the item as a template.

Step 1 – Open or create a c# project.

Ok, so any project will do.  I used an existing project, but you can create a new one if you want.  Any C# project should allow this to happen.

Step 2 – Create a class file.

In one of my C# projects in Visual Studio, I created a new class called XmlClass.cs.

Step 3 – Add the text and the variables to replaced

I put the following text into my new class:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace $rootnamespace$
{
	[Serializable]
	public class $safeitemrootname$
	{
		#region Member Variables
		#endregion

		#region Constructors

		/*
		 * The default constructor
 		 */
		public $safeitemrootname$()
		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

Step 4 – Export the item as a template

  1. In Visual Studio, chose File | Export Template.  This starts a wizard that is extremely easy to follow.Note: If you have unsaved files in your project, you will be prompted to save them.
  2. Chose Item template, select your project, and click Next.
  3. In the next screen there was a tree view of check boxes for all my objects.  I checked the box next to my XmlClass.cs.
  4. In the next screen, provide references.Note: I added only System and System.Xml.
  5. In the next screen, provide a Template name and a Template description.
  6. Click finish.

You should now have the option under My Templates when you add a new item to your project.

This class will be  useful and will save you and your team some typing when you are in the class creation phase of your project and you are creating all your Serializable classes.


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.

Changing the prop snippet for creating a Property in C#

Ok, so it is very common for the c# member variables to start with either an _ (underscore) or an m.  So when creating a property, you can save a lot of time by changing it to assume this as well.

For example, your class may look as follows:

namespace AgentConfigurationPlugin
{
    public class Class1
    {
        #region Member Variables
        String _MemberString;
        int _MemberInt;
        #endregion

        #region Constructors

        /*
		 * The default constructor
 		 */
        public Class1()
        {
        }

        #endregion

        #region Properties
        public String MemberString
        {
            get { return _MemberString; }
            set { _MemberString = value; }
        }

        public int Memberint
        {
            get { return _MemberInt; }
            set { _MemberInt = value; }
        }
        #endregion
    }
}

Note: I use the _ character even though it is hard to type (being up to the right of my pinky finger), so if you prefer, use the letter “m”, which is easy to type (being just below my pointer finger) and it also stands for “member variable”.

        #region Member Variables
        String mMemberString;
        int mMemberInt;
        #endregion

Anyway, whether it is an “m” or “_” or any other character, it is common to prefix member variables. So it would be useful if the property snippet assumed that prefix character as well.

The default snippet for creating a Property is located here:

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#\prop.snippet

The contents looks as follows.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>prop</Title>
			<Shortcut>prop</Shortcut>
			<Description>Code snippet for an automatically implemented property</Description>
			<Author>Microsoft Corporation</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Property type</ToolTip>
					<Default>int</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[public $type$ $property$ { get; set; }$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

Change it to be like this:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>prop</Title>
			<Shortcut>prop</Shortcut>
			<Description>Code snippet for an automatically implemented property</Description>
			<Author>Microsoft Corporation</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Property type</ToolTip>
					<Default>int</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[public $type$ $property$
		{
    			get { return _$property$; }
    			set { _$property$ = value; }
		}
$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

The key section that fixes this is:

			<Code Language="csharp"><![CDATA[public $type$ $property$
		{
    			get { return _$property$; }
    			set { _$property$ = value; }
		}
$end$]]>

Or if you use “m” instead of “_” as I do, of course you would replace the “_” with an “m”.

			<Code Language="csharp"><![CDATA[public $type$ $property$
		{
    			get { return m$property$; }
    			set { m$property$ = value; }
		}
$end$]]>

Now when you create a member variable and then a property that matches it exactly except for the prefix character, the works is done for you, making you a more efficient programmer.

You may want to change the propg snippet as well.


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.

How to use relative paths when debugging in Visual Studio 2008?

Hello everyone,

I have a project one computer in the My Documents folder. When I copy it to another user computer (under their My Documents directory) I want it to work with no tweaking.

Do Macros work? No.

My build process uses build events to copy files to an Install directory and since build events uses macros so it works perfectly. I want to use these same Macros in either or both of two debugging options:

  • Start external program
  • Working directory

So I attempt to use the same Macros:

Start external program: $(SolutionDir)\Install\Program.exe

This fails with the following error:

Working Directory:
The working directory you entered does not exist.  Please enter a valid working directory.

Same failure pretty much if I try to use a macro int he Working directory text field.

Well, that is a let down.

Do Environment Variables Work? No.

So I tried to use environment variables. They didn’t work either.

Start external program:    “%USERPROFILE%\My Documents\My Project\Install\Program.exe”

That wasn’t a good solution anyway, cause I want it to work whether copied to a Desktop or a D: drive or whatever.

What can I do?

Well, I loaded up Process Monitor for Sysinterals Suite and checked where we look. I configured it to just look for the executable.

Start external program:    Program.exe

Turns out we check for the executable relative to either of two paths:

  • In the YourProjectDir\bin\debug\Program.exe (or if you are doing a release build, YourProjectDir\bin\release\Program.exe)
  • The current working directory for Visual Studio 2008’s devenv.exe process.
    • Ok, so if Visual Studio 2008 was launched by double-clicking the the solution file, the working directory is the directory the solution file is in.
    • If you open Visual Studio using the Start | All Programs | Microsoft Visual Studio 2008 | Launch Microsoft Visual Studio 2008 shortcut, then the working directory is “C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\” (or the equivalent 32 bit path).

Ok, so it will check relative to the Project directory without putting in a macro if I open Visual Studio by double-clicking the the solution file. I can work with that.

So if I have an Install directory that contains the Program.exe and if I open Visual Studio by double-clicking the the solution file, I can put this in the Start external program:

Start external program:    Install\Program.exe

I left the Working directory blank.

It worked!

To bad if I ever forget to open by double-clicking the the solution file, and I instead use the shortcut it doesn’t work.  But no biggie, I can close and re-open correctly.

What else did I try?

I thought that if I added a relative path, it would check there.  So I should be able to put something like this:

Start external program:   Program.exe
Working Directory:    Install

But the relative path doesn’t work the same way.  Anything put there is only relative to YourProjectDir\bin\debug (or if you are doing a release build, YourProjectDir\bin\release), so this didn’t work.

I tried to use environment variables, but they didn’t work either.

I tried Macros, they didn’t work either.

I tried this:

Start external program:   Program.exe
Working Directory:    ..\..\..\Install

Nope, that didn’t work.

So what is the working directory when debugging/running from Visual Studio 2008?

I loaded up a project with an Install directory and debugging set to run the executable from the install directory.  I added this line to the program and put a break point on it:

string workingDirectory = Directory.GetCurrentDirectory();

The working directory appears to remain this:

YourProjectDir\bin\debug\ (or if you are doing a release build, YourProjectDir\bin\release\)

Oh well.

In a few weeks I am going to try Visual Studio 2010 and I will have to check if they improved this.

A snippet for handling each native type in C# and Visual Studio…when generics won't work.

So sometimes you have to have a function that can do something to any native type.

Below are two snippets to speed up the coding for you.

Ok, so of course there are times when you can use Generics.

public class myclass<T>
{
	myclass(T inT)
	{
		// your class
	}
}

However, there are functions that don’t work with a generic type T.

public class myclass<T>
{
	myclass(T inT1, T inT2)
	{
		if (inT1 < inT2)
		{
			// do something
		}
	}
}
&#91;/sourcecode&#93;

This results in an error:   Error 1 Operator '<&#39; cannot be applied to operands of type &#39;T&#39; and &#39;T&#39;.

Maybe you need to handle all the native data types.  So it is annoying to type them in, so I created an iftype snippet.

Create a file called iftype.snippet in this directory: C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#\
Copy in this source and save the file.

&#91;sourcecode language="csharp"&#93;
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>iftype</Title>
			<Shortcut>iftype</Shortcut>
			<Description>Code snippet for an automatically implemented an 'if' statement for each native type.</Description>
			<Author>Jared Barneck</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>varName</ID>
					<ToolTip>Variable name</ToolTip>
					<Default>t</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><!&#91;CDATA&#91;
				if ($varName$.Equals(typeof(bool)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Byte)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Char)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(DateTime)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Decimal)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Double)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Int16)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Int32)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Int64)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(SByte)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(Single)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(String)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(TimeSpan)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(UInt16)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(UInt32)))
                {
					throw new NotImplementedException();
                }
                else if ($varName$.Equals(typeof(UInt64)))
                {
					throw new NotImplementedException();
                }
$end$&#93;&#93;>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

However, you prefer a switch statement to an if statement. Here is the same thing using the switch statement.

Create a file called switchtype.snippet in this directory: C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#\
Copy in this source and save the file.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>switchtype</Title>
			<Shortcut>switchtype</Shortcut>
			<Description>Code snippet for an automatically implemented a switch statement for each native type.</Description>
			<Author>Jared Barneck</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>a
			<Declarations>
				<Literal>
					<ID>varName</ID>
					<ToolTip>Variable name</ToolTip>
					<Default>varName</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><!&#91;CDATA&#91;
			Type t = $varName$;
            switch (t.ToString())
            {
                case "System.Boolean":
                    throw new NotImplementedException();
                    break;
                case "System.Byte":
                    throw new NotImplementedException();
                    break;
                case "System.Char":
                    throw new NotImplementedException();
                    break;
                case "System.DateTime":
                    throw new NotImplementedException();
                    break;
                case "System.Decimal":
                    throw new NotImplementedException();
                    break;
                case "System.Double":
                    throw new NotImplementedException();
                    break;
                case "System.Int16":
                    throw new NotImplementedException();
                    break;
                case "System.Int32":
                    throw new NotImplementedException();
                    break;
                case "System.Int64":
                    throw new NotImplementedException();
                    break;
                case "System.SByte":
                    throw new NotImplementedException();
                    break;
                case "System.Single":
                    throw new NotImplementedException();
                    break;
                case "System.String":
                    throw new NotImplementedException();
                    break;
                case "System.TimeSpan":
                    throw new NotImplementedException();
                    break;
                case "System.UInt16":
                    throw new NotImplementedException();
                    break;
                case "System.UInt32":
                    throw new NotImplementedException();
                    break;
                case "System.UInt64":
                    throw new NotImplementedException();
                    break;
            }
$end$&#93;&#93;>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

How to process command line parameters or arguments in a WPF application?

UPDATE 10/25/2010:
Avoid using Environment.CommandLine. It appears much easier, but isn’t as robust. I learned a while ago that the command line arguments can be accessed using Environment.CommandLine. This is only different than the process below in that it is way easier and the first argument is the full path of the executable. So all this work is not exactly necessary, right? Wrong! I tried Environment.CommandLine for a while and it didn’t last. There are times when this executable is launched by another executable and the Environment.CommandLine is not set even though the other executable launched this executable with parameters. So I had to return to using the steps below anyway.


Ok, so I wanted to handle command line parameters, which is easy in every other language, however, the need for easy was overlooked in WPF. It is not obvious and you are not going to figure it out without being told how to do it.

Microsoft provides a sample here, you can look at.
http://msdn.microsoft.com/en-us/library/aa972153.aspx

I am going to walk you through creating a new WPF Project in Visual Studio 2008. Then I will walk you through handling command line parameters (arguments).

  1. Open Visual Studio 2008.
  2. Go to File | New | Project.
  3. Under Visual C#, choose WPF Application and give the project a name and then hit OK.
  4. Go to Project | ProjectName Properties (where ProjectName is the name of your project).
  5. In the Properties of you project, click on Debug.
  6. Enter three parameters intothe Command line arguments text field: Param1 Param2 Param3
  7. Close the properties window.
  8. Double-click on App.xaml to open it. It looks like this:
    <Application x:Class="ParametersForWPF.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="Window1.xaml">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    
  9. Add a carriage return after StartupUri=”Window1.xaml” and start type inside the bracket the word Startup=. As soon as you see an equals sign you will get a pop up with the words . Double-click on that. The name Application_Startup will automatically be added.
    <Application x:Class="ParametersForWPF.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="Window1.xaml"
        Startup="Application_Startup">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    

    Note: This will also automatcially update the App.xaml.cs file which originally looks as follows:

    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
        }
    }
    

    But after adding the Startup=”Application_Startup” line, a function called Application_Startup is automatically added.

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
    
            private void Application_Startup(object sender, StartupEventArgs e)
            {
    
            }
        }
    }
    
  10. Now we only want to work with arguments if there are some, so lets add an if statement inside the Application_Startup function as shown:
            private void Application_Startup(object sender, StartupEventArgs e)
            {
                if (e.Args.Length > 0)
                {
    
                }
            }
    
  11. Ok, so the next step is to create a public static string[] member variable to hold the arguments and assign the arguments array to it. I called my member variable mArgs. I use prefix it with m so I know it is a member variable.
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Windows;
    
    namespace ParametersForWPF
    {
        /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
            public static String[] mArgs;
    
            private void Application_Startup(object sender, StartupEventArgs e)
            {
    
                if (e.Args.Length > 0)
                {
                    mArgs= e.Args;
                }
            }
        }
    }
    
  12. Now, in order to access the data in Windows1.xaml.cs, just call the App.mArgs array in the constructor as shown.
            public Window1()
            {
                InitializeComponent();
                String[] args = App.mArgs;
    
            }
    
  13. Put a break point on the line and start with debugging and sure enough you will see your arguments properly assigned to the String[] args variable. So you now have your parameters accessible in your WPF application.Hope this helps you.

    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.

How to modify the default new class template for C# in Visual Studio 2008 or 2010?

Updated: 5/17/2010 using information aquired from here: How To: Edit Visual Studio Templates

Ok, so I don’t like the way that the default new class template in Visual Studio 2008/2010 looks. I end up typing a lot of things over and over again.

Here is what it a new class looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyNameSpace
{
	class MyClass
	{
	}
}

Here is what I want it to look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyNameSpace
{
	public class MyClass
	{
		#region Member Variables
		#endregion

		#region Constructors

		/// <summary>
		/// The default Constructor.
		/// </summary>
		public MyClass()
      		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

So making this change is easy to do. All you have to do is edit a text file that is compressed.

Copy the zip file file located here to the desktop:
Visual Studio 2008

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Visual Studio 2010

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Extract the zip file.

Using a text editor, open the Class.cs file.

The file will have the following text:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	class $safeitemrootname$
	{
	}
}

Change it to have this text:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;

namespace $rootnamespace$
{
	public class $safeitemrootname$
	{
		#region Member Variables
		#endregion

		#region Constructors

		/// <summary>
		/// The default Constructor.
		/// </summary>
		public $safeitemrootname$()
		{
		}

		#endregion

		#region Properties
		#endregion

		#region Functions
		#endregion

		#region Enums
		#endregion
	}
}

Save the file.

Rebuild the zip file with the new Class.cs.  Be careful to build the zip file correctly.

Copy the new zip file back here and overwrite the existing one:
Visual Studio 2008

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Visual Studio 2010

  • For 64 bit: C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
  • For 32 bit: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Now, you have to rebuild the template classes.  To do this:

  1. Open a command prompt as Administrator.
  2. Change to the appropriate directory:
    Visual Studio 2008
    64-bit

    cd C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\

    32-bit

    cd C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

    Visual Studio 2010
    64-bit

    cd C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\

    32-bit

    cd C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\
  3. Run this command:
    devenv.exe /installvstemplates

Now any new class you create will have your new format.


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.

How to compile a wxWidgets application in Visual Studio 2008?

Step 1 – Install Visual Studio 2008

  1. If you don’t have it, get the express edition here: http://www.microsoft.com/Express/VC/
  2. Run through the installer, not much else to do.

Step 2 – Install wxWidgets

  1. Download wxWidgets (select the wxMSW installer file) from here:
    http://www.wxwidgets.org/downloads/
  2. I choose to install to c:\dev\wxwidgets\wxWidgets-2.8.10 but you can choose a different path if you want.

Step 3 – Create an environment variable for the wxWidgets path.

  1. Click the Start icon.
  2. Right click on Computer and choose Properties.
  3. Click Advanced system settings.
  4. Click the Environment variables button.
  5. Under System Variables, click New.
  6. Enter the Variable name: WXWIN
  7. Enter the Variable Value: C:\Dev\wxWidgets-2.8.10
  8. Click OK, click OK, click OK (yes three times).

Step 4 – Compile the wxWidgets Libraries.

  1. Browse to the following folder: C:\Dev\wxWidgets-2.8.10\build\msw
  2. Located the file called wx.dsw and open it with Visual Studio. (I just double-clicked on it.)
  3. Choose “Yes to all” when Visual Studio prompts you to convert the project.
  4. Build the project.
  5. Wait for the build to complete. It took approximately two minutes on my Lenovo T61p (dual core, 4 GB, Windows 7 64 bit). You should a line like this when it finishes successfully.
    ========== Build: 20 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
  6. Close Visual Studio.

Step 5 – Create a new project

  1. In Visual Studio 2008, go to File | New Project.
  2. Select Visual C++ | Empty Project.
  3. Give the project a name and click OK. I named this wxTest.

Step 6 – Create/Copy your source to this project.

  1. Right-click on the Project name and choose Open Folder in Windows Explorer. This will open to the home folder of your project. (Don’t right click the Solution name, make sure to right click the project under the solution name.)
  2. Open a second Windows Explore window.
  3. In the second window, browse to the wxWidgets sample directory and open the Minimal folder: C:\Dev\wxWidgets-2.8.10\samples\Minimal
    Note: You can choose other projects but you may want to start with Minimal and move on from there.
  4. Copy only the minimal.cpp and minimal.rc files to your project directory (the rest are not needed).
  5. Close the second window pointing to the C:\Dev\wxWidgets-2.8.10\samples\Minimal directory, it is not needed anymore.
  6. From the explorer window open to your project directory, use ctrl+click to highlight both the minimal.cpp and minimal.rc files.
  7. Drag both highlighted files into the Visual Studio Window and drop them over the project name.
    The minimal.cpp file should automatically be placed under the Source files section of your project.
    The minimal.rc file should automatically be placed under the Resource files section of your project.

Step 7 – Customize the project properties

  1. Right-click on the wxTest project and select Properties. (Don’t right click the Solution name, make sure to right click the project under the solution name.)
  2. In the top left of the properties window there is a Configuration drop down menu. Select All Configurations.
  3. Click to expand Configuration Properties.
  4. Click to expand C/C++.

    Note: If you don’t see a C/C++ section, then you don’t have any source files.  You need at least one C++ source file for this section to show up.

  5. Click to highlight General.
  6. Enter the following in Additional Include Directories.
    $(WXWIN)\include;$(WXWIN)\lib\vc_lib\mswd
  7. Click to highlight Preprocessor.
  8. Enter the following in Preprocessor Definitions.
    WIN32;__WXMSW__;_WINDOWS;_DEBUG;__WXDEBUG__
  9. Click to expand Linker.
  10. Click to highlight General.
  11. Enter the following in Additional Library Directories.
    $(WXWIN)\lib\vc_lib
  12. Click to highlight Input.
  13. Enter the following in Additional Dependencies.
    wxmsw28d_core.lib wxbase28d.lib wxtiffd.lib wxjpegd.lib wxpngd.lib wxzlibd.lib wxregexd.lib wxexpatd.lib winmm.lib comctl32.lib rpcrt4.lib wsock32.lib odbc32.lib

    Note: Not all of these libraries are required for this project, however, I list all of these because you may use some of them at some point. If you don’t think one is needed, remove it and recompile and if you don’t get errors, you were right, you probably didn’t need it.

  14. Click to expand Resources. (If you don’t see a Resources option, then you don’t have any files under resources so that is normal. Did you skip Step 5 because you probably should have added a resource in Step 5.)
  15. Click to highlight General.
  16. Enter the following in Preprocessor Definitions.
    _DEBUG;__WXMSW__;__WXDEBUG__;_WINDOWS;NOPCH
  17. Enter the following in Additional Include Directories.
    $(WXWIN)\include;$(WXWIN)\lib\vc_lib\mswd

You are now ready to build your wxWidgets application using Visual Studio 2008 on Windows 7.

Build your project and if you get any errors, go through it again, you probably missed a step (or I did, since I have already been caught with one step left out).


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.