Archive for November 2010

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.

Playing DOS games on FreeBSD

I don’t know if many of you remember my post on old DOS games and how easy it is to play them using DOSBox.  Well, it may not surprise you that you can easily install DOSBox on FreeBSD. And yes, on FreeBSD you can play all your favorite old DOS games.

Of course, I assume you have a FreeBSD desktop.

Installing DOSBox on FreeBSD

To install from ports, do this:

#
#
cd /usr/ports/emulators/dosbox
make install

To install from packages do this:

# pkg_add -r dosbox

Configuring DOSBox on FreeBSD

Create a folder, probably in your home directory but it can be where ever you want, to store your DOS games.

# mkdir ~/Games/dos

The configuration file is in your home director: ~/.dosbox/dosbox-0.74.conf

Add the following line to the end of the config under the [autoexec] section.

# echo mount c /usr/home/username/Games/dos/ >> ~/.dosbox/dosbox-0.74.conf

Note: Make sure you have hte trailing slash ‘/’ as the path you mount to must end in a slash.

Running DOSBox on FreeBSD

DOSBox installs to /usr/local/bin/dosbox which is in $PATH so you can run DOSBox at anytime by simply typing in dosbox in a shell.

However, you can create an entry for it in KDE’s menu if you want.

DosBox

Now before you go on, type in intro and read each page as you will get lots of important information about how to use DOSBox in the intro.

C:\> intro

Now make sure to read these pages. They tell you how to go full-screen, capture/release your mouse, etc…

Downloading DOS Games

As mentioned in my previous post about DOS games, you can go here to this cleverly named site to download a lot of DOS games.

Abandonia

Loading a DOS Game

It is just like DOS.  Change to the directory where your game is and run the games exe file.

For example, if you downloaded The Bard’s Tale II: The Destiny Knight, you would type the following:

Z:\> c:
C:\> cd BARD\BARD2
C:\BARD\BARD2> DK.EXE

And your game is launched.

Have fun.  It would takes years to play all the old DOS games at Abandonia.

FreeBSD or Linux

Ok, so if you have been on my site, you know that I started with Red Hat and never really got into it, and then, settles on FreeBSD.  Why would I choose FreeBSD over Linux? It fit me better.

I actually think that everybody needs to use what suits them.

This is NOT a FreeBSD versus Linux post.  It is a site to help others who are trying to decide whether to use FreeBSD or Linux see some pros and cons and get my recommendation.

FreeBSD

FreeBSD is not Linux or Unix exactly.  It is BSD. It has its own bsd kernel and an is surrounded by a base system.

Here are a list of positives about FreeBSD

  • It is open to proprietary code that just can’t be used in Linux, such as Sun’s ZFS.
  • It is easy to get a small install of just the base system with minimal to no features installed. (Security! Attach surface area is minimized when less software is included.)
  • Jails
  • The ports tree for compiling from source is unmatched by any Linux operating system, but if you prefer binaries, yes, it has them too.
  • Installing software has less problems as you compile it on the system, with the settings you need (rather than get binaries that may have been compiled for a different system or without the settings you need).
  • The documentation is far better than most other open source projects and better than most projects commercial or open source for that matter!
  • OS X chose to use much of FreeBSD in its underlying operating system and so when combining the OS X and FreeBSD market share, FreeBSD code is actually used on more systems than any operating system other than Windows.
  • There are not that many BSD distributions, and the ones that exist have clear focusses different than the others, that later they share.  FreeBSD is a solid server. PC-BSD is a desktop focussed on avoiding dependency problems with its software. OpenBSD is extremely securee. NetBSD is extremely compatible with lots of hardware.  They contribute back to each other often.
  • The License is free and gives everyone who uses it true freedom.
  • The License is free for commercial use.
  • Easy Editor. Newbies can actually use this editor included in the FreeBSD base system.  Don’t forget to learn vi though.
  • Patching is as simple as running freebsd-update.

Here are a list of negatives about FreeBSD

  • Hardware companies tend to make drivers for Windows and Linux first and often don’t include FreeBSD, though most hardware is soon supported.
  • There is not a native Flash Player in FreeBSD, instead the Linux version of Flash must be used.
  • There Desktop options for FreeBSD are not as rich as those for Linux (Example: KDE network settings doesn’t work on FreeBSD, but PC-BSD has their own settings now.)
  • IT/Developers forFreeBSD are harder to come by.

Linux

Linux was originally just a kernel.  The userland was separate.  Now there are plenty of projects that make a nice complete operating system using the Linux kernel and a nice base system surrounding it.

Here are a list of positives about Linux

  • It has a large user base.
  • Free to use.
  • There are plenty of distros to choose from.
  • It is no longer just a kernel but many different groups put out an actual system: Red Hat/Fedora, Debian/Ubuntu, CentOS, SUSE, Arch, Gentoo, etc…
  • A lot of work is going into the desktop environment
  • Development for any Linux platform could benefit all Linux platforms.
  • More and more hardware companies are including Linux drivers
  • Some Software companies make Linux software as well, and the number is increasing
  • Strong commercial backing (which doesn’t make sense for software licensed under the GPL)

Here are some negatives

  • There is often a lot of binary packages that just don’t work.
  • Lack of consolidation.  There are a lot of distributions of Linux and they are not the same. Which one do you choose.
  • Many Linuxes (not all) are now installing desktop software by default, and no longer are minimalistic. (Security! Attach surface area is increased when more software is included.)
  • The inability to write and distribute software that touches GPL software, without having to release your software as GPL too.
  • If you hope to do anything other than use the software or help the community, you need a lawyer to figure out how to interact with the various versions of GPL.
  • The security settings are usually not easy to use and are result in users just turning them off (i.e. SELinux)
  • Are Red Hat and SUSE open source or commercial, they sell support but the software is free, except you can’t get updates without buying support…confusing!
  • IT guys who claim to know Linux usually have done little more than run Ubuntu for a few days.

This is not a flame post and any responses that appear to be trolls will be deleted.

My recommendations

Ok, so what would I recommend if I were paid by a company for consulting?

Server (LAMP)

For a Server running Apache, PHP, SQL, often mis-termed LAMP (Linux Apache MySQL PHP) but really means any OS, Web Server, SQL, Script language.

Recommended OS: FreeBSD

Commerical Appliance

If you work for a company and you need a commercial appliance. Stay away from the dangers of the GPL, just don’t go there.

Recommended OS: FreeBSD

Open Source Desktop

For a quick desktop for a home user that has PC hardware but doesn’t have a license for Windows and doesn’t want to buy one.

Recommended OS: Ubuntu

Note: Sorry PC-BSD friends. Keep working on it.

Commerical Desktop for Employees

If you want a good commercial desktop, you should go with one of the following depending on certain factors, the primary being that some software you may need to use only runs on these two platforms.

Recommended OS: Windows 7 or OS X

However, Ubuntu, Red Hat, SUSE, Fedora, PC-BSD, are all very usable replacements depending on the situation.

Point of Sale (POS) Device

If you need to have to have a POS device for handling sales.

Recommended OS: Depends on needs

Share your thoughts

Hey, please comment.  No flame wars though.  I repeat, this is not a FreeBSD versus Linux post, but a FreeBSD or Linux post, with just some information from my experience. I appreciate all technology and any rude comments will be deleted.  However, feel free to challenge and provide facts, demand facts, etc…

Creating or opening a password protected zip file on FreeBSD

So this works on FreeBSD but it probably works on OS X, most Linuxes, Solaris, and other Unixes as well.

Installing prerequisites

In order to create a password protected zip file and later open it, two ports are needed:

  • zip
  • unzip

To install these using packages, do this as root:

#
#
pkg_add zip
pkg_add unzip

Or using ports:

#
#
#
#
cd /usr/ports/archivers/zip
make install
cd /usr/ports/archivers/unzip
make install

Creating a password protected zip file

There are a couple of different ways you may want to create a zip file. You may want to zip a sing file, or two or more files, or and entire directory and all its contents. You may also want to add a file to an existing zip file.

All of these actions can be done with a binary called zip.

Example 1 – Creating a password protected zip file containing one file

The syntax is simple. The -e parameter is to encrypt with a password. Always put the zip file first and the file to be zipped second.

# zip -e myarchive.zip myfile1

Example 2 – Adding a file to your password protected zip file

Since your zip file already is encrypted with a password and adding a file does not require decrypting, you don’t need the password to add a file to the zip file.

# zip myarchive.zip myfile2

Example 3 – Creating a password protected zip file containing multiple files

This is very similar to Example 1. The -e parameter is to encrypt with a password. Always put the zip file first and the files to be zipped last separated by a space.

# zip -e myarchive.zip myfile1 myfile2 myfile3

Example 4 – Creating a password protected zip file containing a directory and all is contents.

The -r parameter is to do a recursive zip (recursive means to include the folder and all its contents). The -e parameter is to encrypt with a password. Always put the zip file first and then the directory name.

# zip -r -e myarchive.zip mydirectory

Example 5 – Delete a file from the zip

This is easier than you think. Because you are not actually reading the contents of a file in the archive, the password is not needed to delete a file inside the zip file.

# zip -d myarchive.zip myfile1

Opening a password protected zip file

The syntax for unzipping a file is a lot easier.  It uses a different binary file called unzip.

# unzip myarchive.zip

The above prompts for the password automatically and unzips the files, assuming the correct password is provided.

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

Making a package from a port on FreeBSD

Some times is it the simple things that people don’t know. For example, I have always just installed software from ports. Every now and then I would use pkg_add -r to pull a pre-made package from a FreeBSD package server. But I have never actually made a package myself. I have been using FreeBSD for 10 years and many consider me an expert in some areas.  Well, like I always say, it is possible to be an expert in many areas and still be a newbie in some areas.

Recently, I am looking into steps to make a BSD appliance and so I want to keep the system as minimal as possible. So I want to build packages on on a separate build box. So I suddenly realized that I have never made a package myself and I wasn’t exactly sure how.

So is it hard to convert a port into a package? Of course not. If you want to make a package from a port, and you are familiar with ports already, then all you have to do is run make package, and you may want to make the dependent packages as well.

If you need some more granular steps, I will provide them. You just need to follow some simple steps:

FreeBSD make package

Lets assume you want to install lighttpd.

  1. Download the latest ports tree. See this article: How to install ports on FreeBSD?
  2. Search for the port you want.
    #
    #
    cd /usr/ports
    make search name=lighttpd

    The output should look as follows:

    Port: lighttpd-1.4.28_4
    Path: /usr/ports/www/lighttpd
    Info: A secure, fast, compliant, and very flexible Web Server
    Maint: mm@FreeBSD.org
    B-deps: libtool-2.2.10 pcre-8.10 pkg-config-0.25_1
    R-deps: pcre-8.10
    WWW: http://www.lighttpd.net/
  3. Look at the R-Deps. R is short for Run and deps is short for dependencies. If you want a package for lighttpd, it requires pcre-8.10 to run, so you will need a package for pcre-8.10 as well.
    Note: B-deps are not need. B is for Build. These dependencies are only need to build the package.  Once the package is built, they are not needed, so you don’t need to create packages for them.
  4. Make the lighttpd package:
    #
    #
    cd /usr/ports/www/lighttpd
    make package
  5. This creates the file in the /usr/ports/www/lightpd. You may have a directory or share where you store your packages, and you can copy it there if you want. Especially if this is a build machine in a vm that you plan to revert, you need to copy this off the machine or you will lose it when you revert.
  6. Make the pcre package.
    #
    #
    cd /usr/ports/devel/pcre
    make package
  7. This creates the file in the /usr/ports/www/lightpd. You may have a directory or share where you store your packages, and you can copy it there if you want. Especially if this is a build machine in a vm that you plan to revert, you need to copy this off the machine or you will lose it when you revert.

Hopefully this helps you if you ever need to make your packages on one box.

This is also something great to do before an install fest so you can have the latest packages available. Lets say you want to do an install fest for a FreeBSD desktop, you could have all the latest Xorg and Fluxbox or KDE or GNOME packages already built.

Build machine notes
On your build machine “make package” will actually install the package in the process of building the package. However, that is not really a concern as this is a build machine. My recommendation is that you create a build machine in VirtualBox and snapshot it after you download ports. Usually you just continue making packages. When you decide it is time to go back to a clean system, 1) revert your snapshot, 2) update your ports tree, 3) make your new packages.

A simple fix when /tmp is too small and you can’t download a file in Firefox

Firefox Problem

Recently using my FreeBSD desktop, I was unable to download a file in Firefox.

There is not enough room on the disk o save /tmp/IVpWYcrD.exe.part.

Remove unnecessary files from the disk and try again, or try saving in a different location.

So I got this as soon as I tried to download a file. It said there wasn’t enough space to download the file and recommending a different location, however, this error was before I even chose a download location.

Cause

So it appears it starts downloading immediately to /tmp, but since I installed FreeBSD without giving /tmp its own partition, it was dumped in the root partition, which doesn’t have much space.

Here are the partitions I have created.

[jared@slc-jab ~]$ df -aH
Filesystem            Size    Used   Avail Capacity  Mounted on
/dev/label/rootfs0    520M    259M    219M    54%    /
devfs                 1.0k    1.0k      0B   100%    /dev
/dev/label/var0       1.0G    164M    791M    17%    /var
/dev/label/usr0       143G     80G     51G    61%    /usr
procfs                4.1k    4.1k      0B   100%    /proc

So using Firefox as soon as I try to download anything over 219 MB, it would fail.

My first bad idea to fix this (Don’t do this!)

So the fix seemed simple. However, while this resolved the Firefox issue, this fix caused some problems with Xorg and KDE.

As root, I did this:

rm -fR /tmp
mkdir /usr/tmp
chmod 1777 /usr/tmp
ln -s /usr/tmp /tmp

I made sure that the /usr/tmp permissions look as follows: rwxrwxrwt. Yes, that is supposed to end with a ‘t’. Read this for more info: http://www.freebsd.org/doc/handbook/permissions.html

If you screw up your permissions for the /usr/tmp file, Firefox will likely let you know with the following error.

/tmp/LDVDKpa.exe.part could not be saved, because you cannot change the contents of that folder.

Change the folder properties and try again, or try saving in a different location.

So I got the permission issue fixed and then rebooted to try to fix the fact that no other windows would open because I switched the /tmp directory while in X and after that none of my windows would open.

However, when I rebooted, I got this error with kdm and it kdm didn’t start:

Nov  9 09:07:12 slc-jab kdm_greet[1576]: Cannot create $HOME
Nov  9 09:07:12 slc-jab kdm-bin: :0[1575]: Received unknown or unexpected command -2 from greeter
Nov  9 09:07:12 slc-jab kdm-bin: :0[1575]: Abnormal termination of greeter for display :0, code 1, signal 0

I tried to fix the KDE issue, but it seemed to be caused by the fact that /tmp was a link because /usr/tmp had proper permissions but still it didn’t seem to work.

My second bad attempt

I spent hours trying to find a way to change the temp directory in about.config and thought I had it with browser.cache.disk.parent_directory but alas, it never worked.

  1. Leave /tmp as it is.
  2. Create another temp directory:
    mkdir /usr/tmp
  3. Give it the correct permissions.
    chmod 1777 /usr/tmp
  4. Open Firefox.
  5. For the URL type: about:config
  6. Add a new string
    Name: firefox
    Value: /usr/tmp
  7. Restart Firefox.

My third attempt

I tried to create a TEMP environment variable.  In fact, if Firefox is launched from a shell with TEMP specified as ~/.tmp then it works.  However, when the KDE Menu launches Firefox, it never has that environment variable. I added the environment variable to .profile, .cshrc, and rebooted, but it never worked.

Resolution

I added this line to my /etc/fstab file and rebooted. That took care of it. Supposedly tmpfs is experimental, but it is working great.

tmpfs                   /tmp                    tmpfs           rw,mode=1777    0       0

Anyway, I hope this information helps you if you see this issue.

Installing Windows 7 into a virtual machine on FreeBSD using VirtualBox

My job at LANDesk requires that I write code in C# for an application that only runs on Windows Server.  I also have to test a lot of code on Windows 7. Like me, so many people are forced to run a version of Windows because they have special windows applications at work or because that is the platform we are developing for in our jobs.

If running windows is a must for you, as it is for me, then moving to FreeBSD exclusively is just not an option.  I want to run an FreeBSD, but running Windows 7 is a must too.

At first VMWare Workstation looked like it was going to solve this problem. But while its early versions worked on FreeBSD, they failed to port newer versions over.  Quemu just never could get to level of usability needed.  Well, along comes VirtualBox from Sun.  Sun, now Oracle, released an open source edition cleverly named VirtualBox Open Source Edition (OSE).  Like many of Sun’s code, it is duel licensed.

Prerequisites

  1. A FreeBSD desktop – Hopefully you are here because you already have this.  If you don’t have a FreeBSD desktop, you can follow my guide to build one.
    How to install and configure a FreeBSD 8 Desktop with Xorg and KDE?
    Or you can install and use PC-BSD which is a nice desktop version of FreeBSD.
  2. A Windows 7 DVD or ISO and a product key.  Please do not pirate!

Step 1 – Installing VirtualBox OSE on FreeBSD 8.1

Installing VirtualBox is not complex. It involves only a few steps.

  1. Go to the directory for virtualbox-ose in your ports tree.
    # cd /usr/ports/emulators/virtualbox-ose
  2. Configure your installation.
    # make config
  3. Select Guest Additions, as it is not selected by default.
    Note: The defaults are Qt4, DBUS, X11, NLS and they should remain checked.
  4. You may also want to select VNC.
  5. Install virtualbox-ose
    # make install

Step 2 – Configuring FreeBD for Virtual Box

There are few things we need to configure on the FreeBSD system to make VirtualBox work.

  1. Add users to the vboxusers.
  2. Configure CD/DVD drive access.
  3. Configure VirtualBox kernel modules to load.

Step 2.1 – Adding use to the vboxusers group

  1. To add users to the group, use this command:
    FBSD# pw groupmod vboxusers -m SomeUserName

Step 2.2 – Configure CD/DVD drive access

Note: This is a copy of what is in my document for building a FreeBSD Desktop.

FreeBSD is more secure by default, so something as simple as accessing a CD or DVD or USB drive is not actually allowed by default. You have enable this.

These steps assume that your user is a member of the operator group. Remember above during the installation, I mentioned to make your user a member of both the wheel and operator groups.

  1. Access a shell and su to root.
    Note: The easiest shell to access now that you are in KDE is Konsole. To access Konsole, click the K and go to Applications | System | Terminal. Also you can add the shell icon to your panel by right-clicking on the icon and choosing Add to Panel.
  2. Enable vfs.usermount.
    FBSD# sysctl -w vfs.usermount=1
  3. Configure vfs.usermount to be enabled on boot.
    FBSD# echo vfs.usermount=1 >> /etc/sysctl.conf

  4. Open the following file with an editor: /etc/devfs.conf
    FBSD# ee /etc/devfs.conf

  5. Add the following lines:
    # Allow all users to access CD’s
    perm /dev/acd0 0666
    perm /dev/acd1 0666
    perm /dev/cd0 0666
    perm /dev/cd1 0666# Allow all USB Devices to be mounted
    perm /dev/da0 0666
    perm /dev/da1 0666
    perm /dev/da2 0666
    perm /dev/da3 0666
    perm /dev/da4 0666# Misc other devices
    perm /dev/pass0 0666
    perm /dev/xpt0 0666
    perm /dev/agpart 0666
    perm /dev/uscanner0 0666

    Note: Yes, I copied these from a PC-BSD install’s version of this file.

    Note: Change to 0660 to only allow users in the operator group to mount drives.

  6. Edit the /etc/devfs.rules file.
    FBSD# /etc/devfs.rules

  7. Edit the following file: /usr/local/etc/PolicyKit/PolicyKit.conf
    FBSD# ee /usr/local/etc/PolicyKit/PolicyKit.conf

  8. Change the xml’s config section from this…
    <config version="0.1">
        <match user="root">
            <return result="yes"/>
        </match>
        <define_admin_auth group="wheel"/>
    </config>
    

    …to this:

    <config version="0.1">
            <define_admin_auth group="operator"/>
            <match action="org.freedesktop.hal.storage.mount-removable">
                    <return result="yes"/>
            </match>
            <match action="org.freedesktop.hal.storage.mount-fixed">
                    <return result="yes"/>
            </match>
            <match action="org.freedesktop.hal.storage.eject">
                    <return result="yes"/>
            </match>
    </config>
    
  9. Edit the following file with ee: ee /etc/fstab
    FBSD# ee /etc/fstab

  10. See if there is a line in the fstab for your CD/DVD-Rom. Comment out or remove the line for your /cdrom. I usually just comment it out by adding a # sign as shown:
    #/dev/acd0 /cdrom cd9660 ro,noauto 0 0
  11. Restart the computer.

You should now be able to mount CD, DVD, and USB drives. You also should be able to both read and write to them, burn disks, write and format USB drives, etc…

Step 2.3 – Configure VirtualBox kernel modules to load

  1. As root, edit the /boot/loader.conf file.
    # ee /boot/loader.conf
  2. Add the following text:
    # VirtualBox
    vboxdrv_load=”YES”
  3. Save and close the file.
  4. Edit the /etc/rc.conf file.
  5. Add the following text.
    # VirtualBox
    vboxnet_enable
  6. Save and close the file.

Step 3 – Creating your Windows 7 VirtualBox

  1. Launch Virtual Box.
    Note: VirtualBox registers itself with the KDE menu.  On my installation, it was in Lost & Found, but on PC-BSD it was under System.  Either way you can type VirtualBox in the KDE menu search and find it.  Also, VirtualBox is the command and it should in $PATH so you should be able to open any shell from your desktop environment and run VirtualBox and have it open.
  2. Click New. This brings up a Wizard.
  3. Follow the wizard.
    Ok, if you need help with the wizard, here are my steps.
  4. Read and click Next.
  5. Choose an easy name.  I used “W7”.
  6. Make sure the Operating System is set to Microsoft Windows.
  7. Change the Version to Windows 7 (64-bit) or if you are on 32 bit hardware still use just Windows 7.
  8. Click Next.
  9. Allow at least 1536 MB (1.5 GB) for the base memory size.  You can get away with less if you need to. You can do better with more if
  10. you want to.
  11. Click Next.
  12. The Virtual Hard Disk page is already configured correctly, Boot Hard Disk is checked and Create new hard disk is selected. So just click next.
  13. Read and click Next.
  14. For Hard Disk Storage Type, I left it set at Dynamically expanding storage.
    Comment: This means that even if you use a 100 GB drive, it will only physically use as much space as Windows 7 has used in the Virtual Drive. So if Windows 7 is using 10 GB, even if you have 100 GB drive, the physical size on disk is only 10 GB.  This is important information for the next screen.
  15. Click Next.
  16. I change the drive size to 50 or 100 GB.
    Comment: It doesn’t really matter, but it is best to not run out of space either virtually or physically. Read my comment in the previous step.
  17. Click Next.
  18. Read and click Finish.

You virtual Machine now shows in the list.

Lets move to the next step.

Step 4 – (Optional) Changing Settings on your Windows 7 VirtualBox

I make two changes to my Windows 7 virtual box. As noted above this is optional, but I like to do them.

  1. Click the settings.
  2. Click System.
  3. Change the boot order to be hard drive first.
    Note: I make this change because it annoys me it when I install and then reboot the machine after the install and it boots right back to the install media. So I make this change and the press F12 during boot to the CD once.
  4. Uncheck and get rid of the floppy. (Does anyone still use those?)

  5. Now click on Storage.
  6. Under the Storage Tree, select your optical drive.
  7. If you are using an ISO, change the CD/DVD Device to point to the ISO. If you are using a DVD, as I am, choose Host Drive.  My host drive says: Host Drive Optiarc DVD RW AD-7910A (cd0).  I assume everyone drive will show up slightly different, but should start with Host Drive.
  8. Click OK.

Your settings should be good to go.

Step 5 – Install Windows 7

Now it is time to install Windows 7.

Don’t pirate! Use a legal product key. Again, just because I like open source does not make me anti closed source. I am not a Microsoft hater and I would hope you aren’t either. Even if you are, that is no excuse for pirating.

  1. Insert the DVD into your DVD drive, unless you are using an ISO and have already connected it.
  2. Click the Start icon.
  3. A new installation window will popup.
    Important! You may get a lot of popups telling you about important tips for using VirtualBox. Take time to read them. If you don’t read them or don’t already know what they are telling you, you will wish you had read them.
  4. Click in the window and to have it take control of your mouse and keyboard.
  5. Press F12 to choose your boot option.
     

    Note: If you miss this, that is OK,  you can restart the VM and try to be quicker.

  6. Once you have pressed F12 in time, you will see the following screen. At this screen, press the letter next to DVD drive.
  7. Press a key when prompted to boot to the Windows 7 media.

Well, you are off to installing Windows 7.  Hopefully you can get Windows 7 installed on your own, cause I am not here to walk you through doing that. Don’t worry, the install media for Windows 7 should be easy enough for you to follow if this is your first time.

Once finished, you will be running Windows 7 on FreeBSD.

Step 6 – Install VirtualBox Guest Additions

Even though all the devices are virtual, drivers are still needed. VirtualBox guest additions installs most of these drivers as well as other features of VirtualBox.

  1. Log in to your Windows 7 install.
  2. Select Device | Install Guest additions.

    This will mount an ISO and start the installer for VirtualBox Guest Additions inside Windows 7.

  3. Click Run VBoxWindowsEditions.exe.
  4. Follow the wizard.
    Note: I use the default install location and I check the option to Use Direct 3D support.
  5. Reboot when prompted.

Step 7 – Install the sound card driver

The sound card driver must be installed. VirtualBox uses a virtual device representing the Realtek AC’97 sound card.

  1. Log back into Windows 7.
  2. Go to the following web site:
    http://download.cnet.com/Realtek-AC-97-Driver-Windows-Vista-Windows-7/3000-2120_4-10962344.html
  3. Download and install the Realtek AC’97 Driver.
  4. Reboot when prompted.

Your Finished

You now have Windows 7 running. Now you can have the great experience of using FreeBSD as your primary OS and load Windows 7 when you need something requires windows, like I do.

Sources:
http://wiki.freebsd.org/VirtualBox
http://forums.freebsd.org/showthread.php?t=18699
The virtualbox-ose port’s pkg-message

OpenBSD 4.8 release Nov 1, 2010

Another release…

Check out the new release of OpenBSD 4.8.

GUBUG: Let's start meeting again


I live in Utah. The BSD users group is called: The Greater Utah BSD Users Group (GUBUG).

Unfortunately, I haven’t really seen any activity with this group in years. Sometimes I feel like the only active BSD user Utah, though I know this is far from true. I met some great people at the Utah Open Source Conference.

So I am kicking GUBUG into gear! Lets have a restart of the GUBUG meetings!

Date: Nov 17, 2010
Time: 7:00 pm – 8:30 pm
WHERE: LANDesk Building (see map)

I created a Facebook Group and added this as an event. Please join the group and RSVP if you can make it.
http://www.facebook.com/event.php?eid=119773334748668

Topics:
1. Contacting past members
2. GUBUG web site
3. A BSD topic (To be determined)
4. New GUBUG goals.

It will just be a fun meeting, to get things started again.