C# (Mono) on FreeBSD

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

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

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

For more information:

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

For Licensing information:

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

Installing Mono

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

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

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

Compiling Hello World in Mono

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

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

Running a Mono Program

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

# mono hw.exe
Hello World

A Mono IDE: MonoDevelop

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

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

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

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

Is It Really Cross Platform

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

So here are the results of my quick tests:

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

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

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

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

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

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

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

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

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

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

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

No WPF

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

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


Oracle Installer: Wow, can you say poor and unprofessional

So I am installing the Oracle client for the first time in my life (Yes, there are still some geek things I haven’t done yet) and wow was I surprised at the poor quality of the installer.

Here is the ugly:

1. I start the install and immediate a big black Command Prompt window comes up.
2. Once it comes up, it tries to install to a c:\app\jbarneck folder. Really? You haven’t figured out C:\Program Files\Oracle yet?
3. I installed only Instant Client. I needed Administrator as well. On reinstall it installed a new second instance of the Oracle Client. No it didn’t work and I have reverted my VM to try again.
4. When you have gone through their wizard and it is time to start the install, you click Finish. Yes, you heard correctly, you click Finish to start. When the install finishes, there is a small line of text letting me know it was successful and a close button.
5. Then I have to go get some text file called a .ORA file and copy it myself.

Anyway. If it was an Open Source project it wouldn’t be this poor. This is something I would have expected in the NT 4.0 days.

So if this is the lack of enterprise quality that I can expect from Oracle, which is a very rich “enterprise”, I will continue to stay away and recommend others do the same.

All I can say is: Wow, Oracle! Get your act together.


FreeBSD Wireless – Configuring a wireless interface on FreeBSD 8.1

FreeBSD Wireless

FreeBSD has strong support for wireless devices. Here is a quick overview of how to manage wireless interfaces on FreeBSD.

Prerequisites

For Wireless access requires the following:

  1. A wireless interface card
  2. wpa_supplicant
  3. An Access Point

Note: In later of versions of FreeBSD, since 2008, wpa_supplicant was included in base. If you are running an older version of FreeBSD, then wpa_supplicant was a port.  So if you are on FreeBSD 8, you have wpa_supplicant.

To complete this guide, we will also use:

  1. A FreeBSD desktop environment.
  2. wpa_gui

Note: wpa_gui is not included in the base system but is found in ports.

Step 1 – Determine what wireless interface card you have

Some wireless cards are built into the kernel, and may already be loaded.  If you know what card you have, skip this step.

  1. First, we need to find out what wireless card you have. Run ifconfig and look at the network cards you have.  Then to see which one is your wireless card, compare them to the wireless kernel module list here:
    http://www.freebsd.org/releases/8.1R/hardware.html#WLAN

    $ ifconfig
    em0: flags=8843 metric 0 mtu 1500
            options=219b
            ether 00:1e:37:d0:91:cb
            media: Ethernet autoselect
            status: no carrier
    lo0: flags=8049 metric 0 mtu 16384
            options=3
            inet6 fe80::1%lo0 prefixlen 64 scopeid 0x3
            inet6 ::1 prefixlen 128
            inet 127.0.0.1 netmask 0xff000000
            nd6 options=3

    Notice in the above configuration, no wireless card was discovered. Here is an example of one with a wireless card.

    em0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
            options=219b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,TSO4,WOL_MAGIC>
            ether 00:1e:37:d0:91:cb
            media: Ethernet autoselect
            status: no carrier
    iwn0: flags=8843 metric 0 mtu 2290
            ether 00:1e:37:d0:91:cb
            media: IEEE 802.11 Wireless Ethernet autoselect mode 11g
            status: associated
    lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
            options=3<RXCSUM,TXCSUM>
            inet6 fe80::1%lo0 prefixlen 64 scopeid 0x3
            inet6 ::1 prefixlen 128
            inet 127.0.0.1 netmask 0xff000000
            nd6 options=3<PERFORMNUD,ACCEPT_RTADV>
  2. Most wireless cards are PCI devices.  Run pciconf to look for your wireless network card type. This outputs a lot of information, I have snipped my output to isolate only the information about the wireless PCI card.
    $pciconf -lv
    ...
    none1@pci0:3:0:0:       class=0x028000 card=0x10108086 chip=0x42308086 rev=0x61 hdr=0x00
        vendor     = 'Intel Corporation'
        device     = 'Intel Wireless WiFi Link 4965AGN (Intel 4965AGN)'
        class      = network
    ...
  3. Now go to the current release notes for FreeBSD and look through the wireless kernel modules to see which one supports your hardware.
    http://www.freebsd.org/releases/8.1R/hardware.html#WLAN

    Note: I searched for 4965AGN and found my kernel module immediately.
  4. Keep the link open as you move to Step 2.

Step 2 – Make sure the kernel module is loading

If your wireless card is already detected and loading, skip this step.  If not, configure /boot/loader.conf to load your wireless card.

  1. Read the man page for your wireless kernel module, there is a link to it in the hardware notes, to see any special information about loading the kernel module for your kernel module.
  2. Configure the /boot/loader.conf to load the kernel module and make any other required settings to use the kernel module.Example 1 – The Intel iwn kernel module requires a line to load the kernel module and a second line to load the firmware.
    # Wireless
    if_iwn_load="YES"
    iwn4965fw_load="YES"

    Example 2 – The Intel iwi kernel module requires that you accept a license agreement:

    # Wireless
    if_iwi_load="YES"
    legal.intel_iwi.license_ack=1
  3. Save and close the /boot/loader.conf
  4. Now you can either reboot, or you can use kldload to load the kernel modules without rebooting.

Step 3 – Configure the wireless settings in /etc/rc.conf

The rc.conf is where the wireless network card is configured.

  1. In FreeBSD 8 and later, all wireless interfaces should be configured to use the generic wlan device. Then to enable wpa_supplicant, the wlan should be configured to use WPA.
    To make these configurations, add these lines to the /etc/rc.conf.

    wlans_iwn0="wlan0"
    ifconfig_wlan0="WPA DHCP"
  2. Save and close /etc/rc.conf.

Step 4 – Add your Access Point’s (AP) SSID to your /etc/wpa_supplicant.conf

There is a lot of information on how to add an SSID to your /etc/wpa_supplicant.conf file in the man page for wpa_supplicant.conf. But the process is simple.

  1. If you don’t know the SSID, discover or scan for the SSID by running ifconfig wlan0 scan.  Below is an example.
    $ ifconfig wlan0 scan
    SSID/MESH ID    BSSID              CHAN RATE   S:N     INT CAPS
    MyWifi          00:20:e1:96:54:32    6   11M -75:-95  100 E
    OpenNet         da:ce:41:d3:af:3a    6   54M -85:-95  100 IS
    MyWPA           00:24:7b:6b:71:27    1   54M -89:-95  100 EP   RSN WPA WPS
                    00:00:00:00:00:00    1   54M -89:-95  100 E
  2. Now add a network entry for the desired wireless device.  Examples are below:

    Open or no authentication

    network={
            ssid="MyWifi"
            key_mgmt=NONE
    }

    WPA or WPA2

    network={
            ssid="MyWPA"
            psk="SomeP@sswd!"
    }

    More examples

    For more examples, read the man page for wpa_supplicant.conf.

    $ man wpa_supplicant.conf

    Once the SSID is configured properly in the /etc/wpa_supplicant.conf, then an automatic connection to this AP will occur whenever the device is within range.

Step 5 – Install wpa_gui from ports

Often you don’t always know what wireless you are going to connect to and also often you don’t care to store the SSID configuration permanently in the /etc/wpa_supplicant.conf. This is common if you are getting online at an airport, coffee shop, or any hotspot that you don’t frequent. It would be nice to have a graphical interface that shows you the SSIDs available, allows you to connect, but doesn’t store the information. wpa_gui is this tool.

  1. Install wpa_gui from ports
    # cd /usr/ports/net/wpa_giu
    # make install
  2. Add the following two lines to the top of the /etc/wpa_supplicant.conf.
    ctrl_interface=/var/run/wpa_supplicant
    ctrl_interface_group=wheel
  3. Restart the wpa_supplicant.# /etc/rc.d/wpa_supplicant restart wlan0
  4. Run wpa_gui.
    $ wpa_gui
    Selected interface 'wlan0'
    Trying to connect to '/var/run/wpa_supplicant/wlan0'

    wpa_gui opens.

  5. Click Scan and a window listing the available SSIDs appears.
  6. Double-click on an SSID to get the configuration windows.  It will try to select the correct settings as best it can, so often you only need to add the psk or passkey, which is essentially a password.
  7. This will connect you to that SSID.

Note: If you do want to save the networks to the wpa_supplicant.conf by default, then add this line. Otherwise, they are not saved. You may or may not want them to be saved.

update_config=1

Additonal Notes

Note 1: PC-BSD has a network configuration tool, so if you are running PC-BSD, wpa_gui is not necessary.

Note 2: There is a command line tool called wpa_cli that is included in the base system.  wpa_cli is useful if you don’t have a graphical environment.

Note 3: I also configured link aggregation, or lagg, so my wired and wireless interfaces share the same MAC.

ifconfig_em0="up"
ifconfig_iwn0="`ifconfig em0 ether`"
ifconfig_iwn0="ether ${ifconfig_iwn0##*ether }"
wlans_iwn0="wlan0"
ifconfig_wlan0="WPA"
cloned_interfaces="lagg0"
ifconfig_lagg0="laggproto failover laggport em0 laggport wlan0 DHCP"

Resources

http://www.freebsd.org/doc/handbook/network-wireless.html
http://www.freebsd.org/releases/8.1R/hardware.html#WLAN
man wpa_supplicant
man wpa_supplicant.conf
man iwn
man iwi


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.


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.


Changing the prompt for csh on FreeBSD 8.1

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

%

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

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

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

Temporary

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

To see the prompt temporarily, simply run this command:

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

Your prompt should now look as follows:

[SomeUser@SomeComputer ~]$

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

All Users

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

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

Add these lines to empty file:

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

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

[SomeUser@SomeComputer ~]$

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

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

Single User

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

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

By default the file looks as follows:

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

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

# A righteous umask
umask 22

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

setenv  EDITOR  vi
setenv  PAGER   more
setenv  BLOCKSIZE       K

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

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

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

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

# A righteous umask
umask 22

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

setenv  EDITOR  vi
setenv  PAGER   more
setenv  BLOCKSIZE       K

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

Your prompt should now look as follows:

[SomeUser@SomeComputer ~]$

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


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

Where is __LINE__ and __FILE__ in C#?

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

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

Getting __LINE__ and __FILE__ in C# when in debugging mode

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

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

StackHelper.cs

using System;
using System.Diagnostics;

namespace FileAndLineNumberInCSharpLog
{
    public static class StackHelper
    {

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

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

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

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

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

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

using System;

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

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

Getting __LINE__ and __FILE__ in C# when in debugging mode

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

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

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