Laurent Ellerbach

Ce blog est principalement destiné à publier des informations relatives à Microsoft, à ses technologies, aux outils Visual Studio et à ses versions Express notamment Visual Basic

October, 2011

  • Laurent Ellerbach

    Reading file in .NET Microframework

    • 0 Comments

    For the one reading my articles, you know I’m developing in .NET Microframework an application to be able to switch on and off led in my Lego City. In the past post, I’ve explain how to setup a web server with HTTP, generate dynamic pages, handle parameters. And in the last one I show how to overlay 2 images and make the one on top clickable. In this article, I’ll explain how to read a file from the file system. I need this to be able to store images on an SD card for example and push them thru HTTP on the client. But I also want to have a setup file with the position of the led to display on the map.

    .NET Microframework offer basic IO with basic file system. It has to be a FAT format sitting on SD or equivalent. For the netduino, you have the netduino plus version which offers a SD card reader. And the basic IO are already implemented. So you can easily read and write a file. I have to admit I get couple of problems with SD card and have hard time to find one which was working all the time. Also, it looks like there is an hardware/firmware problem with SD card. But it’s about to be fixed. I never get too many problems to read the SD card but mainly to write on it. Here, my need is about reading and not writing.

    In the HTTP Server example, there is a good example of how to read a file and send it over HTTP. Here is the function (a bit modified from the original sample for my own purpose):

    static void SendFile(HttpListenerResponse response, string strFilePath)
     {
         FileStream fileToServe = null;
         try
         {
             fileToServe = new FileStream(strFilePath, FileMode.Open, FileAccess.Read);
             long fileLength = fileToServe.Length;
             // Once we know the file length, set the content length.
             //response.ContentLength64 = fileLength;
             // Send HTTP headers. Content lenght is ser
             Debug.Print("File length " + fileLength);
             // Now loops sending all the data.
    
             byte[] buf = new byte[BUFFER_SIZE];
             for (long bytesSent = 0; bytesSent < fileLength; )
             {
                 // Determines amount of data left.
                 long bytesToRead = fileLength - bytesSent;
                 bytesToRead = bytesToRead < BUFFER_SIZE ? bytesToRead : BUFFER_SIZE;
                 // Reads the data.
                 fileToServe.Read(buf, 0, (int)bytesToRead);
                 // Writes data to browser
                 response.OutputStream.Write(buf, 0, (int)bytesToRead);
    
                 System.Threading.Thread.Sleep(50);
                 // Updates bytes read.
                 bytesSent += bytesToRead;
             }
             fileToServe.Close();
         }
         catch (Exception e)
         {
             if (fileToServe != null)
             {
                 fileToServe.Close();
             }
             throw e;
         }
     }

    The function takes the HTTP response object and the file name of the file to send over HTTP.

    Then the code is quite simple. It first create a FileStream. And as it is well developed, you have a nice try catch Sourire. When you try to access files or resources, always use a try catch. You never know what can happen. You may have the user removing the support on where the file are like the SD card, the file may be corrupted, already access by another thread, etc.

    The file is open on readonly so if there is any other thread which want to access it also in read only, it is possible:

    fileToServe = new FileStream(strFilePath, FileMode.Open, FileAccess.Read);
    long fileLength = fileToServe.Length;

    The size of the file is stored into a variable. It will be necessary because the size of the memory in a netduino is very limited and you can’t open the file totally, put it in memory and send it as you’ll probably do a regular OS like Windows or Linux. Here, there is no operating system, no page file, and very very limited resources to only couple of kilo bytes. Yes, kilo bytes, not mega and far away giga!

    byte[] buf = new byte[BUFFER_SIZE];
    for (long bytesSent = 0; bytesSent < fileLength; )
    {
        // Determines amount of data left.
        long bytesToRead = fileLength - bytesSent;
        bytesToRead = bytesToRead < BUFFER_SIZE ? bytesToRead : BUFFER_SIZE;
        // Reads the data.
        fileToServe.Read(buf, 0, (int)bytesToRead);
        // Writes data to browser
        response.OutputStream.Write(buf, 0, (int)bytesToRead);
    
        System.Threading.Thread.Sleep(50);
        // Updates bytes read.
        bytesSent += bytesToRead;

    Reading the file will be done by slice. We are creating a buffer of the BUFFER_SIZE size. Here in netduino the maximum size is 1024. So the file will be read by slide of 1K and send over the response object. the loop is simple, it just read the file up to the end by slice of 1024 bytes.

    and to allow the system to do something else, it is paused couple of miliseconds. So be aware sending large file over HTTP in a netduino and any other .NET Microframework environment will require lot of loop like this and will take time.

    The rest of the code is just about closing the file. if you are sure your file will be less than 1K, you don’t need the loop, you’ll just need to create a buffer of the right size and read all.

    So we’ve seen the basic of reading a file in .NET Microframework. In a next post we will see how to use this to read a setup file.

  • Laurent Ellerbach

    Display overlay images in HTML and javascript with .NET Microframework

    • 1 Comments

    In my current project of lighting my Lego city, I’m working on a simple web interface that will allow thru a HTTP web page to display an image and small lamp icons on overlay. In my previous project on automate my sprinklers, I’ve implemented a HTTP web server in my netduino. It’s working like any Apache or IIS with kind of dynamic pages like ASP, php or Java. of course the implementation is much smaller and do cover only the very basic functions like GET request and sending file over.

    So as for the sprinkler project, I started with the HTTP Server example provided in the .NET Microframework SDK. I’ve removed what I did not need (same as for the Sprinkler project) and added couple of features like conversion, GET parameter management. Now I have the base, I was looking at a way to display images on overlap. my HTML bases are quite old, last time I did a page by hand was for the sprinkler project but not really with images. So of course, I remember the <img> tag and the map attribute to create an image that can bi clicked in multiple areas but that was not really what I wanted. I wanted multiple real images to be displayed on top of each other and having the ability to click on them.

    I rapidly found the <span> tag which allow to display anything on anyplace on top of HTML code. So it was looking perfect for my usage. The way to use it is to create an area and place HTML code inside with a position on the page. As an example:

    <span style='position:
    absolute;margin-left:158px; margin-top:59px; width:55px;
    height:44px; top:20px; left:50px;'><a href="/"><img border=0 width=55 height=44
    src="lampoff.png"></a></span>
    

    This span will be positioned in an absolute position on the page, starting from 158 pixels from the left side of the page and 59 from the top. Then you have to add another 20 pixels from the top and 50 from the left. The size of this span will be 55 pixels width and 44 pixels height. And it will contain an <a> tag with an image. The size of the image is 55 pixels width and 44 pixels height. the question you may ask is why is the span control taking 2 parameters for each position? one called margin-left + left and for vertical positioning margin-top + top. So good question Sourire the idea there is to allow to position first the span based on a control on the page and then offer the possibility to add an offset. the top/left is the first positioning and the margin-top/margin-left the second one. You want a real example? OK, so lets go with my final page which looks like this:

    image

    As you can see, I’ve positioned some lamps on the main image. And on top of the image there is some text. Imagine than in my code, I want to add more text before, of change the font size. It will change the position of the main picture. So the position of the lamp icons will change too. If I hard code the position of those lamp icons with absolute numbers, I’ll have to change all of them if I do a modification on the page.

    Now, If I can get dynamically the position of the main image and then use the possibility to use the margin to adjust the position on the main image, the only thing I have to care of is really the position on the picture. Well, the bad news there is that in HTML there is no other way than doing javascript to get a position of an object. So I had to code in javascript, 2 functions. 1 which will give me the absolute top position of the image and one for the left position. I have to admit I did not write javascript for such a long time… And I also have to admit, it’s not a language I like very much. No strong typing, no real way to debug correctly, no real language structure and less productivity than with languages like C#, VB, Java, C/C++. But I did it, and here is the result:

    <script langague="Javascript">
            // function to return the absolute Top and Left position
            function findTop(iobj) { ttop = 0; while (iobj) 
    { ttop += iobj.offsetTop; iobj = iobj.offsetParent; }
    return ttop; } function findLeft(iobj) { tleft = 0; while (iobj)
    { tleft += iobj.offsetLeft; iobj = iobj.offsetParent; }
    return tleft; } //to use it if the id of your image is MyImage //findTop(document.all.MyImage); </script>

    The function findTop will take the object you want the top position in argument. In HTML you can have imbricated objects so you have to take care of this to get the real position of an object. So I did a very simple recursive loop to sum the top position of all the parents objects up to the point there won’t be any object. And I simply return the sum of those positions. I did the exact same function for the left position. Now question is: how to use it? well, that’s very simple Sourire Taking the previous example, it will be:

    <span style='position:
    absolute;margin-left:158px; margin-top:59px; width:55px;
    height:44px; top:findTop(document.all.MyImage); 
    left:findLeft(document.all.MyImage);'><a href="/">
    <
    img border=0 width=55 height=44 src="lampoff.png"></a></span>

    So rather than have a number after the left and top attributes, I just call the functions. It assume that the name of the picture is MyImage. To give a name to an object, just use the id attribute:

    <img alt="Map of the city" id=MyImage src="ville.jpg" />
    

    and that’s it! the overall code for the page I generate automatically looks like:

    <HTML><BODY>netduino Lego City
    <p>HTTP Method: GET<br>
    Requested URL: "/default.aspx?id=0;lg=True<br>
    HTTP Version: 1.1"<p>
    <
    script langague="Javascript"> // You don't need to worry about this function findTop(iobj) { ttop = 0; while (iobj)
    { ttop += iobj.offsetTop; iobj = iobj.offsetParent; }
    return ttop; } function findLeft(iobj) { tleft = 0; while (iobj)
    { tleft += iobj.offsetLeft; iobj = iobj.offsetParent; }
    return tleft; } </script> <p> Click the lamp to switch on or off </p><span style='position:absolute;margin-left:158;
    margin-top:59;width:26px;height:45px; top:findTop(document.all.MyImage);
    left:findLeft(document.all.MyImage);'>
    <
    a href='/default.aspx?id=0;lg=False'>
    <
    img border=0 width=26 height=45 src="/WINFS/lampon.png"></a></span>
    <
    span style='position:absolute;margin-left:208;
    margin-top:300;width:26px;height:45px; top:findTop(document.all.MyImage);
    left:findLeft(document.all.MyImage);'>
    <
    a href='/default.aspx?id=1;lg=True'>
    <
    img border=0 width=26 height=45 src="/WINFS/lampoff.png"></a></span>
    <
    span style='position:absolute;margin-left:10;
    margin-top:10;width:26px;height:45px; top:findTop(document.all.MyImage);
    left:findLeft(document.all.MyImage);'>
    <
    a href='/default.aspx?id=2;lg=True'>
    <
    img border=0 width=26 height=45 src="/WINFS/lampoff.png"></a></span>
    <
    span style='position:absolute;margin-left:700;
    margin-top:550;width:26px;height:45px; top:findTop(document.all.MyImage);
    left:findLeft(document.all.MyImage);'>
    <
    a href='/default.aspx?id=3;lg=True'>
    <
    img border=0 width=26 height=45 src="/WINFS/lampoff.png"></a></span>
    <
    img alt="" src="/WINFS/ville.jpg" /></p></BODY></HTML>

    The /WINFS/ path is due to the fact I was running this sample thru the emulator. If you run it on the netduino board, then the SD path is /SD/.

    So I have created all what I need to display an image, put some other pictures as overlap, have the possibility to click on them. Now the next step is about generating dynamically this page from the netduino which I did and I will post explanations in a next post. Of course, there is the possibility to do all this with CSS. It’s working exactly the same way. My need is very simple so I won’t use CSS there but maybe to make my page very sexy in the future. Enjoy this code and post written in a plane Rire

  • Laurent Ellerbach

    Lighting my Lego city using .NET Microframework

    • 1 Comments

    Now I have created a software to pilot sprinklers, I want to be able to pilot my Lego city and light it. I know my sprinkler project is not over as I still need to work on the hardware. I will do it over the winter and try to find someone to help me. This new project looks simpler for me as it will basically only be couple of led. So it can be directly plugged to the netduino board.

    I have quite a big Lego city as you can see in this picture with 2 trains, a modern city, an old city, an airport, couple of rail stations.

    For those who may not have guess, I’m a Lego fan, I have more than 650 official Lego sets from 1970+ to now. Not all are build, some are just used for spare parts to build other kind of constructions. And I have also hundreds of kilos of brick at home which allow me to build whatever I want. You can have a look at part of the collection here.

    Same as for the sprinkler project, the idea is to be able to switch some part on automatically, at night for example, and switch them on and off also manually. In order to reuse the work I’ve done, I will create a similar project with and http web server (like IIS or Apache running on Windows or Linux), dynamic pages (like ASP.NET, php or Java) with parameters. I’ve already develop a web server I will be able to reuse and the management for dynamic input.

    My idea this time is to be able to display a web page with pictures of the city and specific points on the pictures that will represent the light to switch on and off. clicking on them will change the color of the points and switch the light accordingly.

    In a longer term, I will try to pilot also the train lights and the rail switch. That will need a bit more electronic but is very easy to do in term of code. So probably that the code will exist before the electronic as for the sprinkler project. I will try also in this project to use the SD card to store the picture of the city and the points coordinate to be displayed. So a kind of setup file. I’ve already try to play with the SD card but with limited success. I don’t know from where the problem is coming from. I use couple of different cards and I always get errors but never the same. So I think the problem is coming from the hardware.

    So let see where this project will go Sourire

  • Laurent Ellerbach

    Creating and launching timer in .NET Microframework

    • 1 Comments

    In previous posts, I had the occasion to show how to implement a web server using HTTP and handling web request (in my example GET requests) with parameters URL like in a real Windows or Linux server running Internet Information Server (IIS) or Apache with a generated HTML page like for ASP.NET, PHP or Java. Of course in couple of Kilo bits of memory, you just can’t do the same as IIS or Apache. Of course, security is very limited, capacity to cache non existent and many functions does just not exist! But at least you can do what you want and you just can focus on creating web page by hands with real C# code using the standard HTML language Sourire for those of my age who have started to write web pages in 1993 or so remember that it’s not very complicated and notepad was your best friend. Youngest one using tools like Visual Studio, Eclipse or others just don’t know Clignement d'œil Ok, I’m probably a bit polemic there but they may be less comfortable doing it than people of my age or people who developed couple of ISAPI filters.

    So read first this post on the web server implementation, then how to setup the time and date, this one on how to generate a calendar then this one on how to create programs. All done? Good! now, we will create couple of timers to launch the sprinklers. the good news is that in .NET Microframework, there is all what you need to do that. the only thing you have to do is to add a line like that in your initialization phase. I’ve added it in the StartHttpServer function:

    Timer MyTimer = new Timer(new TimerCallback(ClockTimer_Tick), null, 30000, 30000);

    So we have created a Time object that will call a function ClockTimer_Tick every 30 seconds in 30 seconds. The ClockTimer_Tick function looks like:

    static void ClockTimer_Tick(object sender)
    {
        DateTime now = DateTime.Now;
        Debug.Print(now.ToString("MM/dd/yyyy hh:mm:ss"));
        //do we have a Sprinkler to open?
        for (int i = 0; i < SprinklerPrograms.Count; i++)
        { 
            SprinklerProgram MySpr = (SprinklerProgram)SprinklerPrograms[i];
            if ((now.Year == MySpr.DateTimeStart.Year) && (now.Month == MySpr.DateTimeStart.Month) && (now.Day == MySpr.DateTimeStart.Day)
                && (now.Hour == MySpr.DateTimeStart.Hour) && (now.Minute >= MySpr.DateTimeStart.Minute))
            { // this is the time to open a sprinkler
                Debug.Print("Sprinkling " + i + " date time " + now.ToString("MM/dd/yyyy hh:mm:ss"));
                Springlers[MySpr.SprinklerNumber].Manual = false;
                Springlers[MySpr.SprinklerNumber].Open = true;
                // it will close all sprinkler in the desired time of sprinkling. Timer will be called only once.
                Timer MyTime = new Timer(new TimerCallback(ClockStopSprinkler), null, (int)MySpr.Duration.Ticks/10000, 0);
                SprinklerPrograms.RemoveAt(i);
            }
        }
    }            
    

    It starts by creating a DateTime object that take the actual date time. It will be used to see if there are programs to launch. The loop just go thru all the programs. Programs are contained into an ArrayList SprinklerPrograms and contains objects that are SprinklerProgram. All this is describe in this post.

    So what it does is just testing if the program is the right year, right month, right day, right hour and if the minute to start is pasted. As the function is called every 30 seconds, a sprinkler will be started during the minute it was planned. To open the sprinkler, the Sprinkler function Open from the Sprinkler class is called. The code for the class looks like:

    static private OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
    public class Sprinkler
    {
        private bool MySpringlerisOpen = false;
        private int MySprinklerNumber;
        private bool MyManual = false;
    
        public Sprinkler(int SprNum)
        {
            MySprinklerNumber = SprNum;
            //need hardware here
        }
    
        // open or close a sprinkler
        public bool Open
        {
            get { return MySpringlerisOpen; }
            set
            {
                MySpringlerisOpen = value;
                //do harware here
                if (MySpringlerisOpen)
                    led.Write(true);
                else
                    led.Write(false);
            }
        }
        public bool Manual
        {   get { return MyManual; }
            set { MyManual = value; }
        }
            
    
        //read only property
        public int SprinklerNumber
        {
            get { return MySprinklerNumber; }
        }
    }

    This class does not include the real hardware work. It just light on the embedded led when a sprinkler is open and switch it of when closed. As there are multiple sprinklers sharing the same internal led, the led object as to be declare as a static object in the main class to be kept alive and shared by all the sprinklers.

    Here come the specific of the netduino. The internal led is an OutputPort and use a specific port. It can be found in the definition of the enum:

    public const Cpu.Pin ONBOARD_LED = 55;

    The sprinkler class contains the number of the sprinkler, if it is open and if it is a manual open or an automatic opening. The only way to create a sprinkler class is to give it a number. It is done as behind there will be some hardware initialization and all objects will need to be unique. When I’ll have done the hardware work, I’ll come back to post the necessary code Clignement d'œil

    So back to the launch of the program, the code will set the opening to manual and open it in the sprinkler:

    Springlers[MySpr.SprinklerNumber].Manual = false;
    Springlers[MySpr.SprinklerNumber].Open = true;
    // it will close all sprinkler in the desired time of sprinkling. Timer will be called only once.
    Timer MyTime = new Timer(new TimerCallback(ClockStopSprinkler), null, (int)MySpr.Duration.Ticks/10000, 0);
    SprinklerPrograms.RemoveAt(i);

    Then it will create a new timer that will be called after the duration specified to sprinkle. The Ticks member return a number of ticks. 10000 ticks represent 1 second. So the ClockStopSprinkler will be called after the right duration and only 1 time. The function is quite simple, it just reset all sprinklers to close. I’ve decided to do this as I feel it is much more secure. I just can’t run anyway 2 sprinklers at the same time as I don’t have enough water pressure to run more than once a time.

    static void ClockStopSprinkler(object sender)
    {
        Debug.Print("Stop sprinkling " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"));
        //close all sprinklers if automatic mode
        for (int i = 0; i < NUMBER_SPRINKLERS; i++)
        {
            if (Springlers[i].Manual == false)
                Springlers[i].Open = false; 
        }
    }

    If the mode is manual, no reason to stop a sprinkler. The manual mode can be run in another page. I’ll describe this into a future post.

    So quite easy code here to open and close the sprinklers when needed. Just use simple timers! I hope you’ve also enjoyed this post. Coding makes you feel better Sourire and that’s just a marketing guy telling you this Clignement d'œil

Page 1 of 1 (4 items)