Archive for the ‘C# (C-Sharp)’ Category.

Options for copying a directory recursively with C#

Today I had the task of copying a directory recursively in C#. The first thing I did was type into my project “Directory.” and see if intellisense brought up a function called Directory.Copy. Unfortunately there is not a Directory.Copy, which to me seems like an oversight, as copying a directory is fairly common. Maybe it is not an action commonly done in C#.

So next I went to my browser and did a search. Well, I am not the first, nor will I be the last to solve this. There are a number of solutions online and each seem to have both positive and negative comments.

Option 1 – A directory copy using recursion

Pros: This is simple and to the point and elegant.

Cons: One complaint is that this could cause a stack overly by using recursion but this might not be a valid con as the filesystem restrictions in Windows might prevent a stack overflow anyway.

Since I am dealing with a small controlled tree, the con will not affect me., but since we are dealing with a file system, this is likely not to occur.

        private static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
        {
            foreach (DirectoryInfo dir in source.GetDirectories())
                CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
            foreach (FileInfo file in source.GetFiles())
                file.CopyTo(Path.Combine(target.FullName, file.Name));
        }

Option 2 – Use SearchOption.AllDirectories to create the directory structure then then copy all the files

Pros: Does not use recursion
Cons: Are there any?

        private static void CopyFilesRecursively(String SourcePath, String DestinationPath)
        {
            // First create all of the directories
            foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))
                Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));

            // Copy all the files
            foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories))
                File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));
        }

Option 3 – Use one of the methods recommended by MSDN

Unfortunately MSDN is not consistent, and recommends two different methods in two different places, which I am sure were written by different teams.

using System;
using System.IO;

class DirectoryCopyExample
{
    static void Main()
    {
        DirectoryCopy(".", @".\temp", true);
    }

    private static void DirectoryCopy(
        string sourceDirName, string destDirName, bool copySubDirs)
    {
      DirectoryInfo dir = new DirectoryInfo(sourceDirName);
      DirectoryInfo[] dirs = dir.GetDirectories();

      // If the source directory does not exist, throw an exception.
        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        // If the destination directory does not exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }

        // Get the file contents of the directory to copy.
        FileInfo[] files = dir.GetFiles();

        foreach (FileInfo file in files)
        {
            // Create the path to the new copy of the file.
            string temppath = Path.Combine(destDirName, file.Name);

            // Copy the file.
            file.CopyTo(temppath, false);
        }

        // If copySubDirs is true, copy the subdirectories.
        if (copySubDirs)
        {

            foreach (DirectoryInfo subdir in dirs)
            {
                // Create the subdirectory.
                string temppath = Path.Combine(destDirName, subdir.Name);

                // Copy the subdirectories.
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }
}

Or the different one they posted here:

using System;
using System.IO;

class CopyDir
{
    public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {
        if (source.FullName.ToLower() == target.FullName.ToLower())
        {
            return;
        }

        // Check if the target directory exists, if not, create it.
        if (Directory.Exists(target.FullName) == false)
        {
            Directory.CreateDirectory(target.FullName);
        }

        // Copy each file into it's new directory.
        foreach (FileInfo fi in source.GetFiles())
        {
            Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
            fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
        }

        // Copy each subdirectory using recursion.
        foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
        {
            DirectoryInfo nextTargetSubDir =
                target.CreateSubdirectory(diSourceSubDir.Name);
            CopyAll(diSourceSubDir, nextTargetSubDir);
        }
    }

    public static void Main()
    {
        string sourceDirectory = @"c:\sourceDirectory";
        string targetDirectory = @"c:\targetDirectory";

        DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
        DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

        CopyAll(diSource, diTarget);
    }

    // Output will vary based on the contents of the source directory.
}

Option 4 – Use Microsoft.VisualBasic

Pros: One line.
Cons: You have to reference an additional dll that you otherwise do not need.
This additional dll is not available in Mono for cross-platform development.

new Microsoft.VisualBasic.Devices.Computer().
    FileSystem.CopyDirectory( sourceFolder, outputFolder );

There are various other methods:

Resources:
http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
http://msdn.microsoft.com/en-us/library/bb762914.aspx
http://xneuron.wordpress.com/2007/04/12/copy-directory-and-its-content-to-another-directory-in-c/
http://www.logiclabz.com/c/copy-directory-in-net-c-including-sub-folders.aspx

A quick overview of MVVM

Model View ViewModel (MVVM) is a design pattern based on Model View Controller (MVC) but specifically tailored to Windows Presentation Foundation (WPF).

MVVM is not a framework per se but many frameworks have been created. Here is a list of MVVM Frameworks from Wikipedia.

See the Wikipedia site here: Open Source MVVM Frameworks.

Another blog, has some basic information on many of these here: A quick tour of existing MVVM frameworks

A framework is actually not necessary to implement MVVM and you should seriously consider whether using one is right for your WPF application or not. Many applications do not need much of the features the frameworks provide. However, there are two common classes that all MVVM frameworks contain. These are ViewModelBase and RelayCommand. Though some frameworks may give them different names or implement them slightly differently, they all have these classes. For example, MVVM Foundation names the ViewModelBase differently. It is called ObservableObject, which is more appropriate because it is incorrect to assume that all objects that implement INotifyPropertyChanged are going to be ViewModel objects.

Instead of installing and using an MVVM framework, you could simply include these classes in your application, as these are all you need to implement MVVM.

  • ObservableObject
  • RelayCommand

While these two classes are enough, you may want to investigate how different MVVM Frameworks implement and what else they implement and why. You may find that another feature implemented is exactly what you need in your application and knowing about it could save you time.

The Array class in C#

System.Array is an important class to know and understand as almost any programming work has arrays.

Array is an abstract class, so you cannot establish and instance of it. That is OK because it is really just a “function holder” class. The term “function holder” is not an official C# term, but it is a name I give classes that really just exist to hold functions. Array is a “function holder” for array functions.

Lets take a moment to learn a few of the functions in the Array class. We are going to use an array of high scores to learn from.

Array.Sort

Let start by creating an array of high scores. The following code has a function that takes a score and adds it to the list if it is greater than the lowest high score and sorting them.

using System;

namespace ArrayLearning
{
    class Program
    {
        static int[] highScores = new int[12];

        static void Main(string[] args)
        {
            // keep that top 12 high scores
            AddScore(10100);
            AddScore(13710);
            AddScore(14190);
            AddScore(12130);
            AddScore(12130);
            AddScore(16140);
            AddScore(19320);
            AddScore(07250);
            AddScore(18140);
            AddScore(08090);
            AddScore(10010);
            AddScore(14380);
            AddScore(18140);
            AddScore(12190);
            AddScore(19320);
        }

        static void AddScore(int newScore)
        {
            // Pre-sort the high scores in case somehow the
            // first one is not the lowest.
            Array.Sort(highScores);

            // If the new score is greater than the lowest
            // high score, replace the lowest high score
            if (highScores[0] < newScore)
                highScores[0] = newScore;

            // Now resort the scores as the new score may
            // not be in the right place
            Array.Sort(highScores);

            DisplayHighScores();
        }

        private static void DisplayHighScores()
        {
            // Print the new high scores
            for (int i = highScores.Length - 1; i > -1; i--)
            {
                Console.WriteLine(highScores[i]);
            }
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
            Console.WriteLine();
        }
    }
}

Ok, I am not saying this is the proper way to handle high scores in a game. I am just demonstrating Array.Sort for you.

Array.Clear

Ok, lets show an example of Array.Clear. This is a very simple function that sets all the values in the array to their default value. Booleans have a default value of false. Double, Int32, Int64, etc, have a default value of 0. Reference types have a default value of null.

Here is an enhancement to the above snippet that allows demonstrates clearing an entire array. Notice Array.Clear takes the array, then the starting item in the array and the number items in the array. In this example we clear the entire array, but that is not required.

using System;

namespace ArrayLearning
{
    class Program
    {
        static int[] highScores = new int[12];

        static void Main(string[] args)
        {
            // keep that top 12 high scores
            AddScore(10100);
            AddScore(13710);
            AddScore(14190);
            AddScore(12130);
            AddScore(12130);
            AddScore(16140);
            AddScore(19320);
            AddScore(07250);
            AddScore(18140);
            AddScore(08090);
            AddScore(10010);
            AddScore(14380);
            AddScore(18140);
            AddScore(12190);
            AddScore(19320);

            // Clear the high scores
            ClearHighScores();
        }

        static void AddScore(int newScore)
        {
            // Pre-sort the high scores in case somehow the
            // first one is not the lowest.
            Array.Sort(highScores);

            // If the new score is greater than the lowest
            // high score, replace the lowest high score
            if (highScores[0] < newScore)
                highScores[0] = newScore;

            // Now resort the scores as the new score may
            // not be in the right place
            Array.Sort(highScores);

            DisplayHighScores();
        }

        public static void ClearHighScores()
        {
            Console.WriteLine("Clearing High Scores!");
            Array.Clear(highScores, 0, highScores.Length);
            DisplayHighScores();
        }

        private static void DisplayHighScores()
        {
            // Print the new high scores
            for (int i = highScores.Length - 1; i > -1; i--)
            {
                Console.WriteLine(highScores[i]);
            }
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
            Console.WriteLine();
        }
    }
}

Array.IndexOf

Maybe you want to display the place in the top 12 that the player scored. However, the way we are adding the score does not track the new score’s place. So we need to find the place. Here is a small enhancement to the above code that demonstrates the use of Array.IndexOf to find the place.

Notice the addition of the DisplayCurrentPlace function and it’s use of Array.IndexOf. Also since the array is actually sorted with the lowest number at index 0 and the highest score at index 11, I can just subtract the index from the max lengh of 12 high scores to get the correct place.

using System;

namespace ArrayLearning
{

    class Program
    {
        public static int MAX = 12;
        static int[] highScores = new int[MAX];

        static void Main(string[] args)
        {
            // keep that top 12 high scores
            AddScore(10100);
            AddScore(13710);
            AddScore(14190);
            AddScore(12130);
            AddScore(12130);
            AddScore(16140);
            AddScore(19320);
            AddScore(07250);
            AddScore(18140);
            AddScore(08090);
            AddScore(10010);
            AddScore(14380);
            AddScore(18140);
            AddScore(12190);
            AddScore(19320);
            AddScore(06320);

            // Clear the high scores
            ClearHighScores();
        }

        static void AddScore(int newScore)
        {
            // Pre-sort the high scores in case somehow the
            // first one is not the lowest.
            Array.Sort(highScores);

            // If the new score is greater than the lowest
            // high score, replace the lowest high score
            if (highScores[0] < newScore)
            {
                highScores[0] = newScore;

                // Now resort the scores as the new score may
                // not be in the right place
                Array.Sort(highScores);

                DisplayHighScores();
                DisplayCurrentPlace(newScore);
            }
        }

        public static void ClearHighScores()
        {
            Console.WriteLine("Clearing High Scores!");
            Array.Clear(highScores, 0, highScores.Length);
            DisplayHighScores();
        }

        private static void DisplayHighScores()
        {
            // Print the new high scores
            for (int i = highScores.Length - 1; i > -1; i--)
            {
                Console.WriteLine(highScores[i]);
            }
        }

        private static void DisplayCurrentPlace(int newScore)
        {
            Console.WriteLine(String.Format("You placed number {0} out the top 12.", MAX - Array.IndexOf(highScores, newScore)));

            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
            Console.WriteLine();
        }
    }
}

Well, these were three simple examples of using the Array class. As you can see it is little more than a “function holder”.

If you have an example of a function in the Array class, please post it here in the comments.

Originally posted here: The Array class in C#

String and StringBuilder in C#

So we all use the Strings in C# and most of us consider ourselves experts. But are we really experts. When you’re getting tested and you don’t have Visual Studio or MSDN in front of you, are you ready to answer the questions with confidence?

Sometimes it is worth while to re-learn the basics because often simple features you are not using would save you time and prevent you from failing to appear as knowledgeable as you really are. Especially if you have not had a project where you manipulate strings, because you do other complex tasks and you do little more with strings than assign them values and compare them.

Well, here are the two links to the String and StringBuilder objects on MSDN.

Take a moment and read the MSDN pages about these objects even if you have read them before.

Here are some questions that you should answer about these classes.

  1. Which is mutable and which is immutable? What does that mean?

    Answer:

    String is immutable. That means that once you create a string, it cannot be altered in place in memory, but instead, any alteration causes a copy with the modification to be created in a new memory location and the reference is updated to refer to the copy. For example if you append a character you actually get a whole new string in a whole new memory location.

    StringBuilder is mutable. That means that you can change the object in place in memory without creating a copy. For example, if you append a character to StringBuilder it can add it to the same space in memory. There is one exception. If you add so many characters that the next character you add make the string bigger than the memory location’s capacity, a new object in memory is created. The default capacity for this implementation is 16 characters, and the default maximum capacity is Int32.MaxValue. (1) So if you are playing with Strings greater than 16 characters, you should instantiate your StringBuilder objects with a capacity greater than 16.

  2. So can you modify a string in place in memory?

    Answer:

    No. And yes.

    Read this MSDN article: How to: Modify String Contents (C# Programming Guide)

    The short version of the above article is that you can’t normally. But if you use “unsafe” you can, the above link provides the following unsafe code:

    class UnsafeString
    {
        unsafe static void Main(string[] args)
        {
            // Compiler will store (intern)
            // these strings in same location.
            string s1 = "Hello";
            string s2 = "Hello";
    
            // Change one string using unsafe code.
            fixed (char* p = s1)
            {
                p[0] = 'C';
            }
    
            //  Both strings have changed.
            Console.WriteLine(s1);
            Console.WriteLine(s2);
    
            // Keep console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
    

    Would you actually do this though?

  3. What is the easiest way to reverse a String?
        public static string ReverseString(string s)
        {
    	char[] arr = s.ToCharArray();
    	Array.Reverse(arr);
    	return new string(arr);
        }
    

    Notice another C# class called Array was used. This class, like String and StringBuilder, is another class that you may be forgetting about an overlooking.

    When I was asked how to reverse a string, the Array.Reverse function did not come to mind and so I recreated it with this function, which obviously takes more time and a developer’s time is too expensive to recreate work already done for you.

        private static String Reverse(String inString)
        {
            char[] myChars = inString.ToCharArray();
            for (int i = 0, j = inString.Length - 1; i < inString.Length / 2; i++, j--)
            {
                char tmp = inString[j];
                myChars[j] = inString[i];
                myChars[i] = tmp;
            }
            return new string(myChars);
        }
    
  4. Which is more efficient for concatenation or appending characters, String or StringBuilder?

    StringBuilder is by far more efficient. Microsoft has a knowledge base article on this here: http://support.microsoft.com/kb/306822

    I changed the code slightly to use the Stopwatch to time the ticks to get more accurate data.

    using System;
    using System.Diagnostics;
    
    namespace StringBuilderPerformance
    {
        class Program
        {
            static void Main(string[] args)
            {
                // The greater the loops the better the performance ratio
                const int sLen = 30, Loops = 10000;
                int i;
                string sSource = new String('X', sLen);
                string sDest = "";
                //
                // Time string concatenation.
                //
                Stopwatch timer = new Stopwatch();
                timer.Start();
                for (i = 0; i < Loops; i++) sDest += sSource;
                timer.Stop();
                long stringTicks = timer.ElapsedTicks;
                Console.WriteLine("Concatenation took " + stringTicks + " ticks.");
                //
                // Time StringBuilder.
                //
                timer.Reset();
                timer.Start();
                System.Text.StringBuilder sb = new System.Text.StringBuilder((int)(sLen * Loops * 1.1));
                for (i = 0; i < Loops; i++) sb.Append(sSource);
                sDest = sb.ToString();
                timer.Stop();
                long stringBuilderTicks = timer.ElapsedTicks;
                Console.WriteLine("String Builder took " + stringBuilderTicks + " ticks.");
                Console.WriteLine("Using StringBuilder takes " + ((double)stringBuilderTicks / (double)stringTicks * (double)100).ToString("F") + "% of the time that using String takes.");
    
                //
                // Make the console window stay open
                // so that you can see the results when running from the IDE.
                //
                Console.WriteLine();
                Console.Write("Press any key to finish ... ");
                Console.ReadKey();
            }
        }
    }
    

    Here are the results:

    Concatenation took 5338055 ticks.
    String Builder took 2213 ticks.
    Using StringBuilder takes 0.04% of the time that using String takes.

    Press any key to finish …

Anyway, I hope this post helps you remember the basics.

Refreshing a button enabled/disabled by RelayCommand.CanExecute

When using the RelayCommand class, a command class used for MVVM development, you may find times when a button that is enabled or disabled based on RelayCommand.CanExecute does not refresh until a keyboard or mouse click.  When this happens you may have to manually force this refresh to occur. You can force the refresh in the ViewModel with this function:

CommandManager.InvalidateRequerySuggested();

If you want to see this in action, you can download the LDPing project I have recently made.

svn co https://ldmsplugins.svn.sourceforge.net/svnroot/ldmsplugins/LDPing

You don’t need to know about LANDesk or know what an LDPing is to understand what is going on enough to see how to use this one function. In the LDPing project, clicking the button starts a background process to run an LDPing. The button disables when clicked. Once the ping is finishes, the button should enable, however, originally it didn’t enable.  I had to add the CommandManager.InvalidateRequerySuggested() function.

Here is the code:

        /// <summary>
        /// This is the Ping method that launches an LDPing as a BackgroundWorker process, using
        /// PingWorker which is an object that inherits BackgroundWorker and adds one property called
        /// PingSucceeded.
        /// </summary>
        private void Ping()
        {
            IsPinging = true;
            ClearPingResults();

            PingWorker worker = new PingWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoPing);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_PingCompleted);
            worker.RunWorkerAsync();
        }

        void worker_DoPing(object sender, DoWorkEventArgs e)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();

            // Now lets ping
            PingWorker worker = sender as PingWorker;
            LDPing tmpLDPing = LDPingAction.AgentPing(IPAddress);
            if (tmpLDPing == null)
                worker.PingSucceeded = false;
            else
                worker.PingSucceeded = true;
            timer.Stop();

            // Lets make sure the GUI spinner has at least a little spin
            int i = 1200 - (int)timer.ElapsedMilliseconds;
            if (i > 0)
                Thread.Sleep(i);
            LDPing = tmpLDPing;
        }

        void worker_PingCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            IsPinging = false;
            PingWorker worker = sender as PingWorker;
            if (worker.PingSucceeded)
                ConnectionResult = "Ping Successful.";
            else
                ConnectionResult = "Ping failed.";

            // This makes the UI refresh against the RelayCommand.CanExecute() function.
            // Essentially, this makes the button enable when pinging is done.
            CommandManager.InvalidateRequerySuggested();
        }

Without the CommandManager.InvalidateRequerySuggested() function, the button’s enabled state doesn’t refresh until an event such as a keyboard or mouse click.

Timing a process

So I wanted to see how long some of my code took and if it didn’t take long enough, make it take longer. Yes, I really said that and I have a good reason for it.

My use case is this:

  • I have a process that is being kicked off using BackgroundWorker.
  • For user experience reasons, I wanted my WPF GUI spinner to have a minimum time of 1.2 seconds that it spins while a process runs.

See my spinner post: WPF replacement options for an animated gif or How to make a spinner?

Here is what I did:

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
            Stopwatch timer = new Stopwatch();
            timer.Start();

            // Now lets do the work that you need a spinner for
            // Your code goes here ....

            timer.Stop();

            // Lets make sure the GUI spinner has at least 1.2 seconds of spin
            int i = 1200 - (int)timer.ElapsedMilliseconds;
            if (i > 0)
                Thread.Sleep(i);
    }

How to animate an edit box to slide in and out using Expression Blend

Ok…so I created a simple WPF and MVVM application called My Friends.  This is just a simple applications, the main goal was not to create a My Friend app, but do demonstrate how to make an edit box slide in an out.

The application is too big to give you step by step instructions to create the whole application, so instead, I am going to make it available for download and then tell you how to see the changes.

  1. Download and extract the solution from the link below:
    MyFriends.zip
  2. Open the project in Expression Blend (not Visual Studio).
  3. Get to know the Application. (Ok, I guess you could do this part in Visual Studio…but the intent is to learn an Expression Blend feature.)
    Check out the Person and PersonCollection classes in the Model folder.
    Check out the Views and the corresponding ViewModels and look at the binding statements.
    The MVVM folder has some standard MVVM classes, that if you know MVVM you should be familiar with.
    The business has an XML Serialization helper class.
    The data folder contains an XML that is serialized from the PersonCollection class.
  4. In Expression Blend, open the View\FriendListView.xaml.
  5. In the Objects and Timeline tab, get to know the assets that are being used. (I think they are all standard assets. I don’t think I am using anything that doesn’t come with .NET and Expression Blend by default.)
  6. In the Objects and Timeline tab, specifically look at the PersonDetailsView object.
    Notice it is behind the FriendList.
    This is the edit box that is animated and it will slide to the right when you click edit.
  7. Go to the States tab.
    Look a the State group that is created. There are two groups: EditFriendOpenState and EditFriendClosedState.  The names should be obvious.
    Notice the Transition duration is set to .5 and notice the Easing function.
  8. There is a behavior or action called GoToStateAction that was dragged over the Edit button and configured to change the state to EditFriendOpenState.
  9. The GoToStateAction was also dragged over the X button on the edit page and configured to change the state toEditFriendClosedState.
  10. Build the application and see how the state changes and how it uses the Easing function for .5 seconds to slide the edit field out.

Here is a sample image:

Anyway, I hope you find this a fun sample application to learn with.

 

This project is also an example of:

  • Basic C#
  • Xml Serialization
  • MVVM (including ICommand and RelayCommand with buttons)
  • Using Data Converters (as one converter is used)

Exercises for further learning:

LINQ exercise

  • There is a comment in the View\FriendListView.xaml that uses LINQ, but there is a reason LINQ wasn’t used, can you determine the reason.
  • What would you have to do to use LINQ and make the application work?

DateTime exercise

  • There is an Age property that was left commented out.  Uncomment it, make it read-only and make it provide the correct number in years based on the Birthday.

How to create a sphere in Expression Design

Expression Design makes creating a sphere quite easy. Below is a blue sphere with a shadow that was quite simple to make and that you can make by following this short post.

What you will learn

  • Using the ellipse tool
  • Gradient and basic manipulation and movement of the gradient
  • One possible way to create a shadow

Step 1 – Create a new Expression Design document

  1. Open Expression Design and click File | New.
  2. Name the file BlueSphere.design (or whatever name you would like).
    Note: I used a custom width and height of 250 x 125, and left the resolution at 96.
  3. Click OK.

Step 2 – Create the sphere

  1. Select the Ellipse tool from the ToolBox (which is on the left by default but you can move it wherever you want).
    Note: If you cannot find it, try pressing “L” as that is the shortcut key.
  2. Draw a circle on the screen while holding down the shift key(the shift key is what tells Expression Design that you are looking for a perfect circle and not an ellipse).
    Note: The width and height of my circle was 83.25 x 83.25.
  3. With the circle selected, go to the properties tab.
  4. Under Appearance, click the Fill tab.
    Note: Hold your cursor over the tab and it will tell you which tab is the Fill tab and which is the Stroke tab.
  5. Change the color to blue for now. We will apply gradient in the next step.
  6. Click the Stroke tab.
  7. Under the Stroke tab and all the way under the color picker, look for a drop down menu. (By default this menu has an image of a black line but can have many options.)
  8. Change it to No Stroke.
  9. Change the Stroke Width to 0 px.

Step 3 – Create the gradient effect

The gradient effect is what makes a circle on a screen look like a sphere.  It is what makes the circle appear to fade from white to dark blue.

  1. Make sure the circle is selected and go to the Properties tab.
  2. Under Appearance, click the Fill tab.
  3. Select the Gradient option.
    Note: It is the bottom left of the four boxes just left of the color boxes. Once you click this, you will have a gradient bar.
  4. To the right of the gradient bar, there are two gradient options: Linear Gradient, Radial Gradient. Choose Radial Gradient.
  5. On the gradient bar, you should see two markers (squares with a triangle on top).  Click the left marker and set the color to white.
  6. Click the right marker and set the color to blue.
    Note: I used color #153FC4.
  7. Just below the Linear Gradient, Radial Gradient option, there is a drop down that allows you to “Move, scale, rotate or skew the fill of the object”. Click it.
  8. Change X and Y to 12 px.
    Note: This moves the center of the gradient up and to the right, leaving a part of the sphere on the bottom left without a gradient.
  9. Change Width and Height to 135%.
    Note: This makes the gradient area larger fixing that the part on the bottom left that was left without the gradient when we moved the gradient up and to the left.

Step 5 – Create the shadow

In case you don’t want a shadow, this is a separate step you can choose to do if you want.

  1. Select the Ellipse tool from the ToolBox.
    Note: Remeber, try pressing “L” as it is the shortcut key.
  2. Draw an ellipse on the screen that is a little more than twice as wide as it is tall.
    Note: I created one that is 40×90.  You can see the size on the bottom of the Expression Design screen.
  3. Change the Fill to black.
  4. Under Effects, click the “fx” drop down button and choose Effects | Gaussian Blur.
  5. Set the Radius to .5.
  6. Set the Opacity to 70%.
  7. Now turn the shadow -2.7 degrees.  You can either grab a corner of the selection when the shadow is selected or you can enter this into the the Rotation Angle option at the bottom of the Expression Design window.
  8. Right-click the shadow and choose Arrange | Send to back.
  9. Place the shadow under the sphere where it looks most natural.

Click the Sphere to download a zip file containing: BlueSphere.design, a BlueSphere.png and a BlueSphere.xaml.

 

Download

 

 

C# and Boxing and Unboxing

In order to understand boxing, you first must understand the different value types in C#. There are two types you should be aware of.

Value Types

Value Types are any type that is a struct or an enum.  Value types are fast because they are handled by the stack. Most of the built-in types in the C# language are structs, and so are value types.  Here is a complete list of value types.

bool System.Boolean
byte System.Byte
sbyte System.SByte
char System.Char
decimal System.Decimal
double System.Double
float System.Single
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
short System.Int16
ushort System.UInt16

Value types are not Objects, they are structs.

Reference Types

Reference Types are not usually built-in types, though there are two built-in reference types. They are stored on the heap, so they are fast, but not as fast as value types.  Also, if you run out of memory, the swap or page file could be used and your object could potentially be on disk, which is slow.

object System.Object
string System.String

Object and String are both reference types even though they are built-in types. That means they are stored on the heap. However, the stack is still used. Instead of holding the data, the stack must hold a reference to the data.

Note: When a value type is boxed, it is boxed into the built-in Object type.

Any class created is a reference type.  So if you create a Person class, it is a reference type.

What is Boxing in C#

Boxing is the concept of encapsulating a value type in the Object reference type.

This is the simplest example of boxing.

int i = 100;
Object o = i;

So if you look at the above you have two variables. The first, i, is an int that is a value type and stored on the heap.  The second is a reference type. The heap holds a reference to a location on the heap where the object is stored.  The heap is slower than the stack, and there is a cost when copying from the stack to the heap.

Sometimes boxing is not at first obvious. For example, if you have your own struct you might see different behavior than the built-in types. Calling the ToString() function may or may not cause boxing. Usually it does not cause boxing in built-in types. Look at this example.

    public struct Rectangle
    {
        public double width;
        public double height;
    }
            int i = 100;
            Rectangle rect = new Rectangle() { height = 100, width = 200 };
            r.ToString();
            // No boxing
            Console.WriteLine(i.ToString());
            // Boxing occurs
            Console.WriteLine(rect.ToString());

The reason boxing occurs on your own struct is because you didn’t override the ToString() function.  The documentation states:

If thisType is a value type and thisType does not implement method then ptr is dereferenced, boxed, and passed as the ‘this’ pointer to the callvirt  method instruction. [1]

So you could have done this to prevent boxing.

    public struct Rectangle
    {
        public double width;
        public double height;
        public override string ToString() { return width.ToString() + "," + height.ToString(); }
    }

Anytime an value type is encapsulated into an Object reference type and stored on the heap, boxing occurs.

What is Unboxing

Unboxing just means to remove a value type the is encapsulated in an Object reference type and restore the value back to the stack.

int i = 100;
// Boxing
Object o = i;

// Unboxing
int j = (int)o;

So the above code shows a simple cast that pulls a value type out of the Object reference type.

Why is this important?

Speed.  When you box a value type, you are encapsulating it into an object. The object is stored on the Heap. The Heap is fast, but the stack is faster. There is of course a cost to copying data back and forth between the heap and stack. And if you are short on memory it could really bog you down if your application had to rely on the swap or page file, as these are stored on disk and disks are not fast.

Fastest Fast Slow
Stack Heap Disk (swap or page file)

Is Boxing bad?

No. It is a very important part of C#.

It is only bad when it is not needed but still used (usually unintentionally) and causing a performance hit, such as when looping through data in a large list. So if you are ever looping through a large list of value types, it might be a good idea to check to see if you are avoiding boxing and unboxing every value in the list.


Resources

http://www.dijksterhuis.org/exploring-boxing/#more-908
http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx
http://www.codeproject.com/KB/cs/boxing.aspx
http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.constrained.aspx

Expression Studio Training Videos – A check list of videos from Expression.Microsoft.com

There are a lot of free training videos at the Expression 4 web site. However, this web site has two problems:

  1. The videos aren’t necessarily in order.
  2. There is not defined method to track your learning progress as you watch them.

Well, now it is easy. Just copy and paste this page, or easier, download this Excel document:

Expression Training Videos.xls

You can now track you progress as you self-train and go through the Expression 4 training videos.

Training Subjects



Expression Studio

Introducing Expression 4 (eight videos)
Completed Introduction Videos
Introduction to Expression Studio Ultimate
Introduction to Expression Web
Introduction to Expression Blend
Introduction to SketchFlow, a feature of Expression Studio Ultimate
Introduction to Expression Encoder Pro
Expression Web Demo Overview
Expression Blend and SketchFlow Demo Overview
Expression Encoder Pro Demo Overview
Getting Started with Silverlight – For Designers (eleven video series)
Completed Beginner Videos
What is Silverlight? An Overview
Understanding and Working with XAML Code in Expression Blend
Creating Vector-Based Artwork with Expression Design
Applying Color and Effects to Projects using Expression Design
Organizing Your Project using Layout Containers in Expression Blend
Editing the Appearance of Your Project Items using Expression Blend
Exploring the Objects and Timeline Task Pane in Expression Blend
Customizing Silverlight Video Players using Expression Blend
Optimizing Video for Silverlight Playback using Expression Encoder
Adding Interactivity to Silverlight Projects using Expression Blend
Publishing Silverlight Projects to the Web using Expression Blend
Getting Started with Standards-Based Design (ten video series)
Completed Training
Understanding the Benefits of Standards-Based Design with Expression Web
Styling Text using CSS with Expression Web
Understanding CSS Pseudo Classes for Styling Links using CSS with Expression Web
Understanding CSS Margins and Padding with Expression Web
Using CSS Positioning for Layout with Expression Web
Adding Background Images Using CSS with Expression Web
Using CSS Floats to Create Flexible Page Layouts with Expression Web
Clearing CSS Floats with Expression Web
Adding JavaSript to Your Site with Expression Web
Using External CSS Stylesheets with Expression Web



Prototyping

Additional Expression Blend Training Videos
Download the assets, step-by-step guide, and video package (127MB)
Completed Training
Introducing SketchFlow with Expression Blend 3
Adding Navigation Screens in SketchFlow with Expression Blend 3
Building Basic Layout in SketchFlow with Expression Blend 3
Using SketchStyle Controls to Enhance a SketchFlow Layout with Expression Blend 3
Working with Components in a SketchFlow Project with Expression Blend 3
Adding Navigation to Buttons in SketchFlow with Expression Blend 3
Working with States in SketchFlow with Expression Blend 3
Working with the SketchFlow Animation Panel with Expression Blend 3
Working with Behaviors in SketchFlow with Expression Blend 3
Using Sample Data in SketchFlow with Expression Blend 3
Exporting your SketchFlow project with Expression Blend 3
Adding Feedback and Annotations in the SketchFlow Player with Expression Blend 3


Additional Videos


Additional Expression Blend Training Videos
Completed Training
Displaying Dynamic Content in Silverlight using Expression Blend
Understanding and Managing Silverlight Resources with Expression Blend
Making Silverlight Objects Appear Transparent over HTML using Expression Blend
Creating a Template for a ScrollBar with Expression Blend
Customizing an Expression Encoder Template using Expression Blend
Creating Animated XAML Overlays for Expression Encoder using Expression Blend and Design
Customizing a Silverlight Template with Expression Blend
Customizing the Look of a Radio Button in Expression Blend
Customizing the Look of a Listbox in Expression Blend
Creating a Calculator with Expression Blend
Using Runtime Storyboarding in Expression Blend
Creating User Controls in Expression Blend
Reusing and Customizing User Controls in Expression Blend
Making a Slider Control in Expression Blend
Exploring XAML Layout Controls in Expression Blend
Using the Breadcrumb Trail in Expression Blend
Using Vertex Animation with Expression Blend
Using the Border Control in Expression Blend
Using the GridLayout Panel in Expression Blend
Using the Layout Stack Panel in Expression Blend
Using the Binding Scrollbar in Expression Blend
Creating Visual Transitions in Expression Blend
Use an In-State Animation To Make a Silverlight 2 Button Pulse While Focused
Customize The Check Mark In a Silverlight 2 CheckBox
Add States to a UserControl for Silverlight 2
Create Custom Buttons for Silverlight 2
Create and Edit Clipping Paths in Blend
Use the Key Spline Editor in Blend
Create the Wet Floor Effect in Expression Blend
Customize Expression Media Silverlight Templates Using Blend
Working with 3D Cameras in Expression Blend
Working With 3D Materials in Expression Blend
Importing and Manipulating 3D Objects in Expression Blend
Create User Controls in Expression Blend
Working With Clipping Paths in Expression Blend
Using an ObjectDataSource in Expression Blend
Creating a Control Template in Expression Blend
Introduction to Styles
Using Expression Design to Generate XAML Resources for Expression Blend
Motion Paths
Sharing Styles Among Heterogeneous Elements
Basic Animation
Timeline Interpolation
Working with the Grid Panel
Adding Video
Creating and Using an XMLDataSource
Create Data Templates
Creating and Using Brush Resources in Expression Blend
Introducing Blend and Working with Control Editing
Using Databinding with External Data
3D Animation and Event Triggers
Databinding to Control Properties
Designer and Developer Collaboration and Additional Demos



Beehive Game

Additional Expression Blend Training Videos
Download the assets, step-by-step guide, and video package (104 MB)
Completed Training
Organizing and Importing Assets into Expression Blend 3
Creating the BeeHive Game Interface Using Expression Blend 3
Understanding Layout Containers with Expression Blend 3
Creating a User Control with Expression Blend 3
Adding and Applying Behaviors with Expression Blend 3
Adding Game Walls and Creating Animation with Expression Blend 3
Animating Controls with the Visual State Manager with Expression Blend 3
Working with Text and Embedding Fonts with Expression Blend 3
Adding Audio Resources to a Silverlight Game with Expression Blend 3
Publishing and Testing Your Silverlight Game with Expression Blend 3

Well, once you have gone through all these videos you can probably call yourself trained in Application Design using Expression Studio, SilverLight and WPF.

With these skills expect to make between 40k (0-1 years experience) and 80k (5+ years experience).