Im Baaack

by Alfie 5. December 2009 21:04

I have been MIA for a while now. This website has been down and I was too busy to upload previous posts and continue my journey in code. I apoligize to my readers and I look forward to share clean simple code samples and tutorials with you.

Tags:

Information

6 Ways To Improve Your Code

by Alfie 5. December 2009 20:26

To paraphrase BJarne Stroustrop, Clean Code is elegant, simple and efficient and does one thing well. I particularly love this statement because it has always been a strong belief of mine. I will now attempt to go through a few simple every day checklist that can improve code readability and ultimately, maintainability.

 

Tip #1: Identifiers

Identifiers, functions, classes/interface, should have names that are clear and concise. Most developers, including myself, love to write code late at night. This is when we can crank out our latest and greatest. But if you are like me, when you look at that same piece of art you cranked out a few weeks ago (or even the night before), you can hardly recognize what the variable call killSwitchForCat means.

Below is a table of good and bad identifiers just to give an idea.

Bad

Good

int w = dayOfMonth/7; // what is ‘w’ in the equation

int week = dayOfMonth/7;  //Write what was intended

int l; // don’t know if this is 1 or lowercase L

int length; // This is more easily identified and is even more searchable in Visual Studio

 

 

 

Tip #2: Naming Methods

Methods are some of the hardest things to name at times… especially when you have no clue what it really does. This tip is similar to tip #1 but is accompanied by an additional condition. Methods should be named according to the task they perform. This leads me to OOD (Object Oriented Design) 101 which says that your methods names should be the verb phrases from your design.

E.g.

GetProducts()
SaveProduct()

Tip #3 Consistency in Method Operations

Have you ever inherited code where you have 2 or more methods with the same (Overloaded) and you think to yourself, “They have the same name and since I know that this one does task A then this other method with the same name must perform the same task A.” Then you build and run only to find you crash with an exception only an alien can decipher.

E.g.

void SaveProduct()

    {

        EnsureConnection();

        SaveToDatabase(CurrentSelectedProduct);

    }

 

    void SaveProduct(Product product)

    {

        //You may get a crash here because ProductRepository.Products may be null

        Merge(ProductRepository.Products, product);

    }

This one will save you a lot of time and trouble in maintenance and readability.

Tip #4 Rule of Three: Function Are More Readable When Segmented

This one I learned in my first year of college yet have time and time again neglected this simple rule.
When you write a function you should divide it into 3 segments.
i. Declarations
ii. Initializations
iii. Functionality

E.g.
double ComputeLogOfBaseN(int baseN, double number)

    {

        int result; // Declaration

        result = 0; // Initialization: I know this is unrealistic but I am simply making a point;

        result = log10(number) / log10(baseN); // Functionality;

        return result;

    }

 

Tip #5: Function Arguments are more readable when <= 3

Have you notice that in the .Net framework most methods that you have to deal with on the regular have 3 or less arguments. The more arguments a function has the harder it is to read. Readability is the key to maintaining code. If you have a function that takes more than 3 arguments I suggest encapsulating them in a structure that is light weight.


Tip #6: Functions should have one entry and one exit.

Consider this function:
bool EvaluateUser(User u)

{

   if(!u.IsActive) return false;

   else if(u.IsOnline && !Role.IsInRole(“Administrator”, u)) return false;

    return false;

}

 

//VS

 

bool HasAdminPriviliges(User u)

{

   bool canProceed = false;

   if(!u.IsActive) canProceed  = false;

   else if(u.IsOnline && Role.IsInRole(“Administrator”, u)) canProceed = true;

    return canProceed;

}

Note: One return statement

Tags: ,

Concepts | Best Practices

MVVM (Model View View-Model) For Dummies

by Alfie 20. May 2009 20:45

Introduction

A few months ago I took the leap from WinForms programming to WPF and quite naturally, I took to it like a duck to water. Well, to be honest I had been developing Silverlight applications since its inception and being that Silverlight is a subset of WPF it required a low learning curve to catch on. However, the concept of Commanding was a bit different in WPF and I soon began to see how much more powerful Commanding in WPF was compared to Silverlight.

One of the areas in which Commanding is exemplary is in the way in which it complements MVVM.  But what is MVVM, and why is it useful? This is the toughest concept (In my opinion) to grasp when it comes to WPF (and Silverlight) programming. Why you ask? Because it is simple and as developers we often like code or concepts that warp our minds, so when we figure it out we can brag to our peers how it only took 2 hours to understand and implement the next BIG thing (No I am not projecting).  On a side not, I have found that everyone one who blogs about MVVM complicate it by adding too much code which just throws you for a loop. Simplicity is the key to all things complicated. So let’s delve into a little theory and we will finish up with some short-to-the-point code.

Purpose

The purpose of this post is to
a. Give a simple and clear definition of Model View View-Model
b. Provide a clear and simple sample that clearly illustrates MVVM usage

MVVM?

Figure 1.

 

 

Just in case you cannot read the text in the image here it is below:

1.        The View holds a reference to the ViewModel. The View basically displays stuff by Binding to entities in the View Model.

2.        The ViewModel exposes Commands, Notifiable Properties, and Observable Collections to the View. The View Binds to these ViewModel entities/members

3.        The Model is your data and or application objects that move data while applying Application Logic. If you have a Business Layer then you might not need this.

Above is a simple figure that tells you exactly what MVVM is. In my own words, the ViewModel is the most significant in the entire pattern as it is the glue that sits between the View and the Model and binds both of them together. Now let’s explore some code.

Code

The application you are about to see is very intricate in design and implementation and as such must not be criticized by anyone. Here is an overview of what the application does. It takes your first name, last name and age and displays it to you in message box.  Below is the really complicated class diagram.

Figure 2.

 

 

 Let’s take a look at the PersonModel class which is the only Model in the application:

namespace OliverCode.MVVM.Model

{

    internal class PersonModel : System.ComponentModel.INotifyPropertyChanged

    {

        private string firstName;

        public string FirstName

        {

            get { return firstName; }

            set

            {

if(firstname != value)

{

                   firstName = value;

                   OnPropertyChanged("FirstName");

                  }

            }

        }

 

        private string lastName;

        public string LastName

        {

            get { return lastName; }

            set

            {

if(lastname != value)

{

                        lastName = value;

                        OnPropertyChanged("LastName");

                  }

            }

        }

 

        private int age;

        public int Age

        {

            get { return age; }

            set

            {

if(age != value)

{

 

                        age = value;

                        OnPropertyChanged("Age");

                  }

            }

        }

 

        #region INotifyPropertyChanged Members

 

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

 

        private void OnPropertyChanged(string propertyName)

        {

            if (PropertyChanged != null)

                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));

        }

 

        #endregion

    }

}

Person class implements the INotifyPropertyChanged interface which enables a WPF elements to be immediately notified if any of the properties changed on a Person object.

Moving on… Let’s look at the View which is cleverly named, PersonView (Quite creative if I might add).

<UserControl x:Class="OliverCode.MVVM.View.PersonView"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Height="Auto" Width="Auto"

    xmlns:local="clr-namespace:OliverCode.MVVM.ViewModel">

    <StackPanel Orientation="Vertical" Margin="4">

        <!--Here is where we the view gets a reference to the ViewModel Declaratively-->

        <StackPanel.DataContext>

            <local:PersonViewModel />

        </StackPanel.DataContext>       

        <StackPanel Orientation="Vertical" DataContext="{Binding Path=Person, Mode=TwoWay}" Margin="4">

            <StackPanel Orientation="Horizontal">

                <Label Content="First Name:" Margin="0,0,4,0"/>

                <TextBox Width="250" Text="{Binding Path=FirstName}"/>

            </StackPanel>

            <StackPanel Orientation="Horizontal" Margin="0,5,0,0">

                <Label Content="Last Name:" Margin="0,0,4,0"/>

                <TextBox Width="250" Text="{Binding Path=LastName}"/>

            </StackPanel>

            <StackPanel Orientation="Horizontal" Margin="0,5,0,0">

                <Label Content="Age:" Margin="35,0,4,0"/>

                <TextBox Width="50" MaxLength="3" Text="{Binding Path=Age}"/>

            </StackPanel>

        </StackPanel>       

        <StackPanel>

        <!—The Command is bound to the Property in the PersonViewModel call SavePersonCommand-->

            <Button Content="Save" HorizontalAlignment="Right" Width="80" Command="{Binding Path=SavePersonCommand}"/>

        </StackPanel>

    </StackPanel>

</UserControl>

 

The key take away from the XAML above is the way the PersonViewModel is attached to the PersonView’s DataContext (This is the typical means by which the View gets a reference to the ViewModel).  Also pay attention to the Button element who’s Command is using the Binding Class to Attach the SavepersonCommand, which is a property on the ViewModel. Typically, binding to a command is more complicated than this, but because of the WPF Mvvm Toolkit 1.0 which is located here http://wpf.codeplex.com/Wiki/View.aspx?title=WPF%20Model-View-ViewModel%20Toolkit from the Microsoft Team, developers can now easily Bind to commands. I have included the DelegateCommand class in the project so you don’t need to download it directly. There is also a CommandReference class whose purpose is to resolve limitations in WPF when binding data binding from XMAL (This is not used in the program).

WPF Mvvm Toolkit 1.0 Tidbits

There are several classes in the toolkit but the one you should pay attention to is the DelegateCommand. This class makes it easy to write a function to handle a gesture or command. Gestures can be thought of as any interaction that can initiate a command. I use the DelegateCommand directly in my PersonViewModel like so.

private DelegateCommand savePersonCommand;

 

        public ICommand SavePersonCommand

        {

            get

            {                

                if(savePersonCommand == null)

                    savePersonCommand = new DelegateCommand(new Action(SaveExecuted), new Func<bool>(SaveCanExecute));

 

                return savePersonCommand;

            }

 

        }

 

public bool SaveCanExecute()

        {

            return Person.Age > 0 && !string.IsNullOrEmpty(Person.FirstName) && !string.IsNullOrEmpty(Person.LastName);

        }

 

        public void SaveExecuted()

        {

            System.Windows.MessageBox.Show(string.Format("Saved: {0} {1} - ({2})", Person.FirstName, Person.LastName, Person.Age));

        }

 

Here is the entire personViewModel class:

namespace OliverCode.MVVM.ViewModel

{

    internal class PersonViewModel

    {

        public PersonModel Person { get; set; }

 

        private DelegateCommand savePersonCommand;

 

        public ICommand SavePersonCommand

        {

            get

            {                

                if(savePersonCommand == null)

                    savePersonCommand = new DelegateCommand(new Action(SaveExecuted), new Func<bool>(SaveCanExecute));

 

                return savePersonCommand;

            }

 

        }

 

        public PersonViewModel()

        {

            //This data will load as the default person from the model attached to the view

            Person = new PersonModel { FirstName = "John", LastName = "Doe", Age = 999 };

 

        }

 

        public bool SaveCanExecute()

        {

            return Person.Age > 0 && !string.IsNullOrEmpty(Person.FirstName) && !string.IsNullOrEmpty(Person.LastName);

        }

 

        public void SaveExecuted()

        {

            System.Windows.MessageBox.Show(string.Format("Saved: {0} {1} - ({2})", Person.FirstName, Person.LastName, Person.Age));

        }

    }

}

Simple, isn’t it? I hope I have helped someone by saving them hours trying to find a simple demonstration of MVVM in WPF. Thank you and happy coding.

 

Tags: , ,

WPF | Best Practices | Design Patterns

RIA Services

by Alfie 19. May 2009 20:34

RIA Services - Release

Microsoft release RIA (Rich Internet Application) Services for Silverlight. What is RIA Services you ask? Well, in the words of Microsoft.


Microsoft .NET RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier. “

 

I have been following RIA Services for a while now and have even integrated it with a current project of mine. I use it in a 2 tier/2 layer approach where I generated LINQ to SQL classes that interacted directly with my database tables. This worked nicely. Data binding, Validation, and Authentication are easily integrated into your project. It has a few quirks but nothing that can’t be ironed out with a little fiddling here and there.

The next step is to see how it fits in with 2 tier/3 layer approach, where the middle layer will be POCO (Plain Old CLR Objects) which are part of a pure Domain Model. Check back for update on RIA Services.
I will post a simple solution that will be simple and easy to understand.

 

Here are a few links to get you started

March Preview: http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&displaylang=en

Code: http://code.msdn.microsoft.com/RiaServices

Tags:

Silverlight 3 | RIA Services

Commanding in WPF

by Alfie 17. May 2009 20:38

WPF Commanding: The Basics

Commanding in WPF is unlike your traditional events in Winforms. Commands were primarily designed to be used at the application level, but they have become one of the most popular features among developers when it comes to UI programming (we tend to use them more than they should be). Commands enable the developer to define a task once and “attach” it multiple times without having to go through the traditional means which would require duplicating the code or even calling it in more than one place (This is the magic). WPF intrinsically provides 5 commands that you can use out of the box.

i.                     ApplicationCommands

ii.                   ComponentCommands

iii.                  EditingCommands

iv.                 MediaCommands

v.                   NavigationCommands

I have explored them and have taken a liking to ApplicationCommands (In fact this is the one that most developers will use).

To use command do the following:

1.       Link  your custom/predefined  command to a control that you want to respond to the command and add a input gesture to the command

2.       Create a handler for the command and use the CommandBindings class to bind the handler to the control

3.       Add the binding to the control’s Commands collection

So let’s delve into some code to demonstrate WPF commanding.

Lets first look at the XAML:

<Window x:Class="Commanding.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1" Height="340" Width="509"

    xmlns:MyCommands="clr-namespace:Commanding">

    <Grid>

        <Border Padding="5" BorderBrush="Black" BorderThickness="2" CornerRadius="5" Margin="10">

            <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Top" Height="64">

                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">

                    <Label>Type Your Name :</Label>

                    <TextBox Name="txtName" Width="200"></TextBox>

                    <Button Command="MyCommands:Commands.HelloCommand" Content="Say Hello" Padding="3"></Button>

                </StackPanel>

                <CheckBox Name="chkCanExecute" Content="Uncheck to suppress command execution" IsChecked="True"/>

            </StackPanel>

        </Border>

    </Grid>

</Window>

 

The key section in the xaml code is the name space called MyCommands and the Button Element. The namespace

xmlns:MyCommands="clr-namespace:Commanding

 references the namespace in which the custom command is defined.

The Button Element’s Command property is associated with the custom command:

<Button Command="MyCommands: CustomCommand.HelloCommand" Content="Say Hello" Padding="3"></Button>

Below you will see the HellowCommand Property from the CustomCommand class.

 

namespace Commanding

{

    public class CustomCommand

    {

        private static System.Windows.Input.RoutedUICommand helloCommand;

 

        static CustomCommand ()

        {

            // First: I created a gesture collections

            System.Windows.Input.InputGestureCollection gestureCollection

                = new System.Windows.Input.InputGestureCollection();

 

            //Second: I add the input (Key gesture) that I want to trigger this command)

            gestureCollection.Add(new System.Windows.Input.KeyGesture(System.Windows.Input.Key.H, System.Windows.Input.ModifierKeys.Control));

 

            //Third: Initialize my command

            helloCommand = new System.Windows.Input.RoutedUICommand("HelloCommand", "HelloCommand", typeof(Commands), gestureCollection);

        }

 

        public static System.Windows.Input.RoutedUICommand HelloCommand

        {

            get { return helloCommand; }

        }

       

    }

}

Below I Bind the property from the custom command, then assign a handler and add it to the Window’s CommandBindings. Notice that I didn’t bind it to the button control directly.

namespace Commanding

{

    /// <summary>

    /// Interaction logic for Window1.xaml

    /// </summary>

    public partial class Window1 : Window

    {

        public Window1()

        {

            InitializeComponent();

 

            CommandBinding binding = new CommandBinding();

 

            binding.Command = Commanding.Commands.HelloCommand;

 

            binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);

 

            binding.CanExecute += new CanExecuteRoutedEventHandler(binding_CanExecute);

 

            this.CommandBindings.Add(binding);//Commenting out this line disables the button

        }

 

        void binding_CanExecute(object sender, CanExecuteRoutedEventArgs e)

        {

            e.CanExecute = (bool)chkCanExecute.IsChecked;

        }

 

        void binding_Executed(object sender, ExecutedRoutedEventArgs e)

        {

            MessageBox.Show(string.Format("Hello {0}, you have mastered commanding", txtName.Text));

        }

    }

}

Notice the binding_CanExecute method. This give you conditional execution. When you subscribe to this event, this method is called first to see if it ok to call your command. We use a check box to turn this on and off.

Next post we will look at Commanding and MVVM (Model View ViewModel). Here, you will see the power of Commanding. The code that is in the Window1 class violates a lot of GUI principles. With MVVM you will have a centralize place to (the ViewModel) where you can have reusable commands.

Tags:

Concepts | WPF

About the author

Hi, my name is Alfie and I am a Senior Software Developer living in NYC.  Being a programmer here is like being in the carnival and your main act is to walk the tight rope. This figurative rope is your job. It is not very stable and at the point where you start out is your boss helping you along by shoving you – they tend to call this, hitting the ground running. Then at the opposite end is also the same boss periodically throwing a random object your way expecting you to catch it and remain steady on the rope – this is synonymous to the many different things that he\she expects you to “juggle” while maintaining a clear head. Then at the bottom of the rope, guess who is there - your boss of course waiting for you to fall. Don’t think he is there to catch you. His only purpose is to wait for you to fail so that he can reprimand you like a 7 year old even though you were performing at a rate that is not even superhumanly possible. But the job must be done and must get done, even if you have to break the most fundamental rule of physics and move faster than the speed of light. If you can relate then hopefully this blog will help you in some way.

Month List

Recent Comments

Comment RSS

My Quotes

"This place that many call a melting pot is really a laboratory where natural selection is an on going experiment" - My answer when asked how I view NYC

"Life is an arrangement of random events which are all subjectively bounded at any given instant by a single individual with a greater will." - When the definition of time stopped making sense to me

"Don’t forget to live" - After seeing Day After Tomorrow and realizing how insignificant I am

Powered by BlogEngine.NET 1.5.0.7 - Eco Theme by n3o Web Designers