Curves make everything look better
02 September 08 09:43 AM | Coding4Fun | 1 Comments   

CurvedScrollBar1[1] Charles Petzold blogged about a rather interesting, while geeky, topic a bit ago about non-affine transforms.  I personally had to look up what that exactly meant, but what it allowed Charles to create create curved slider bars with WPF.

Charles has a 2D shown to your right, my left, XAML example along with a 3D transform too.

  • Direct link to 2D example: Here
  • Direct link to 3D example: Here

His blog post goes on to explain the needed settings and issues on doing this.

Filed under:
Zooming in deeper with custom tiles
29 August 08 12:46 PM | Coding4Fun | 1 Comments   

image_e20fdfba-90b4-413f-bc22-7ec79aefa6a4[1]

Mike Ormond and Mike Taulty each have an entry on DeepZoom and creating MultiScaleTileSources for Silverlight 2.

Mike Ormond’s example is a Mandelbrot set which is pretty cool.  Wikipedia has an amazing write-up about what exactly a Mandelbrot set is, but it is a perfect example for showing off DeepZoom and the MultiScaleTileSource.

So why would someone need a custom source to do DeepZoom?  Not every solution is able to use the DeepZoom composer.  I could have parsed images already such as map imaging or a data source that is calculated on the fly.

Both Mike’s, awesome job!

Filed under:
Doodles in Silverlight
25 August 08 10:47 AM | Coding4Fun | 0 Comments   

imageEver want to do writing recognition on the Internet? Julia Lerman wrote an article for MSDN article that demonstrates how you can use InkPresenter in the .Net framework with Silverlight.  The interesting thing with the InkPresenter is you don’t need a Tablet PC to use it.  Plus you can use the built in handwriting recognition to get back what you write!

If you want a demo of her amazing application, you can play with the demo over at her blog.

Filed under:
Your Code Sunk My Battleship!
24 August 08 11:00 AM | Coding4Fun | 3 Comments   

Clarity Battleship is a multi-player game in which players code the "artificial intelligence" needed to command their fleet to victory on the high seas. The game is built using WPF and WCF.
Bryan's Blog

Difficulty: Intermediate
Time Required: 1-3 hours to create your own fleet
Cost: Free
Software: Visual Basic or Visual C# Express Editions
Hardware:
Download: Download

    Clarity Battleship

    At Clarity Consulting we’re always looking for a little friendly competition. That’s why a few times a year we hold coding competitions that we call Tech Challenges. I recently organized one based on the classic board game Battleship.

    The flow of the game is based loosely on the board game. The simple goal is to sink all of your opponents’ ships. Since we’re writing code though, I decided to step up the game play and make it a more interesting, requiring more strategy than luck.  Just like the board game, the battlefield is a grid. Unlike the classic, however, multiple teams can battle at the same time. Each team’s fleet is assigned to a region of the Battlefield.

    In our tournament we had six teams battle at a time and held one “Battle Royale” with eleven teams.  Below you can see a sample screen shot of a game with three teams. Blocks in red indicate damage. The bottom of the screen displays messages broadcast or information about fleets that have been sunk. 

    Screen Shot

    Teams position ships at the beginning of the game and give ships orders to execute including:

    • Attacking locations on the battlefield
    • Performing reconnaissance on an area of the battlefield
    • Broadcasting messages to opponents or conspirators via an “open radio frequency” (collusion and deception are allowed and encouraged!)

    Game play is pseudo turn-based. Teams are notified by the game when their ships are ready to execute an order. Teams are also notified as ships are damaged or sunk. The game ends when only one team remains.

    Application Architecture

    Now that you have a feel for the game play, let’s talk about the code. One reason for building this game was to give myself a fun way to learn more about Windows Communication Foundation (WCF) and Windows Presentation Foundation (WPF), new features of the .NET Framework 3.0.

    WCF provides a new unified mechanism for client-server communication that greatly simplifies that amount of work necessary to by standardizing the way you build your communication pieces. I recommend reading this article as a good place to start learning about WCF.

    WPF enables richer user interfaces and better integration between developer and designer through the use of XAML. As you can see by my simple (though I think pretty cool) UI, I focused my interest on WCF, but did take advantage of a bit of what WPF has to offer.

    Overview

    The Battleship application is divided into three parts. The Battleship.Components project is a shared assembly that contains the classes which manage the communication and the logic of the game as well as class definitions for all of the ships (i.e. AircraftCarrier, Battleship, etc.). The Battleship.Gameboard uses WPF to display the action on the battlefield. Finally, console applications are built by each team wishing to compete.

    The diagram below shows how the pieces fit together.

    Architecture Diagram - Overview

    WCF Communication

    As I mentioned, my focus in development was using WCF to manage the communication between the fleets and the game. I was very interested in exploring the bidirectional communication that can be achieved with WCF because it seemed like a perfect fit for the scenario. A traditional web service can receive messages from clients and send back responses. However, it can’t originate a message on its own to send to the client. For example, with a web service I could easily have a fleet tell the game about an order to execute (i.e. “I want my Battleship to attack 7,2”). However, I can’t have that web service inform another team that its ship was just sunk.

    With WCF I was able to achieve this without writing a lot of custom code. There is some complexity in the code, but most of that is because my goal was to hide the communication layer from the building of a fleet so that players could simply focus on writing the code to implement their strategy. The following sections will walk through the flow of the communication.

    Server Side

    While the Battleship.GameBoard is Windows Forms App, it actually should be considered the server in this application. That’s because it hosts the WCF service that the Fleets call.

    To define a WCF service, you start by defining the interface for the service. Similar to the WSDL of a web service, this is going to tell consumers what the contract, or inputs and outputs, of the service are. Callers will call the different operations exposed by the service.

    In this application, the IBattleshipGameService interface seen below defines the contract for the service.

    [ServiceContract(CallbackContract=typeof(IBattleshipGameServiceCallback))]
    public interface IBattleshipGameService
    {
        [OperationContract(IsOneWay = true)]
        void RegisterFleet(Fleet fleet);
    
        [OperationContract(IsOneWay = true)]
        void ExecuteOrder(string shipID, Order order);
    }

    The interface shows that there are two methods for consumers to call, RegisterFleet and ExecuteOrder. The OperationContract attribute indicates that these are methods. The IsOneWay parameter of the attributes indicates that no response is sent back to callers. That probably seems straightforward for the RegsterFleet call, but you might expect that ExecuteOrder might return a result.

    Actually what happens is that when a fleet is registered, the service holds on to a channel for calling back to the fleets. And the ExecuteOrder method only queues up an order for processing, but doesn’t immediately execute it. Before queuing it up, the game logic ensures that there aren’t already too many pending orders in the queue for the ship. This prevents a team from cheating by blasting the server with orders. We’ll delve more into how the communication back to the client is achieved later.

    With the interface to the service defined, let’s turn our attention to a portion of the application configuration file.

    <configuration>
      <system.serviceModel>
        <services>
          <service name="Clarity.Battleship.Components.GameSide.BattleshipGameService" 
                        behaviorConfiguration="BattleshipGameServiceBehavior">
            <endpoint address="http://localhost:8088/BattleshipGameService"
                      binding="wsDualHttpBinding"
                      contract="Clarity.Battleship.Components.GameSide.IBattleshipGameService"/>
          </service>

    This shows the definition of the service. The contract attribute indicates the service will adhere to the IBattleshipGameService interface. The binding attribute indicates that the WSDualHttpBinding will be used. This is the plumbing that allows both services and clients to send and receive messages.

    With the interface and configuration in place, a concrete implementation has to be built. The BattleshipGameService class provides this. This class implements the IBattleshipGameService interface described above. The actual code for registering a fleet and executing an order are therefore defined here.

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,UseSynchronizationContext = false)]
    public class BattleshipGameService : IBattleshipGameService

    Note the ServiceBehavior attribute and its InstanceContextMode property that decorate the BattleshipGameService class. WCF uses this attribute to decide how to execute the operation when a call comes into the service. In this case, the attributes indicate that the service should run as a singleton. In other words, all calls will be executed by a single instance of the BattleshipGameService. You can further see this in the following code taken from the constructor of the Game class that shows how the service is actually brought to life.

    Uri u = new Uri("http://localhost:8088/BattleshipService");
    _gameHost = new ServiceHost(new BattleshipGameService(), new Uri[] { u });
    _gameHost.Open();

    The ServiceHost (which does what it sounds like and hosts the service) is created by passing in an instance of our service object and the uri for the address of the service (I know the uri seems redundant since it’s in the config, but as far as I saw I had to use this constructor). Since we know the service host will just use the single instance of the BattleShipGameService, we can track that instance through a private property for convenience and hook its events as seen in the code snippets below.

    private BattleshipGameService BattleshipGameService
    {
        get
        {
            return (BattleshipGameService)_gameHost.SingletonInstance;
        }
    }
    
    this.BattleshipGameService.FleetRegistered +=
       new FleetRegisteredEventHandler(BattleshipGameService_FleetRegistered);
    this.BattleshipGameService.OrderExecuted += 
       new OrderExecutedEventHandler(BattleshipGameService_OrderExecuted);

    This allows us to elegantly pass off the calls to the Game class. The service then acts as a simple pass through and leaves the Game class to manage the game.

    Client Side

    Now that we’ve covered the basics of the server side, let’s look at what happens on the client side. In each console app, a class is created that derives from the FleetCommander class (there are complete directions on how to do this with the downloadable source). The FleetCommander class exposes all of the ships of the Fleet for the team to program against.

    To avoid cheating, (some would call it creative programming) each ship gets a unique identifier set by the Game at startup. That way the Game knows which orders are legitimate. To hide that id and details from the FleetCommander and make a very simple and intuitive interface, the method for executing an order is exposed off of the ship classes. The code snippet below shows how FleetCommander could react to an event indicating that a ship is ready for orders. In this case it is saying that the ship should attack the coordinate at location _targetX, _targetY.

    public override void OnShipAwaitingOrders(Ship ship, Order lastOrder)
    {
          Order orderToExecute = new Order();
          orderToExecute.Coordinate = new Coordinate(_targetX, _targetY);
          orderToExecute.Type = OrderType.Attack;
          ship.ExecuteOrder(orderToExecute);

    Under the covers, the Ship.ExecuteOrder method raises an event which is handled by the base FleetCommander class. The FleetCommander calls the appropriate method on a WCF client class which makes the call to the BattleshipGameService.

    A portion of the definition of the WCF client can be seen below. You’ll see that it is a class that derives from the DuplexClientBase. This class manages the channels that pass messages back and forth. You can think of it as similar to a web service proxy class.

    public partial class BattleshipGameServiceClient : 
        System.ServiceModel.DuplexClientBase<IBattleshipGameService>, IBattleshipGameService
    {

    So that covers how messages are sent to the server, but you may be asking yourself “How did a FleetCommander find out it that a ship was awaiting orders?” or for that matter “How does it get notified about anything?”

    Well, each FleetCommander has an instance of a listener class which receives callbacks from the game service. The way this is set up for the listener is very similarly to how we set up the service. Once again we start with an interface, in this case the IBattleshipGameServiceCallback interface.

    public interface IBattleshipGameServiceCallback
    {
        [OperationContract(IsOneWay = true)]
        void OnFleetUpdated(Fleet fleet, FleetUpdateReason reason);
    
        [OperationContract(IsOneWay = true)]
        void OnGameStateChanged(GameInfo gameInfo);
    
        [OperationContract(IsOneWay=true)]
        void OnOrderExecuted(string shipID, Order lastOrder);
    
        [OperationContract(IsOneWay = true)]
        void OnMessageReceived(string data, Coordinate c);
    
        [OperationContract(IsOneWay = true)]
        void OnFleetSunk(string fleetName);
    }

    Just like before the OperationContract attributes are used to indicate the methods available. And just like before we need a concrete implementation of the interface. Enter the FleetCommanderListener.

    public class FleetCommanderListener : IBattleshipGameServiceCallback

    The FleetCommanderListener is used when creating the BattleshipGameServiceClient. As you can see in the constructor definition below, a callbackInstance parameter must be passed in. The BattleshipGameServiceClient can then handle communication to the server via the IBattleshipGameService interface and also listen for communication back that adheres to the IBattleshipGameServiceCallback interface!

    public BattleshipGameServiceClient(System.ServiceModel.InstanceContext callbackInstance) :
         base(callbackInstance)

    The last little piece of the puzzle is the client configuration file.

      <system.serviceModel>
        <client>
          <endpoint name="Clarity.Battleship.Components.IBattleshipGameService"
                    address="http://localhost:8088/BattleshipGameService"
                    binding="wsDualHttpBinding"
                    bindingConfiguration="BattleshipBinding"
                    contract="Clarity.Battleship.Components.GameSide.IBattleshipGameService" />
        </client>
        <bindings>
          <!-- configure a binding that support duplex communication -->
          <wsDualHttpBinding>
            <binding name="BattleshipBinding"
                     clientBaseAddress="http://localhost:6088/BattleshipGameClient/">
            </binding>
          </wsDualHttpBinding>
        </bindings>
      </system.serviceModel>

    As you can see from the example above, the configuration is fairly straightforward. Just like in the server config, we say we’re using the wsDualHttpBinding. The one additional piece of info is the clientBaseAddress which tell the server how to call back into the client.

    The Complete Picture

    So after reading all of this, you might be thinking “I thought he said there wasn’t much custom code needed.” I think that is still true in terms of the WCF. While certainly not trivial, it really boils down to building a couple interfaces, their concrete implementations, and filling out some config files. Most of the complexity came in was in building out the eventing model to simplify the interface for teams.

    The following diagram helps pull everything together by showing an example of the flow of the communication for execution of an order.

    Architecture Diagram - Flow

    1. The derived FleetCommander makes calls the ExecuteOrder method on a Ship (i.e. “I want my Battleship to attack 7,2”)

    2. The Ship raises an event which is handled by the FleetCommander base class which in turn calls to the BattleshipGameServiceClient

    3. This WCF client class makes the WCF call to execute the order

    4. The single instance of the service raises an event to the Game class with the order information

    5. The Game class which controls all the game flow enqueues the order

    6. After processing an order from the queue, the Game calls the OnOrderExecuted WCF callback which gets invoked on the FleetCommanderListener

    7. Finally the FleetCommanderListener raises an OrderExecuted event to the derived FleetCommander class (i.e. “Your Battleship’s attack at 7,2 resulted in a Hit”) which is turned calls the OnShipAwaitingOrders method and the cycle starts over

    WPF User Interface

    The last thing to cover with the architecture is the UI. It is pretty simple, but I wanted to experiment a little with WPF. The Gameboard assembly contains a class called Battlefield that is a WPF Window (comparable to a Winform Form). A Grid control makes up the main component of the gameboard. The grid lent itself to building the UI since everything stretches nicely to fit the screen, regardless of the number of teams competing.

    Once the game starts, the game board is setup by adding rectangles and images to the grid control. Throughout the game, the colors of the rectangles are changed to indicate shots, recon, or hit targets.

    Below is an example of some of the Battlefield code behind in which the rectangle for the location of the order is painted a different color depending on the result of an order.

    Rectangle r = _rectangles[_lastOrderStarted.Order.Coordinate];
    if (e.Order.Result == OrderResult.ShipHit)
    {
        r.Fill = Brushes.Red;
        _rectangleFills[e.Order.Coordinate] = r.Fill;
    }
    else if (e.Order.Result == OrderResult.ShipSunk)
    {
        r.Fill = Brushes.Red;
        _rectangleFills[e.Order.Coordinate] = r.Fill;
    }
    else if (e.Order.Result == OrderResult.Miss)
    {
        r.Fill = _rectangleFills[e.Order.Coordinate];
    }
    else
    {
        r.Fill = _rectangleFills[e.Order.Coordinate];
    }

    Conclusion

    Hopefully you enjoyed this game and learned a little in process. I encourage you to download the code and build your own fleet. The download includes a document called “Clarity Battleship – Building a FleetCommander” which gives you step by step instructions. Feel free to post your own builds here for other people to challenge and good luck with your battles!

    Bryan Dougherty is a Principal with Clarity Consulting, a software development consulting firm based in Chicago, IL. He is an MCP with several years of professional software engineering experience. Bryan earned a B.S. in Computer Science from Northwestern University and writes about topics related to software development on his blog.

    Chat with the experts!
    15 August 08 02:30 PM | Coding4Fun | 1 Comments   

    268788533_0ff2269aa0[1] Have a hard question about Internet Explorer 8, Windows Mobile or Windows Embedded?  Do you want to tap into the deep knowledge of the talented Microsoft Embedded Devices Group members and the IE product team?

    If so, please join us for a live chat and bring on the questions!

    MSDN has chats that can help answer your tough questions.

    http://msdn.microsoft.com/en-us/chats/default.aspx has a list of times and dates for each of the chats.  The mobile team even has chats planned all the way out to December!

    Filed under:
    Stall Status: Know before you go
    13 August 08 11:03 AM | Coding4Fun | 1 Comments   
     icon Stall Status is a Silverlight-based Vista Sidebar Gadget that uses the Z-Wave wireless protocol and door sensors to notify you of the occupied/available state of the bathroom stalls.
    Clarity Consulting, Inc

    Difficulty: Easy
    Time Required: 1-3 hours
    Cost: $50-$100
    Software: Visual C# Express Edition
    Hardware: ControlThink Z-Wave SDKHawking Technologies Z-Wave HRDS1 door sensor
    Download: Download

      Stall Status

      Every now and then someone throws out an idea for a completely off-the-wall application that just has to be built. When Jon Rauschenberger, Clarity’s CTO, came into my office with his “brilliant idea” for a monitoring system to track the “occupied/available” state of our washroom stalls, I immediately recognized it as one of those moments. I had been doing some research on the Z-Wave wireless protocol for a client project earlier that week, and I thought “Stall Status” would be a fun way to get some hands on experience using Z-Wave.

      In this article I will walk you through how to write managed code that interacts with Z-Wave devices. I’ll also show how to use Silverlight 2.0’s access policies to write “connected clients”: client applications that establish a persistent TCP connection to a remote server and thereby avoid having to poll the server for status changes. Finally, I’ll walk through the steps necessary to deploy a Silverlight 2.0 application as a Windows Vista Sidebar Gadget.

      What is Z-Wave?

      Z-Wave is a wireless communication protocol that works over radio frequency and is specifically designed for low-power, low-bandwidth usage scenarios. Typical usage scenarios for Z-Wave devices are monitoring and control applications – such as home automation. Available devices include door sensors, switches, and motors. Z-Wave devices are interoperable - devices labeled as Z-Wave compliant should all work together.

      A Z-Wave network consists of one or more devices and a centralized controller. A controller can be a standalone (often hand held) hardware unit or a software-based kit. Devices on a Z-Wave network handle the routing of messages automatically without the need to set up pre-defined routes. This means that if you have several devices in your network that need to communicate together (e.g. a door sensor and an alarm), the devices can route messages through each other. This “mesh” communication capability allows you to extend the range of your network much farther than you would be able to if the devices all required direct connections to each other.  For example, if you have three devices, A, B and C, device A can communicate with device C, even if C is outside of A's range, by routing its messages through device B.  This all works automatically.

      My simple Z-Wave network for Stall Status consists of door sensors to notify me when a stall door is opened and closed, and a software based controller. I used Hawking Technologies’ HRDS1 battery powered door sensors for each stall door in the washroom. The HRDS1 is considered an “occasionally on” device – it quietly sits in sleep mode until it detects an open/close event from the door. This is the same type of device you would use, for example, when building an alarm system for monitoring windows and doors.  For the Z-Wave controller I used an excellent software-based controller and SDK from ControlThink, which you can purchase for $70. The controller consists of a USB dongle and a set of APIs for connecting to and communicating with devices. ControlThink includes a number of .Net sample applications, but be warned that the sample applications are not device specific, and the available devices usually assume you are integrating them into an existing hardware-controlled environment, so the documentation surrounding their usage tends to be sparse.

      Using the ControlThink SDK is very straight forward. You simply plug in the USB dongle, reference their DLL from your .Net application, and connect to the controller with a single line of code. Once connected, you can manage your network by adding devices, removing devices, iterating the list of devices, etc.

      I ended up writing three applications to support Stall Status:

      1. An administrative application for adding/removing/listing the Z-Wave devices on my network.  This is called StallStatusAdmin.
      2. A Windows Service to listen for open/close events from the door sensors and notify any connected client.  This is called StallStatusController.
      3. A Silverlight 2.0 client application (the end-user interface) that connects to the Windows Service to receive event notifications.  This is called StallStatusSilverlight.

      Setting up the Z-Wave network

      The administration application is a simple Windows Forms EXE that allows me to manage the network by adding, removing and listing the devices. This is simple to do using the ControlThink SDK – in most cases involving just a couple lines of code. Each Z-Wave device has some mechanism to put the device into “programming mode” . The HRDS1 has a button on the back that when pressed, puts the device into programming mode and allows the device to accept programming codes from the controller.

      Listing 1 shows how to add a device to the network. Adding a device consists of registering the device with the controller, and then creating a relationship between the controller and the device's association group to enable the device to route messages to the controller. Once a device is registered, the controller assigns a unique NodeID that we will use to differentiate the three sensors from each other.

      C#

      ZWaveController controller = Connect(); 
      MessageBox.Show("After pressing OK, press the \"programming\" button on your device.");
      ZWaveDevice device = controller.AddDevice();
                  
      device.Groups[1].Clear();
      device.Groups[1].Add(controller.Devices.GetByNodeID(controller.NodeID));
      VB.Net
      Dim controller As ZWaveController = Connect()
      MessageBox.Show("After pressing OK, press the ""programming"" button on your device.")
      Dim device As ZWaveDevice = controller.AddDevice()
      
      device.Groups(1).Clear()
      device.Groups(1).Add(controller.Devices.GetByNodeID(controller.NodeID))

      Listing 1 – Adding a device to the network.

       

      Getting a list of the registered devices on the network is as easy a iterating through the Devices collection on the controller.

      C#

      string result = "";
      ZWaveController controller = Connect();
      
      if (controller.Devices.Count > 0) {
         foreach (ZWaveDevice d in controller.Devices)    {
          result += d.GetType().ToString() + " as Node #" + d.NodeID + " PollEnabled = " + d.PollEnabled + "\r\n";
         }
      }
      else {
         result = "No devices found on the network";                
      }
      MessageBox.Show(result);
      VB.Net
      Dim result As String = ""
      Dim controller As ZWaveController = Connect()
      
      If controller.Devices.Count > 0 Then
         For Each d As ZWaveDevice In controller.Devices
          result &= d.GetType().ToString() & " as Node #" & d.NodeID & " PollEnabled = " & d.PollEnabled & Constants.vbCrLf
         Next d
      Else
         result = "No devices found on the network"
      End If
      MessageBox.Show(result)

      Listing 2 – Listing the devices in the network.

      Receiving Z-Wave Events

      Once the devices are registered on the network, they will send event notifications back to the controller each time the sensor is triggered. The next steps for us are to write code to receive the events and forward them to any client applications that are connected. To do this we’ll write a Windows Service that listens for events from the sensors.

      All of the work for listening for events from the Z-Wave devices is handled for us by the ControlThink SDK. We simply connect to the controller and sink the LevelChanged event. We do this in our Run method, which is called from within our service’s OnStart function.

      C#
      public void Run() {
         try  {
             _controller = new ZWaveController();
             try  {
                _controller.Connect();
             }
             catch (Exception ex) {
                throw new Exception("Unable to connect.\r\n" + ex.ToString());
             }
      
             _controller.LevelChanged += new ZWaveController.LevelChangedEventHandler(_controller_LevelChanged);
      
             _policyListener = new PolicyListener();
             _listener = new SocketListener();
             _listener.Port = 4530;
                   
              new System.Threading.Thread(new System.Threading.ThreadStart(_listener.StartSocketServer)).Start();
              new System.Threading.Thread(new System.Threading.ThreadStart(_policyListener.StartSocketServer)).Start();
              new System.Threading.Thread(new System.Threading.ThreadStart(ClearRecent)).Start();
         }
         catch (Exception ex) {
             Logger.WriteException(ex);
         }
      }

      VB.Net

      Public Sub Run()
         Try
             _controller = New ZWaveController()
             Try
                _controller.Connect()
             Catch ex As Exception
                Throw New Exception("Unable to connect." & Constants.vbCrLf & ex.ToString())
             End Try
      
             AddHandler _controller.LevelChanged, AddressOf _controller_LevelChanged
      
             _policyListener = New PolicyListener()
             _listener = New SocketListener()
             _listener.Port = 4530
      
              CType(New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf _listener.StartSocketServer)), System.Threading.Thread).Start()
              CType(New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf _policyListener.StartSocketServer)), System.Threading.Thread).Start()
              CType(New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf ClearRecent)), System.Threading.Thread).Start()
         Catch ex As Exception
             Logger.WriteException(ex)
         End Try
      End Sub

      Listing 3 – Listening for Z-Wave events when our service starts up.

       

      In addition to listening for events from the ZWave Controller, our Run method also sets up socket listeners for talking to the Silverlight client application, which we will talk about later. An important detail to note, however, is the use of threading in the Run method. Remember that this is called directly from our service’s OnStart code which we should not block - if you block OnStart, you’ll see the service stuck at “Starting...” in the Service Control Manager. Anything that will block or that is long running (such as a socket listener) needs to run on a separate thread.

      When the controller detects that one of the sensors has changed its state, it throws the LevelChanged event to our service. Our service handles LevelChanged in the _controller_LevelChanged method. The signature for the LevelChanged event looks like this:

      void _controller_LevelChanged(object sender, ZWaveController.LevelChangedEventArgs e)

      The LevelChangeEventArgs contains the original device that raised the event. We have three door sensors connected to our network. When any of them are triggered, LevelChanged is raised and we can inspect the LevelChangedEventArgs to get the NodeID of the unique identifier of the device. That’s all there is to interacting with the Z-Wave network.

      Silverlight 2.0

      Now that we’ve got the server infrastructure set up it is time to build a client application so we can actually start using Stall Status. I built the client application in Silverlight as an exercise to show how to use Silverlight 2.0’s access policy to make cross domain network calls from a Silverlight client application. I also knew that it is simple to deploy a Silverlight application as a Windows Vista Gadget, and the Sidebar was to be my preferred deployment model for the application.

      StallStatus2

      Figure 1 – Stall Status interface

      The main UI for the application is pretty simple – three ellipses, one for each stall, colored green if the stall is available and red if the stall is occupied. Most of the challenge with building the client piece has to do with connecting to the service and listening for updates. To do this, we create a persistent TCP connection and wait for data to be sent from the service over the socket. This is much better than a polling approach for an application like this because of the way the Z-Wave door sensors work. They are in sleep mode most of the time, and are only using power when they transmit a signal due to the door opening or closing. If we polled the devices frequently, it would kill the batteries in the device. Also, most of the time there is no change to the state of the doors, so polling would really be a waste.

      Silverlight contains certain security mechanisms around network connectivity, especially TCP sockets. This is due to the fact that a Silverlight application runs in the context of the user’s browser, so special controls need to be in place to limit the type of connectivity that Silverlight applications can initiate. For socket-based connections, Silverlight 2.0 requires an access policy to be in place on the target server. This access policy essentially is a challenge/response mechanism that prevents a Silverlight application from connecting to an arbitrary server, potentially masquerading as the end user.

      Access Policy

      An Access Policy must be in place on the server for in order to enable a Silverlight 2.0 client to connect using sockets. The Silverlight framework handles all of the validation for the presence of the access policy, so your client application does not need to do anything. However, if the proper policy is not in place on the target server, Silverlight will throw an Access Denied exception, so your client application should be prepared to handle this situation. This is all very similar to how network access in Flash applications work. In fact, Silverlight can consume Flash policy files directly, as well as Silverlight policy files. In the Stall Status application, we’re going to be using Silverlight policy.

      When a Silverlight application attempts to open a socket to a target server, Silverlight will automatically look for an access policy on the server by establishing a TCP connection over port 943, and sending a policy request. The policy request is simply an XML-style string: <policy-file-request/>. It is up to the author of the service that is receiving the request to ensure that they properly respond to this request, or else Silverlight will raise an exception on the client. All of this is described in detail in the MSDN documentation on the new network security restrictions in Silverlight 2.0.

      In order to respond to a request for an access policy on our server, we need to implement a network listener on port 943 that responds to Silverlight’s policy file request. Dan Wahlin wrote a multi-part blog post showing exactly how to do this, and the listener I used for Stall Status, plus much of the other socket code, is copied from his example. I recommend reading his post - it is a great primer on writing TCP socket clients in Silverlight 2.0.

      Our listener class run in our windows service and simply sets up a listener on port 943. When it receives a policy file request, it returns the appropriate response, as shown below.

      <?xml version="1.0" encoding ="utf-8"?>
      <access-policy>
        <cross-domain-access>
          <policy>
            <allow-from>
              <domain uri="*" />
            </allow-from>
            <grant-to>
              <socket-resource port="4530" protocol="tcp" />
            </grant-to>
          </policy>
        </cross-domain-access>
       </access-policy>

      This response tells Silverlight to allow incoming connections to port 4530, which is the port that our service is listening on to accept connections from our Silverlight client.

      Why is this important? Well, without access policy in place, there is nothing that prevents a malicious Silverlight application from connecting to a server without permission. For example:

      • Suppose you have an active session with your online bank. A malicious Silverlight application served up from Site A could attempt to connect to your bank using your existing login token (which may be stored as a cookie). With access policy in place, your bank would need to have a policy stating that it allowed Silverlight applications originating from Site A to connect to your bank.
      • Suppose you connect to Site A and download a malicious Silverlight application. The application can potentially connect to your corporate intranet and because you are on a corporate domain, the Silverlight app impersonates you. With the access policy rules in place, this would be prevented.

      Persistent client connections

      Now that we’ve got our access policy in place, we’re ready to code up our Silverlight client to connect to our server and wait for updates. Silverlight 2.0 can only connect using sockets over the port range 4502-4534. Our Windows Service uses 4530. It creates a listener on this port and then sits and waits for connections from our Silverlight clients.

      C#

      _listener = new TcpListener(IPAddress.Any, Port);
      _listener.Start();
      while (true)
      {
         _waitEvent.Reset();
         _listener.BeginAcceptTcpClient(new AsyncCallback(OnBeginAccept), null);
         _waitEvent.WaitOne();
      }

      VB.Net

      _listener = New TcpListener(IPAddress.Any, Port)
      _listener.Start()
      Do
         _waitEvent.Reset()
         _listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf OnBeginAccept), Nothing)
         _waitEvent.WaitOne()
      Loop

      Listing 4 – Our main listener for client connections

       

      We’re using asynchronous sockets, so we’ve set up a delegate – OnBeginAccept – to accept and process our connections. The code to process the connects is listed below.

      C#

      _waitEvent.Set();
      TcpListener listener = _listener;
      TcpClient client = listener.EndAcceptTcpClient(ar);
      
      if (client.Connected)
      {
         Logger.WriteLine("Accepted a connection from " + client.Client.RemoteEndPoint.ToString());
      
         StreamWriter writer = new StreamWriter(client.GetStream());
         writer.AutoFlush = true;
         _clients.Add(writer);
         writer.WriteLine("Connected.");
      
         if (ClientConnected != null)
         {
           ClientConnected(this, null);
         }
      }

      VB.Net

      _waitEvent.Set()
      Dim listener As TcpListener = _listener
      Dim client As TcpClient = listener.EndAcceptTcpClient(ar)
      
      If client.Connected Then
         Logger.WriteLine("Accepted a connection from " & client.Client.RemoteEndPoint.ToString())
      
         Dim writer As New StreamWriter(client.GetStream())
         writer.AutoFlush = True
         _clients.Add(writer)
         writer.WriteLine("Connected.")
      
         If ClientConnected IsNot Nothing Then
           ClientConnected(Me, Nothing)
         End If
      End If

      Listing 5 – Accepting a new client connection

       

      Here we are simply adding a StreamWriter for each connected client to a List. We do this so when we receive events from the door sensors, we can loop through this List and notify all of the clients. We notify them by writing a tokenized string to the StreamWriter. We also have code to remove any clients from the list if we fail to write to their stream. This way we can catch the situation where the client disconnected.

      C#
      for (int i=_clients.Count-1;i>=0;i--)
      {
         try
         {
            _clients[i].WriteLine(eventText);
         }
         catch (Exception ex)
         {
            Logger.WriteException(ex);
            Logger.WriteLine("Removing client # " + i + " because we failed to send them data.");
            _clients.Remove(_clients[i]);
         }
      }

      VB.Net

      For i As Integer = _clients.Count-1 To 0 Step -1
         Try
            _clients(i).WriteLine(eventText)
         Catch ex As Exception
            Logger.WriteException(ex)
            Logger.WriteLine("Removing client # " & i & " because we failed to send them data.")
            _clients.Remove(_clients(i))
         End Try
      Next i

      Listing 6 – Sending an update to all clients

       

      The text we pass to each client (represented in the code above by the eventText variable) is simply the NodeID of the sensor that triggered the event and the state (open/closed) on the sensor. The Silverlight client receives this text, parses it out, and updates the color of the ellipse accordingly.

      C#
      private void UpdateText(string text)
      {
          string[] parts = text.Split(' ');
      
          if (parts.Length != 2) {
              return;
          }
      
          int stallNumber = Convert.ToInt32(parts[0]);
          string status = parts[1].ToLower();
      
          StatusIndicator thisStall = null;
          switch (stallNumber) {
              case 1:
                  thisStall = this.Stall1;
                  break;
              case 2:
                  thisStall = this.Stall2;
                  break;
              default:
                  thisStall = this.Stall3;
                  break;
          }
      
          if (status.Trim() == "open") {
              thisStall.Status = StallStatus.Open;
          }
          else if (status.Trim() == "closed") {
              thisStall.Status = StallStatus.Closed;
          }
          else if (status.Trim() == "recent") {
              thisStall.Status = StallStatus.Recent;
          }
          else {
              thisStall.Status = StallStatus.Unknown;
          }
      }
      VB.Net
      Private Sub UpdateText(ByVal text As String)
          Dim parts() As String = text.Split(" "c)
      
          If parts.Length <> 2 Then
              Return
          End If
      
          Dim stallNumber As Integer = Convert.ToInt32(parts(0))
          Dim status As String = parts(1).ToLower()
      
          Dim thisStall As StatusIndicator = Nothing
          Select Case stallNumber
              Case 1
                  thisStall = Me.Stall1
              Case 2
                  thisStall = Me.Stall2
              Case Else
                  thisStall = Me.Stall3
          End Select
      
          If status.Trim() = "open" Then
              thisStall.Status = StallStatus.Open
          ElseIf status.Trim() = "closed" Then
              thisStall.Status = StallStatus.Closed
          ElseIf status.Trim() = "recent" Then
              thisStall.Status = StallStatus.Recent
          Else
              thisStall.Status = StallStatus.Unknown
          End If
      End Sub

      Listing 7 – Receiving the update on the client from the server

       

      The only other thing the application contains is the concept of "recently occupied". Once a stall has been vacated, we track it as recently occupied. This shows up on the client application as a yellow ellipse. To do this we keep track of a timestamp whenever the door opens.  Our Service contains a dedicated thread that checks for doors opened more than 2 minutes ago. If it finds any, it changes the door's status from “Recent” to a status of “Opened”.

      C#
      private void ClearRecent()
      {
        while (!_wait.WaitOne(10000,false))
        {
          var q = from stall in _stalls
            where stall.Timestamp.AddMinutes(2) < DateTime.Now && stall.State.Equals(DoorState.Recent)
            select stall;
      
          foreach (Stall stall in q)
          {
            if (stall.State.Equals(DoorState.Recent)) {
              stall.State = DoorState.Open;
              Broadcast(stall.NodeID, DoorState.Open);
            }
          }
        }
      }
      VB.Net
      Private Sub ClearRecent()
        Do While Not _wait.WaitOne(10000,False)
          Dim q = From stall In _stalls _
                  Where stall.Timestamp.AddMinutes(2) < DateTime.Now AndAlso stall.State.Equals(DoorState.Recent) _
                  Select stall
      
          For Each stall As Stall In q
            If stall.State.Equals(DoorState.Recent) Then
              stall.State = DoorState.Open
              Broadcast(stall.NodeID, DoorState.Open)
            End If
          Next stall
        Loop
      End Sub

      Listing 8 – Clearing the “recently opened” flag

      Vista Sidebar Gadget

      Once I had the Service and Silverlight client apps written, it was time to deploy the client as a Vista Sidebar Gadget. This is actually pretty simple to do with a Silverlight application, but there are a couple things to work through for 64-bit versions of Vista.

      Packaging a Silverlight application to run as a Gadget is not that different than running it locally or via a web page. You simple collect all of the files for your application, add a manifest file, zip them up, and rename the ZIP file so it has a .gadget file extension.

      One easy way to create the manifest file is to start from an existing file from one of your existing gadgets. You can find your installed gadgets in the folder \Users\<user name>\AppData\Local\Microsoft\Windows Sidebar\Gadgets. Note that by default the AppData folder is hidden. Check the folders of any of your gadgets and you’ll see that they all contain an gadget.xml file. Copy one of these, open it, and make any changes that you need to. Most of the elements in the file are self explanatory, but for a full explanation, check out this article.

      Once you’ve got your files and manifest packaged up, you can distribute your gadget. Users can run .gadget files directly in Vista and Vista automatically installs them into the sidebar.

      StallStatusGadget2

      Figure 2 – Stall Status deployed as a Vista Sidebar gadget

      One note with Silverlight-based gadgets and the 64-bit version of Windows Vista: Since Silverlight is a 32-bit application, you cannot directly host Silverlight-based gadgets in the 64-bit version of Sidebar.exe (which is the running by default on 64-bit Vista). As a work around, you can run the 32-bit version of Sidebar.exe, which is located in the \Program Files (x86)\Windows Sidebar\ folder.

      As we’ve seen in this article it is easy to use .Net to control a Z-Wave network, and there are tons of creative uses for the technology. Writing network-enabled Silverlight applications has become much more powerful in Silverlight 2.0. And deploying Silverlight-based applications as Vista Sidebar Gadgets is pretty simple.

      Filed under: ,
      Your fly down? Zip it up natively.
      11 August 08 11:45 PM | Coding4Fun | 3 Comments   

      zipper Jaime Olivares got sick and tired of having to use the java.util.zip namespace or invoking shell API’s to produce a Zip file.  Jaime decided to create a pure .Net 3.0 / 3.5 class that can create / append to zip file.

      Here is a quick example on how he zips a file.

      ZipStorer zip;
      
      if (this.RadioCreate.Checked)
          // Creates a new zip file
          zip = ZipStorer.Create(TextStorage.Text, "Generated by ZipStorer class");
      else
          // Creates a new zip file
          zip = ZipStorer.Open(TextStorage.Text, FileAccess.Write);
      
      // Stores all the files into the zip file
      foreach (string path in listBox1.Items)
      {
          zip.AddFile(path, Path.GetFileName(path), "");
      }
      
      // Creates a memory stream with text
      MemoryStream readme = new MemoryStream(
      System.Text.Encoding.UTF8.GetBytes(string.Format("{0}\r\nThis file
          has been {1} using the ZipStorer class, by Jaime Olivares.",
      DateTime.Now, this.RadioCreate.Checked ? "created" : "appended")));
      
      // Stores a new file directly from the stream
      zip.AddStream("readme.txt", readme, DateTime.Now, "Please read");
      readme.Close();
      
      // Updates and closes the zip file
      zip.Close();

      Another awesome thing is you can use this class with the .Net Compact Framework.

      Filed under:
      Making Gravity do your bidding
      07 August 08 06:02 PM | Coding4Fun | 0 Comments   

      FunWithGravity7[1] The nice fellows at BoneSoft have created a neat little program at CodeProject that shows off how to do some pretty physics simulations in c#.  They talk about how they did the calculations.

      Here is how he does a full calculation loop:

      foreach (Particle p in particles) {
          ...
          if (particles.Count > 1) { 
              Vector a = new Vector();
              foreach (Particle p2 in particles) {
                  if (object.ReferenceEquals(p, p2)) { continue; }
                  Vector unit = p2.Location - p.Location;
                  float magnitude = (float)Math.Sqrt(
                      (unit.X * unit.X)
                      + (unit.Y * unit.Y)
                      + (unit.Z * unit.Z));
                  float factor = (GravitationalConstant * (
                      (p.Mass * p2.Mass) / (magnitude * magnitude * magnitude)
                  )) / p.Mass;
                  unit *= factor;
                  a += unit;
              }
              p.Velocity += a;
          }
          ...
      }

      Just a quick glance at the code, with the Parallel Programming extensions for .Net, I bet we could make this program able to handle more.

      Filed under:
      Silverlight, 44 examples to do pretty much everything
      05 August 08 03:43 PM | Coding4Fun | 0 Comments   

      e4952ae7-3399-43df-9816-df16b7e6d4fa[1] Mike Taulty did a spectacular collection of Silverlight 2.0 screencasts.  They range from the standard Hello World to data binding to file IO to threading.

      Channel 9 has a complete list of all 44.

      Filed under:
      AddOn Studio for World of Warcraft v2 beta
      31 July 08 03:29 PM | Coding4Fun | 3 Comments   

      For those lovers of World of Warcraft, The AddOn studio for Visual Studio v2 beta is now available on CodePlexChannel 9 even did an interview with some of the developers.


      Gabor Ratky and Attila Kisko: AddOn Studio for World of Warcraft
      Filed under:
      Silverlight controlling your workout
      28 July 08 01:01 PM | Coding4Fun | 1 Comments   

      Page Brooks created a neat Silverlight application that controls his treadmill.  Page openly admits it is a proof of concept and really lacks a real purpose, but from using some tools, he was able to create a very usable UI with minimal effort.

      Treadmill Controller

      Here is a video of it in action.

       

      Update:  I put down the wrong person, Page Brooks created this.  Sorry!

      Update 2: Page has a 2nd part of this 3 part series on their blog.

      Filed under:
      We want you to brag to us!
      22 July 08 11:59 AM | Coding4Fun | 0 Comments   

      Heroes Popfly WhiteHeroes Express White 

      Remember when your parents told you not to brag?  Don’t listen to them. 

      The Coding4Fun team wants you to tell us your story so we can feature you on our site!  PopFly or Visual Studio Express, both work!

      If you’re interested, send us your story to expop@microsoft.com

      Filed under:
      GeoTag, You’re it!
      21 July 08 01:21 PM | Coding4Fun | 0 Comments   

      Roiy Zysman has an interesting article on GeoTagging images.  With a few quick .Net image functions, Roiy was able to embed the GeoTag properties in.

      geotag

      Now if you really want to do GeoTagging and your camera doesn’t support it, I suggest syncing your GPS and camera together then merging the data from the GPS to the time stamps on your photos!

      Filed under:
      A terrarium in my computer? I’m more of a city person …
      16 July 08 11:30 AM | Coding4Fun | 1 Comments   

      whidbey_image001_3[1] Scott Parker alerted me that the Windows SDK team released TerrariumTerrarium’s source code can be found over on CodePlex too!

      So what is Terrarium?  Way back in .Net 1.x land, someone game up with the idea to create a game to get people interested and building cool stuff.  In Terrarium, you can create herbivores, carnivores, or plants and then introduce them into a peer-to-peer, networked ecosystem where they complete for survival. Terrarium demonstrates some of the features of the .NET Framework, including Windows Forms integration with DirectX®; XML Web services; support for peer-to-peer networking; support for multiple programming languages; the capability to update smart client, or Windows-based, applications via a remote Web server; and the evidence-based and code access security infrastructure.

      Here are a few of their hit list items to get fixed:

      • 3.5 framework/Visual Studio 2008 upgrade
      • Leverage 2.0 language features. Much of the code was 1.1 so generics and other goodness wasn’t there. The current codebase is compiled and built on Visual Studio 2005/2.0 Framework but not really making use of the features (yet). For example, all WinForms are 1.1 style (i.e. no partial classes). Same with the 3.5 upgrade where more cool stuff could be done all over the codebase.
      • Extend the current system by adding new features. Not sure off the top of my head what those features would be but there’s plenty of room for improvement.
      • ClickOnce install of the Terrarium Client from a Terrarium Server. This would be a nice-to-have since ClickOnce is a breeze to keep clients updated. However it would require some reshuffling of the current client as it requires additional files and ClickOnce has limitations on what it can put on a users machine.
      • XNA upgrade/port. This is pretty major as DirectX isn’t really all that abstracted away in the current system but the hope would be to bring Terrarium to the Xbox 360 (complete with networking support). This is probably a 4.0 release that could be a year or so away (but would kick the llamas’ butt)
      • The server project website is a bit of a mess (read:disaster). It was built in the 1.1 days and never updated. It contains a mixture of code behind files, raw class files, and aspx pages with embedded code. In short, it needs to be rewritten. The web services are okay, although with moving to 3.5 we should probably look at using WCF instead.

      They would love to have community members to help out too.

      Update:  Scott Hanselman has an article about Terrarium too.

      Filed under:
      Radiohead armed with lasers
      14 July 08 01:41 PM | Coding4Fun | 2 Comments   

      cliffs Radiohead did something pretty interesting.  They released their new music video, which was done all in LIDAR.  Their video is, for all intents and purposes, is just pure data!

      They have all the data for you to play with over at http://code.google.com/creative/radiohead/

      If you want to get it running on your PC, use need to grab a copy of Processing over at http://www.processing.org/download

      Filed under:
      More Posts Next page »
      Page view tracker