Archive

Archive for December, 2009

Deep Copy / Clone Objects in Silverlight with C#

December 28, 2009 7 comments

The following code will add an extension method to Silverlight 3 based C# code to perform a deep copy of a custom object.  This templated method uses the MemoryStream serialization/deserialization technique, but will not work with UIElement members or derivatives.

public static class ExtensionMethods
{
       public static T DeepCopy<T>(this T oSource)
       {
              T oClone;

              DataContractSerializer dcs = new DataContractSerializer(typeof(T));

              using (MemoryStream ms = new MemoryStream())
              {
                     dcs.WriteObject(ms, oSource);
                     ms.Position = 0;
                     oClone = (T)dcs.ReadObject(ms);
              }

              return oClone;
       }
}

Basketball Play Designer in Silverlight 3

December 12, 2009 4 comments

Silverlight is an exciting new technology that provides a cool platform for building EMBED’able applications and complete web sites using Visual Studio and Expression Blend. There are numerous features that are worth exploring, but my favorite is the seperation of the UI/UX and the implementation, along with Expression Blend.

Being a C#/C++ software guy with some graphical design skills, this is a perfect match. In this article, we’ll create the start of a Silverlight application for designing basketball plays. The finished product’s looks can change quite a bit, but the functionality remains the same:

     Standard Court - Click for Larger Image     Abstract Court - Click for Larger Image

In the first video clip you will learn how to create the project in Visual Studio and the static visual layout in Expression Blend.

In part 2, you will learn how to create and wire up dynamic controls and event handlers and create the associated C# code.

The next steps for this application will be presented in an upcoming article and include:

  • Drag and drop animation
  • Better styling (buttons, etc)
  • Passing and dribbling
  • Record and playback
  • Save plays and play templates (e.g., ‘2-3 zone’)

Download Source: SilverlightBasketballSample.zip (316KB)

A Quick Line Counter in C++

December 11, 2009 Leave a comment

A quick source code line counter written in C++.  This project uses the Microsoft Foundation Classes (MFC), along with the standard C++ libraries. It could use some additional features and more advanced error handling, but it is fairly complete. One quick note (that several have brought to my attention), the percentages do not usually add up to 100% – that is because of the use of integers instead of floating point types, which essentially rounds down. The code is available below.

Windows Line Counter Screenshot

Download Source: WinLocCounterSample.zip (216KB)

Categories: Code, Samples Tags: ,

Iterate Directories & Files in C++

December 9, 2009 Leave a comment

In standard (non-managed) C++ on the Windows platform, traversing a directory / folder tree recursively can be accomplished via the Win32 API.  The following listing is a simple example that displays the name of each file.

#include <windows.h>
#include <string>
#include <vector>
#include <stack>
#include <iostream>

using namespace std;

// Recursive directory traversal using the Win32 API
bool ListFiles(wstring path, wstring mask, vector<wstring>& files)
{
	HANDLE hFind = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATA fdata;
	wstring fullpath;
	stack<wstring> folders;
	folders.push(path);
	files.clear();
	
	while (!folders.empty())
	{
		path = folders.top();
		fullpath = path + L”\\” + mask;
		folders.pop();

		hFind = FindFirstFile(fullpath.c_str(), &fdata);

		if (hFind != INVALID_HANDLE_VALUE)
		{
			do
			{
				if (wcscmp(fdata.cFileName, L”.”) != 0 &&
                    wcscmp(fdata.cFileName, L”..”) != 0)
				{
					if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
					{
						folders.push(path + L”\\” + fdata.cFileName);
					}
					else
					{
						files.push_back(path + L”\\” + fdata.cFileName);
					}
				}
			}
			while (FindNextFile(hFind, &fdata) != 0);
		}

		if (GetLastError() != ERROR_NO_MORE_FILES)
		{
			FindClose(hFind);

			return false;
		}

		FindClose(hFind);
		hFind = INVALID_HANDLE_VALUE;
	}

	return true;
}

int main(int argc, char* argv[])
{
	vector<wstring> files;

	if (ListFiles(L”C:\\source”, L”*”, files))
	{
		for (vector<wstring>::iterator iter = files.begin(); iter != files.end(); ++iter)
		{
			wcout << iter->c_str() << endl;
		}
	}

	return false;
}

Categories: Code, Win32 Tags: , , ,

Silverlight 3 – Dynamically Add & Remove Objects in C# Code

December 8, 2009 6 comments

I recently spent a few minutes trying to figure out how to create rectangles and ellipsis in Silverlight code – I was sure I had it all hooked up and coded properly, but I missed one little thing (isn’t that the way it always goes).    

Here is what the canvas looks like in Blend:
Click for Larger Image    

Create the dynamic controls:
The following C# code does the heavy lifting to dynamically create an ‘offensive player’ (which is really an ellipse) and associated event handlers and is called by the ‘O’ button click event handler.  

public void CreateOffensivePlayer()
{ 
     // Create an Ellipse
     Ellipse player = new Ellipse();
     player.Height = 25;
     player.Width = 25;
 
     // Create the brushes
     SolidColorBrush blueBrush = new SolidColorBrush();
     blueBrush.Color = Colors.Blue;
     SolidColorBrush blackBrush = new SolidColorBrush();
     blackBrush.Color = Colors.Black;

     // Set the width, color and fill
     player.StrokeThickness = 1;
     player.Stroke = blackBrush;
     player.Fill = blueBrush;
 
     // Add to the Canvas
     player.SetValue(Canvas.LeftProperty, _mouseXpos – player.Width / 2);
     player.SetValue(Canvas.TopProperty, _mouseYpos – player.Height / 2);
 
     // Set the tag to identify the player
     string elementName = “offensiveplayer” + (++_offensivePlayerCount).ToString();
     player.Tag = elementName;
     player.Name = elementName;
 
     // Dynamically add the event handlers
     player.MouseEnter += new MouseEventHandler(oPlayer_MouseEnter);
     player.MouseLeave += new MouseEventHandler(player_MouseLeave);
 
     // Add the player to the canvas
     LayoutRoot.Children.Add(player);
} 

Remove the dynamic controls:
The following event handler removes the shapes that were dynamically created on the canvas. It assumes the existance of LayoutRoot and a global _shapeCount integer.

private void btnClearShapes_Click(object sender, System.Windows.RoutedEventArgs e)
{
    // Make a copy of uielements in order to remove the desired shapes
    UIElement[] tmp = new UIElement[LayoutRoot.Children.Count];
    LayoutRoot.Children.CopyTo(tmp, 0);

    // Iterate the uielements
    foreach (UIElement uielement in tmp)
    {
        Shape myShape = uielement as Shape;

        // Make sure we have a shape and the shape has a tag
        if (myShape != null && myShape.Tag != null)
        {
            // We only want to remove our dynamically created shapes
            if (myShape.Tag.ToString().Contains(“mycustomshape”))
            {
                LayoutRoot.Children.Remove(uielement);
            }
        }
    }

    _shapeCount = 0;
}

How to Embed Video Content in SharePoint

December 2, 2009 1 comment

I am frequently asked about the rich content that appears in the SharePoint sites I have developed.  Specifically the video, Silverlight and Flash content.  The most common question is “how do you create a SharePoint site that doesn’t look like SharePoint?”  While the technical answer to that question is a little complex, the simple answer (that provides the ability to provide video content) is actually pretty simple.

Although some of the following pre-requisites may already be in place, you will need a document library and a web part page.

1Create a Document Library to contain the Web Part Pages (aspx).  These files must have a home, but you can use an existing library if a suitable one exists.  The name of the library is somewhat arbitrary, but should be as consise as possible.  It is also a good idea to provide an accurate description of the library.
   
2Create the Web Part Page or modify an existing page that will contain the video content.
   
3Edit the newly created Web Part Page and add a ‘Content Editor Web Part’.
   
4Enter the Embed code (either manually or by cut-and-pasting from YouTube, etc) into the source editor of the CEWP.
   
5Exit from editing mode of the Web Part Page and you should now see a video player with your video.
   
6If you are using a publishing site, with corresponding web content management enabled, the steps are slightly different, just add the CEWP and Embed code.  Don’t forget to check-in and publish your changes.
Categories: HowTo, SharePoint Tags: , ,
Follow

Get every new post delivered to your Inbox.