Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Posted in Uncategorized | 1 Comment

Kelly Moore Bags

As I was looking for a bigger camera bag, I came across Kelly Moore Bags – http://www.kellymoorebag.com/.  I was looking for a bag with a flap and zipper top just like what I have now (I have an ugly black camera bag), but bigger and not bulky, with lots of pockets.  I fell in love with the b-hobo!  Not only is it stylist, it’s very functional.  I’ve read a tons of reviews on it, can’t wait to get my hands on one!!

Posted in Uncategorized | Leave a comment

Professor Emeritus Martin Garden (1914 to 2010) – RIP

 

Yesterday the world lost an illustrious individual – Professor Martin Garden.

Read all about him on wiki

Posted in Uncategorized | 1 Comment

Communication between C++ Linux servers and .Net clients – Part 1

One of the major challenges for wall street applications is communication between Linux servers written in C++ and .NET client (either Windows or web-based).  In the next series of articles, I will explore many different address the issue.

The platforms I will be using:

  • Linux – Fedora 12
  • .NET clients – .NET 4.0 clients, Windows based and web based.

Some of the solutions I will explore are:

And may be more.  Stay tuned….

Posted in Uncategorized | Leave a comment

Model View ViewModel – Part 2

In the previous article, I’ve described a light exposure timer application using MVVM.  I’ve described the interface of the MVVM for this application and showed how the view binds to MVVM.  This article will take a look at how MVVM is implemented.

The MVVM interface is listed below:

public interface ITreatmentViewModel : INotifyPropertyChanged
{
    void Play();
    void Stop();
    void Load(Stream s);
    void Save(Stream s);
    void AddTimeDelay(int timeDelta);

    ObservableCollection<TreatmentStep> Steps { get; }
    int CurrentPos { get; }
    TreatmentStep CurrentStep { get; }
    int DurationLeft { get; }
    bool IsPlaying { get; }
    IList<TreatmentStep> TreatmentPlan { get; set; }
    int TotalDuration { get; }
}

I’ve created DefaultTreatmentViewModel to implement this interface:

public class DefaultTreatmentViewModel : ITreatmentViewModel
{
    ObservableCollection<TreatmentStep> _steps = new ObservableCollection<TreatmentStep>();
    int _currPos = 0;
    DispatcherTimer _timer = new DispatcherTimer();
    int _timeLeft = 0;

    public DefaultTreatmentViewModel()
    {
        _timer.Tick += new EventHandler(_timer_Tick);
        _timer.Interval = TimeSpan.FromSeconds(1);
        AddDefaultSteps();
    }

ObservableCollection is commonly used in WPF for bindable collection; this replaces the BindingList in WinForms.  I use the DispatchTimer so that property change firing will be on the proper thread.

_timer_Tick timer callback function will be responsible for updating various properties related to Playing – CurrentPos, CurrentStep, DurationLeft, and IsPlaying; it is the “brain” of this MVVM class:

private void _timer_Tick(object sender, EventArgs e)
{
    // Reduce time left by 1.  Done if still time left

    DurationLeft = _timeLeft – 1;
    if (_timeLeft > 0)
    {
        return;
    }

    // Try to move to next step.  If no more next step, done

    int nextStep = _currPos + 1;

    if (nextStep >= _steps.Count)
    {
        IsPlaying = false;
        return;
    }

    // Otherwise, move to next step

    CurrentPos = nextStep;
    DurationLeft = _steps[nextStep].Duration;
}

Property change notification will be automatically generated when property setter is called:

public int DurationLeft
{
    get { return _timeLeft; }

    private set
    {
        _timeLeft = value;
        PropertyChanged(this, new PropertyChangedEventArgs("DurationLeft"));
    }
}

public bool IsPlaying
{
    get { return _timer.IsEnabled; }

    private set
    {
        _timer.IsEnabled = value;
        PropertyChanged(this, new PropertyChangedEventArgs("IsPlaying"));
    }
}

public int CurrentPos
{
    get { return _currPos; }

    private set
    {
        _currPos = value;
        PropertyChanged(this, new PropertyChangedEventArgs("CurrentPos"));
        PropertyChanged(this, new PropertyChangedEventArgs("CurrentStep"));
    }
}

Another slightly tricky aspect of this MVVM is the AddTimeDelay function.  Since the TreatmentStep does not implement INotifyPropertyChanged interface, modifying the object will not trigger update in DataGrid.  So, I use the simple trick of removing it and then inserting it into the same position:

public void AddTimeDelay(int timeDelta)
{
    _steps.Where(x => x.BodySide != TreatmentStep.Side.None).ForAll(x => x.Duration += timeDelta);
    Enumerable.Range(0, _steps.Count).ForAll(x => UpdateStep(x));
}

private void UpdateStep(int n)
{
    TreatmentStep step = _steps[n];
    _steps.RemoveAt(n);
    _steps.Insert(n, step);
}

Play/Stop just set the IsPlaying property, which enables/disables timer from firing:

public void Play()
{
    if (_steps.Count == 0)
    {
        return;
    }

    _timeLeft = 0;
    _currPos = -1;
    IsPlaying = true;
}

public void Stop()
{
    IsPlaying = false;
}

Finally, we use XM L serialization for Saving/Loading:

public void Load(System.IO.Stream s)
{
    List<TreatmentStep> steps;
    XmlSerializer xml = new XmlSerializer(typeof(List<TreatmentStep>));
    steps = xml.Deserialize(s) as List<TreatmentStep>;
    TreatmentPlan = steps;
}

public void Save(System.IO.Stream s)
{
    List<TreatmentStep> steps = new List<TreatmentStep>(TreatmentPlan);
    XmlSerializer xml = new XmlSerializer(steps.GetType());
    xml.Serialize(s, steps);
}

This completes the implementation of the MVVM class.

Going back to the view class and look at sound generation.  Instead of embedding the code into the view class, I created an Announcer class which “binds” to the MVVM:

Announcer _sndPlayer;

public TreatmentView()
{
    _vmModel = new DefaultTreatmentViewModel();
    DataContext = _vmModel;
    _vmModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_vmModel_PropertyChanged);
    _sndPlayer = new Announcer(_vmModel);
    InitializeComponent();

Text to Speech (TTS) synethsis is quite easy in .NET 4.0 using the System.Speech.Synthesis library.  For example, to say, “Front in 3”, just do this:

SpeechSynthesizer _speech = new SpeechSynthesizer();

private void PrepareToSwitch(TreatmentStep.Side side, int timeLeft)
{
    Debug.WriteLine("PrepareToSwitch " + side + "," + timeLeft);
    string txt = side.ToString() + " in " + timeLeft;
    _speech.SpeakAsync(txt);
}

The “brain” of Announcer class is in the property change notifier, which decides when to say what:

private void PropChange(object sender, PropertyChangedEventArgs args)
{
    string propName = args.PropertyName;

    if (propName == "DurationLeft")
    {
        int duration = _vmModel.DurationLeft;

        if (duration == 3)
        {
            // Get next step if any

            int nextStep = _vmModel.CurrentPos + 1;
            if (nextStep >= _vmModel.Steps.Count)
            {
                return;
            }

            TreatmentStep step = _vmModel.Steps[nextStep];
            PrepareToSwitch(step.BodySide, duration);
        }
        else if (duration < 3 && duration > 0)
        {
            CountDown(duration);
        }
    }
    else if (propName == "CurrentPos")
    {
        if (_vmModel.CurrentStep.BodySide != TreatmentStep.Side.None)
        {
            Switch(_vmModel.CurrentStep.BodySide);
        }
    }
    else if (propName == "IsPlaying")
    {
        if (!_vmModel.IsPlaying)
        {
            Finish();
        }
    }
}

The Announcer class validates the beauty of MVVM model.  When MVVM was created, there was no consideration of sound synthesis.  Sound synethesis is added subsequently without intrusion into either MVVM or the display view.

This concludes my short venture into MVVM.

Posted in Uncategorized | Leave a comment

Model View ViewModel – Part 1

In the forever attempt to create a pattern to solve model, model presentation, and model interaction, developers created many paradigms.  First came Model View Controller (MVC), it was good and still is good enough for web applications like ASP.NET MVC.  Then came Model View Presenter (MVP).  The MVP approach works pretty well in a code-driven, as opposed to data-driven, solution such as WinForms.

With the introduction of WPF with powerful support of data driven model– data template, dependency properties, and data bindings, there is now a new approach – MVVM.  Basically, there are existing business model objects, and there is a view model which encapsulates one or more model objects and to expose one or more properties that can be bound by one or more view objects.  Models update model view which then notifies views of updates.  Views can also change property value thereby updating the models.

I wrote an app recently using MVVM.  The app is a timer for suntan light exposure machine.  You create a schedule containing multiple steps, each step containing a side of body to be exposed and for how long.  You then play the schedule and it should make announcements to notify you when to turn.

When application starts, it looks like:

 

It uses the new WPF data grid to show the steps.  Relevant buttons will be enabled/disabled based on the Commanding architecture.  When the Play button is pressed, the current step will be selected and time left updated with each passing second:

Program also has sound in the form “Front in 3… 2… 1… switch Front” and tells you “Done” when done.

You use the Adjust button to quickly add/subtract seconds to/from each step, like so:

You can download the click-once deployable application from here

The MVVM looks like this:

public interface ITreatmentViewModel : INotifyPropertyChanged
{
    void Play();
    void Stop();
    void Load(Stream s);
    void Save(Stream s);
    void AddTimeDelay(int timeDelta);

    ObservableCollection<TreatmentStep> Steps { get; }
    int CurrentPos { get; }
    TreatmentStep CurrentStep { get; }
    int DurationLeft { get; }
    bool IsPlaying { get; }
    IList<TreatmentStep> TreatmentPlan { get; set; }
    int TotalDuration { get; }
}

Each function corresponds to an action of a command.  Steps can be bound directly to data grid, and other properties help GUI to update while playing schedule using INotifyPropertyChanged interface.

TreatmentStep looks like:

public class TreatmentStep
{
    public enum Side
    {
        None,
        Front,
        Back,
        Right,
        Left
    };

    public Side BodySide { get; set; }
    public int Duration { get; set; }
    public string Description { get; set; }
}

It’s pretty easy to make MVVM.Steps the item source of datagrid, and each column binds to a different property of TreatmentStep, like so:

<DataGrid x:Name="dgSteps" ItemsSource="{Binding Steps}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridComboBoxColumn x:Name="cbBodySide" SelectedItemBinding="{Binding BodySide}" Header="Body Side" CanUserSort="False"></DataGridComboBoxColumn>
        <DataGridTextColumn Binding="{Binding Duration}" Header="Length of Exposure" CanUserSort="False"></DataGridTextColumn>
        <DataGridTextColumn Binding="{Binding Description}" Header="Description" CanUserSort="False"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

We use commanding architecture so that buttons will be enabled/disabled based on view model state:

<Window.CommandBindings>
    <CommandBinding Command="MediaCommands.Play" x:Name="cmdPlay" CanExecute="cmdPlay_CanExecute" Executed="cmdPlay_Executed"></CommandBinding>
    <CommandBinding Command="MediaCommands.Stop" x:Name="cmdStop" CanExecute="cmdStop_CanExecute" Executed="cmdStop_Executed"></CommandBinding>
    <CommandBinding Command="Save" x:Name="cmdSave" CanExecute="cmdPlay_CanExecute" Executed="cmdSave_Executed"></CommandBinding>
    <CommandBinding Command="Open" x:Name="cmdLoad" CanExecute="cmdPlay_CanExecute" Executed="cmdLoad_Executed"></CommandBinding>
    <CommandBinding Command="Cut" x:Name="cmdAdjust" CanExecute="cmdPlay_CanExecute" Executed="cmdAdjust_Executed"></CommandBinding>
</Window.CommandBindings>

And the codebehind:

private void cmdPlay_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = !_vmModel.IsPlaying;
}

private void cmdStop_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = _vmModel.IsPlaying;
}

Getting datagrid to select the current row while playing is more tricky.  Rather than going overboard with property triggers, event handlers, I just set up a property change listener on the view model which then updates data grid accordingly:

_vmModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_vmModel_PropertyChanged);

private void _vmModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    string propName = e.PropertyName;

    if (propName == "CurrentPos")
    {
        int currPos = _vmModel.CurrentPos;
        dgSteps.SelectedIndex = currPos;
    }
    else if (propName == "IsPlaying")
    {
        CommandManager.InvalidateRequerySuggested();
    }
}

I may improve this in a future version.  Note that changing of property value for IsPlaying will cause all commands to re-evaluate themselves.

Next article will talk about sound generation and the implementation of view model.

Everything else about GUI hookup is pretty straight forward.  Get the complete source here

Posted in Uncategorized | Leave a comment

Bing is Down???!!!

 

If you happened to try bing circa 9pm Central time, you would see this message:

 

Now, with all the redundancy and cloud computing, how could Microsoft have trouble putting up a simple web page?

Posted in Uncategorized | Leave a comment