I'm a very big fan of readable code, that is why I use a lot of foreach statements, and I would like to iterate through all the buffers of a specific file and then do something on them. So why not use the IEnumerable interface for this. The following simple example is just that.
The first thing we need to do is make a method that returns an IEnumerable<byte[]>. This way we can use an foreach statement on the method. Then we need to open our file, very convenient with a using statement so we can be sure that whatever happens the filestream will be closed and we don't hold resources to long.
class Program {
public static IEnumerable<byte[]> GetBuffers(string filename) {
int numBytes = 0;
using (FileStream fs = new FileStream(filename, FileMode.Open)) {
do {
byte[] buffer = new byte[1024 * 8];
numBytes = fs.Read(buffer, 0, 1024 * 8);
if (numBytes > 0) {
yield return buffer;
}
} while (numBytes > 0);
}
}
static void Main(string[] args) {
foreach (byte[] buffer in Program.GetBuffers
(@"testfile.dat")) {
Console.WriteLine(buffer.Length);
}
Console.ReadLine();
}
}
At this moment it is really easy to access the buffers in the stream and take action on the buffers. Off course there should be some exceptionhandling, but that is easy enough.
After seven days of Barcelona, I'm all loaded up for the next step in development. I was updated on the technologies of tomorrow in a 5 days during training on a few km of the sea and in temperature of about 20 degrees while the sun was shining.
Of course there are a lot of post on the web about the top sessions in Barcelona, but there were two others that need some special attention because development doesn't always need to be about keeping your boss happy, but also keep yourself happy with "Coding for Fun". I was pleasantly surprised to see these sessions on TechEd Developers.
First of all there was the session about Microsoft Robotics Studio given by Martin Calsyn that was a really good introduction about the studio in general. I was pleased to see the the room was full. I was amazed about how many people like Robotics, it seems we need to see our code move things.
Then there was the session about XNA Game Studio given by Rob Miles, (this guy really rocks) he talked about writing games not only for fun but also professional. He gave a good impression on XNA and how easy it is to write games. I loved his cheese game and so did the all the others off the fully loaded room.
Conclusion, TechEd is about professional coding, but also about FUN. So check out the links and get started.
The new CTP of Robotics studio has been released since 7 november. Here are the links.
Long ago I wrote an Example on threading with the WinApi using Delphi, now we have AsyncCallBacks and managed threading. But since a few months we also have the CCR and take my word for it, this baby rocks. I will supply you guys with another run of the "Really Simple Sample" series and now it will be on the CCR. Here goes the first sample.
First off all I tried to build a winforms application running in the CCR way, I used the Ccr.Adaptors.WinForms namespace to accomplish this in a simple way. Just create a new WinForms application and change the Program class like follows.
static class Program {
//Expose the dispatcher queue for use in all your forms
public static DispatcherQueue DQueue {
get {
return _DispatcherQueue;
}
}
//Expose the WinFormsService Port for use in all your forms
public static WinFormsServicePort WFServicePort {
get {
return _WFServicePort;
}
}
private static DispatcherQueue _DispatcherQueue;
private static WinFormsServicePort _WFServicePort;
[STAThread]
static void Main() {
System.Threading.ManualResetEvent MainThreadEvent = new System.Threading.ManualResetEvent(false);
// Create the Dispatcher that will execute our delegates that we add to the
// DispatcherQueue
using (Dispatcher dispatcher = new Dispatcher(0, "BlogExample Dispatcher")) {
_DispatcherQueue = new DispatcherQueue("BlogExample DispatcherQueue", dispatcher);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Bind the DispatcherQueue to the WinformsAdaptor and
// create the WinFormServicePort.
_WFServicePort = WinFormsAdaptor.Create(_DispatcherQueue);
// Use the WinFormsServicePort to create a MainForm.
// We use a delegate to create the form on the right thread and
// bind a delegate to the HandleDestroy event of the form to let the
// application stop when the MainForm closes.
_WFServicePort.Post(new RunForm(
delegate { Form1 form = new Form1();
form.HandleDestroyed += delegate(object sender, EventArgs e) { MainThreadEvent.Set(); };
return form;
}
));
// Wait for the form to be closed, the WinFormsAdaptor is taking
// care of the Application.Run in its own thread, we just need
// to make sure the application keeps on running by blocking the
// current thread.
MainThreadEvent.WaitOne();
// We need to inform the WinFormsAdaptor that it is oke to quit.
_WFServicePort.Post(new Shutdown());
}
}
}
Now that we have a running form, let's build a sample that queries a webservice several times with different parameters and show the result in a listbox, off course async. Add a listbox and a button to the MainForm and write the following code.
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
//The port that receives the responses of the webservices.
private Port _ResponsePort;
//The port that receives any exceptions of the requests to the webservices.
private Port _FailurePort;
// A simple method to call a webservice async and fill our ServiceResponse instance with
// the city.
private void CallTemperatureServiceAsync(localhost.TemperatureService service, string city) {
ServiceResponse response = new ServiceResponse();
response.city = city;
service.GetTemperatureAsync(city, response);
}
private void button1_Click(object sender, EventArgs e) {
localhost.TemperatureService temperatureService = new localhost.TemperatureService();
//Create the ports
_ResponsePort = new Port();
_FailurePort = new Port();
// Define the GetTemperatureCompleted event. We use this delegate to post to the correct port.
temperatureService.GetTemperatureCompleted += new CCRBlogExample.localhost.GetTemperatureCompletedEventHandler(temperatureService_GetTemperatureCompleted);
// Make the calls to the webservice.
CallTemperatureServiceAsync(temperatureService,"Brussels");
CallTemperatureServiceAsync(temperatureService,"Antwerp");
CallTemperatureServiceAsync(temperatureService,"Ghent");
// And here it happens, this is the cool stuff here.
// We use an Interleave Arbiter to coordinate the results of
// the webservicerequest. We define here that we should stop all processing
// when there is one exception on the requests, so even if you call the webservice
// 100 times, any excpetion will stop the processing.
// Furthermore we define here we can handle all request concurrently, if we would access
// non-threadsafe resources we could put them in the ExclusiveReceiverGroup and the CCR
// will make sure there is only one thread handling them.
Arbiter.Activate(Program.DQueue, Arbiter.Interleave(
new TeardownReceiverGroup(
Arbiter.Receive(false, _FailurePort,
delegate(Exception ex) { })),
new ExclusiveReceiverGroup(),
new ConcurrentReceiverGroup(
Arbiter.Receive(true, _ResponsePort,
delegate(ServiceResponse response) {
Program.WFServicePort.FormInvoke(delegate {
ResultListBox.Items.Add(response.city + ":" + response.Temperature.ToString());
});
}))));
}
//Here we handle all posting to the correct ports depending on the output of the async request of the
//webservice.
void temperatureService_GetTemperatureCompleted(object sender, CCRBlogExample.localhost.GetTemperatureCompletedEventArgs e) {
if (e.Cancelled) {
//Post exception;
_FailurePort.Post(new Exception("cancelled"));
return;
}
if (e.Error != null) {
//Post exception;
_FailurePort.Post(e.Error);
return;
}
//Post ServiceResponse
ServiceResponse response = e.UserState as ServiceResponse;
response.Temperature = e.Result;
_ResponsePort.Post(response);
}
}
// A simple class to transport data and to use
// in the Ports.
public class ServiceResponse {
public int Temperature;
public string city;
}
What I like most is the possibility to use local variables in other threads. Like you see in the RunForms delegate. You don't need to declare them somewhere global, they are defined local and your code stays really clean and readable.
This is cool stuff, easy to use and easy to follow. Think of all projects you did with threading and look at this. The next sample will be a sample on how to program async in a sequential way. A feature of the CCR, that will change the way we program async.
if you see the message "Garbled data received from LEGO NXT. Bluetooth header (31) does not match
expected packet length (0) for command: GetDeviceInfo: 155." in your VS2005 output window or in the logging in the dsshost webpage do not panic, this is only a warning. If you want to remove this just add the following code to the switch statement in the ReturnPacketDataSize method of the LegoHelper class
case 0x9B:
return 31;
When working with the tutorials of Microsoft Robotics Studio I found some really unfamiliar code like "Arbiter.Activate(Arbiter.Receive<bumper.Update>(true, bumperNotificationPort, BumperHandler))". If I find code like this I want to know what it is, the kid in me will never die I suppose... So this piece of code is using the Concurrency and Coordination Runtime (in short CCR), a very nice and easy library to use threading in your applications, it is really amazing how easy it is to create workerthreads and a responsive application. There is a great article on MSDN magazine in the column Concurrent Affairs of Jeffrey Richter on the CCR, but in short it goes like this. There are 4 main classes in the CCR.
- Dispatcher : A thread pool ready to use, you can create more than one.
- DispatcherQueue : A Queue that contains delegates for a Dispatcher.
- Port : A workitem data, by posting data to the Port the DispatcherQueue gets filled with delegates
- Arbiter : A binding between a Port and a DispatcherQueue, in effect it combines a delegate with data posted on a Port and posts it in a DispatcherQueue.
There are more possibilities in the CCR but read the article and view the video on channel9 with Jeffrey Richter and George Chrysanthakopoulos. Definitly some really cool stuff you should check out, and not only for Robotics Studio.
Okay, after one week of connecting bluetooth to the NXT, which included one new Bluetooth dongle, about 200 cigarets and a lot of my hair, it finally happend, I have connected Robotics Studio and the NXT. Time to get programming and do some nice things with this NXT. In order to make everyone's live easier who want to try this out, there is one solution to make this work within 5 minutes. Rebuild the LegoNxt Service and change the baudrate to 115200 in the legoNxt.cs file like this "if (_legoBlock.Open(_state.Comport, 115200))". After rebuilding this it works all fine and you should see something like this in your command line screen.

The main program should start on your NXT and if all goes well the hourglass should disappear. At that time your NXT is connected and ready to serve you, how humble.
Another tip set the sleep option in the settings on the NXT to "never", it will avoid several minutes of search why your NXT is not connectable if you know what I mean.
Finally some time to blog. Let's see what I did the last few days, on saturday I did some calls to get my LEGO mindstorms NXT. It took me about 16 phonecalls to find a local store that had it in stock, yes in stock because I don't like waiting for things that I want to have now. After a road trip of 63 km I finally got home with it and started playing. When I was done building I had to install the software and most off all I had to pair it with the Microsoft Robotics Studio. Installing the software was not really difficult but getting the NXT to connect through bluetooth was hell, I had to install the driver several times and today I finally managed to get a connection. Now it is time to get it connected with Robotics Studio, when I manage to get it working I will surely blog about that one, it is already exciting to get connected to my personal robot.
On the other hand I was in Portugal, Lisbon for a business meeting on a really nice project which will get me really started with the DotNet framework 3.0, so expect some nice examples in the next months (if I have time and otherwise later, because it is a really hard shedule). It was rather rainy but they have great restaurants and even better food, I should plan more meetings overthere.
And the best news of the last month arrived today with email, I finally got registered for TechEd : Developers. Yep, yep, I will attend the event from 7-10 november in Barcelona.
Ever wanted to build a robot that finishes your project on time for you while you are drinking a good glass of red wine in the sun ? Well than you should install immediately the Robotics Studio October 2006 CTP. I'm not really an expert on robotics but I did some embedded development in my early programming years, if it would have been like it is now in Robotics Studio than I would probably never have become a DotNet developer, but would be surrounded by robots doing my work.
It includes a VPL (visual programming language) that has no learning curve at all, imagine what you would have to do to let the PC say some text. It took me 3 minutes including learning the basics of VPL. Here it is.

This tool is the best example I have seen of SOA since long, everything here is a service, sensors, lights, cameras, batteries, engines and so on. All interacting through soap messages, at a speed of 90.000 soap messages in a second, pretty performant I think. You can link it with external robots or you can simulate it, this simulation is rendered in managed DirectX, and excuse me, it looks amazing, for more information on simulation read the Microsoft Robotics Studio Simulation Overview.
Want to play ?
Sandcastle is the new help file generator for developers, like NDoc it generates library documentation from your source and managed assemblies.
It has three major components
- MRefBuilder: produces XML-formatted reflection information files
- BuildAssembler: binds your xml comments and the generated MRefBuilder files into HTML files
- XslTransform: Generates and manipulates auxiliary data files.
Of what I could read in a small amount of time, this tool is highly customizable, not only by configuration files but also by coding. You can download the September CTP here .
Resources:
I think we Belgian developers are probably the most spoiled developers of them all, after an MSDN event on Framework 3.0 and a MSDN evening on Internet Explorer again two evenings on planned. Be fast because seats are