CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Peter's Gekko

public Blog MyNotepad : Imho { }

March 2006 - Posts

  • Download a file with a browser, the server side part

    I have an asp.net application where the user can download a file by clicking a link. It could be a file of any type. Getting it work took more effort than expected. Let me use my blog as a public notepad and share the result.

    protected void LinkButtonDownLoad_Click(object sender, EventArgs e)

    {

        string bestandsnaam = (sender as LinkButton).CommandArgument;

        string fullFileName = Server.MapPath("DownLoads") + "\\" + bestandsnaam;

        if (System.IO.File.Exists(fullFileName))

        {

            bestandsnaam =  Server.UrlPathEncode(bestandsnaam);

            Response.Clear();

            Response.ContentType = "application/binary";

            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", bestandsnaam));

            Response.TransmitFile(fullFileName);

            Response.Flush();

            Response.End();

        }

    }

    The name of the file (bestandsnaam in Dutch:) is read from the linkbutton's CommandArgument as that's a bindable property. UrlPathEncode is necessary for filenames containing blanks. The ContentType is set to application/binary to make sure any format will get across safely.

    Thanks to me neighbor who used to blog and is still an invaluable resource. The code is no big deal but we had to assemble it ourselves being unable to find a full working example.

  • Radrace

    Jeff kept the RAD candle burning. May I add some kerosene ? The radrace (most links on the site point nowhere) is a competition where teams of two developers compete against each other to build a working application within two days. The limitations are that you have to cart in the equipment to do that by yourself (fork lift truck for an AS/400 allowed ?), the data model should be finished for 90% (no metrics defined), the main part of the data should come with the app (?) and the application will be made available for real life use. I'll leave it to Jeffrey to strike the match. To me it's sufficient to say that this does not look like my vision of RAD. The funny thing is that the event seems to be mainly a Java thing. I thought "those" guys were so serious.

  • Copy source as HTML for VS2005 !

    When writing an HTML document which contains source code, like blogposts, CopySourceAsHtml is a tool of great value. It just takes a couple of clicks to copy source from Visual Studio to your HTML editor. The project did have a somewhat flaky status in VS 2003, in my experience the 1.2 worked well in most of the cases, 1.3 usually gave exceptions when copying. You could not install it in VS2005, posting VS 2005 code took copying it to VS 2003 first.

    Today I found a VS 2005 port of CopySourcesAsHTML.  Here is a link to an installer with notes on installing. And it works like a charm ! Absolutely recommended.

  • Multiple eventsinks on a (Delphi) automation object. How to turn a single cast delegate into a multicast delegate

    When you have a COM automation server your code can invoke methods and properties on the automation object. With a connectable COM object code invocations can go both ways. The consumer invokes methods and the server fires events. To subscribe to these events the client passes an event sink to the server. An event sink is an object which implements an interface with a (type library defined) set of event handling methods. This event sinking mechanism is defined very flexible, a full implementation of the COM IconnectionPointContainer  interface works with a collection of multiple types of eventsinks and each sink-type collection can manage any number of sinks.

    In the real world the implementation of eventsinks is less elaborate. Notorious is the support in Delphi. A Delphi automation object accepts just one sink of one type. Borland can put the blame on that on Microsoft as the VCL (Delphi class library) code of their implementation is a straight C++ to Object Pascal port of the code found in the MS press book "OLE controls inside out". (Read here for a deeper story) Anyway, the fact that the Delphi automation object supports only one sink will give you a hard time in .NET.

    These demo snippets are based on the sample for my COM in Delphi series. It is an in-process form to browse the file system. The automation object fires an event when the user selects another directory. At first sight working with the object in .NET is no big deal.

    private FileManager.FileZapper fm;

    private void Form1_Load(object sender, EventArgs e)

    {

        fm = new FileManager.FileZapperClass();

        fm.OnDirectoryChanged += new FileManager.IFileZapperEvents_OnDirectoryChangedEventHandler(DisplayOnLabel);

        fm.OnDirectoryChanged += new FileManager.IFileZapperEvents_OnDirectoryChangedEventHandler(AddToListBox);

    }

     

    void DisplayOnLabel(string dirName)

    {

        label1.Text = dirName;

    }

     

    void AddToListBox(string dirName)

    {

        listBox1.Items.Add(dirName);

    }

    In this snippet a new automation object fm is instantiated and two handlers subscribe to the OnDirectoryChanged  event. One to display the current directory on a label, the other to add the history of the directories visited in a listbox. This code will build and run but the moment an event is fired in the automation object an exception is thrown. Each of the methods subscribing to the event takes a separate event sink and the Delphi automation object supports only one. In case only one eventhandler is subscribing the code will run without any problems.

    There are two way to work around this. One is to extend the the Delphi framework class. Read here for a full story how to get that done. The other way is to find a workaround in the consuming client which I will describe here.

    An event which can sink events to multiple eventhandlers subscribing is a multi cast delegate, an event which can sink only events to one subscriber is a single cast delegate. Delphi events are all single cast, .NET events are all multicast. To turn the single cast delegate in the automation class into a multi cast I will build a new class which inherits from the COM class and redefines the event.

    class MyComServer : FileManager.FileZapperClass

    {

         // Hide the event in the base class as it will fail on multiple event handlers

        public new event IFileZapperEvents_OnDirectoryChangedEventHandler OnDirectoryChanged;

        public new event IFileZapperEvents_OnSelectionChangedEventHandler OnSelectionChanged;

     

        private void MyComServer_OnDirectoryChanged(string DirName)

        {

            // fire eventhandler subscribed to this new implemenatation of the event

            this.OnDirectoryChanged(DirName);

        }

     

        private void MyComServer_OnSelectionChanged()

        {

            // fire eventhandler subscribed to this new implemenatation of the event

            this.OnSelectionChanged();

        }

     

        public MyComServer()

            : base()

        {

            // This is the one and only eventsink connected the COM server

            base.OnDirectoryChanged += new IFileZapperEvents_OnDirectoryChangedEventHandler(MyComServer_OnDirectoryChanged);

            base.OnSelectionChanged += new IFileZapperEvents_OnSelectionChangedEventHandler(MyComServer_OnSelectionChanged);

        }

     

    }

    The class inherits straight form the COM class. Both the OnDirectoryChanged and the OnSelectionChanged event are reintroduced with the new keyword. (You could override the events but this will force you to re-implement all other members as well, something which will not pop up until you try to run the code). These new events are normal .NET multicast delegates (read here for a deeper discussion on the difference between the event and delegate keyword). The class has two private methods to fire the event to all subscribers. These will be fired by the automation object itself. After executing the constructor of the base (COM) class the constructor of the inherited class passes the private members as eventsinks to the event in the COM baseclass.

    Now all events are routed through this one event and the automation object only has one sink to take care of. The downside is that the automation object also has to sink events when nobody is actually subscribed to the events. In case that's an unaffordable overhead you have to do some optimization. But I hope you get the idea.

    The code in the winform now changes to

    private MyComServer fm;

    private void Form1_Load(object sender, EventArgs e)

    {

        fm = new MyComServer();

        fm.OnDirectoryChanged+= new FileManager.IFileZapperEvents_OnDirectoryChangedEventHandler(DisplayOnLabel);

        fm.OnDirectoryChanged += new FileManager.IFileZapperEvents_OnDirectoryChangedEventHandler(AddToListBox);

        fm.OnSelectionChanged += new FileManager.IFileZapperEvents_OnSelectionChangedEventHandler(MoveSlider);

    }

    And here's the almost old-fashioned looking Delphi6 form operating in the process of a .NET 2.0 winform and firing events on multiple handlers.

    To quote Delphi eventsink master Binh Ly: (check his very handy COM registration tool):  have fun !

  • A . in the first part of an email address

    An email address does contain at least one dot; Take Pete@Gekko-Software.nl Some organizations, like mine, also use dots in the first parts; like Pete.van.Ooijen@Gekko-Software.nl Imho this makes sense, the dots separate the parts of my full name. But a lot of sites, including FI parts of MSDN, do not accept such an address; it's considered ill-formatted. Not very user-friendly, especially when the messages returned are pretty vague.

  • Timeout on a (sql) database: SqlConnection.ConnectionTimeOut and SqlCommand.CommandTimeOut.

    When your app runs into a timeout on a database operation the error message may lead you in a wrong direction to fix things. Which happened to me so this is my little index to the docs.

    A sqlConnection has a ConnectionTimeout property. It  is a property which determines the maximum number of seconds your code will wait for a connection to the database to open. It is set in the connectionstring to the database

    data source=BROCHIS;initial catalog=Indato;integrated security=SSPI;Connect Timeout=60;

    Opening the connection does not do anything in the database yet. That is handled by a SqlCommand, which could be part of a SqlDataAdapter. The SqlCommand has a CommandTimeOut. This is a settable property which determines the maximum number of seconds the command is given to execute the sql. By default this is 30 seconds. When you perform something costly in the database this is the one whose value you'll have to change.

    SqlCommand cmd;

    .....

    if (bigJob)

       cmd.CommandTimeout = 60;

    For both properties a value of 0 indicates to wait forever. Both properties also apply to non sqlserver database operations. They are defined in IdbConnection and IdbCommand.

    Posted Mar 20 2006, 09:03 AM by pvanooijen with 10 comment(s)
    Filed under:
  • Sunspots, cyborgs and ambient intelligence in Groningen

    In the Dutch city of Groningen is the Mediacentrale:

    It's a former power plant which has been transformed into a centre for multimedia and other IT business. March 16th, it was stage for Amigro, a 1 day conference on ambient intelligence.(Google for variations). Organized by the department of AI of the Groningen university in cooperation with the local platform for the stimulation of ICT. Every year they have something special; last year and the year before that is was a robot competition (including the .NET wonder on wheels).

    So this year it was a conference on "ambient intelligence" which is the effect of having intelligent devices everywhere. A very good speaker on such devices was Rob Tow who works for Sun Research labs

    He had a very good story which went form the ancient Greeks to the emerging ecosystem of intelligent devices and ended with a demonstration such a creature. The Sunspot; soon for sale, is an intelligent matchbox containing sensors, leds, a wireless network, IO-ports and is running a Java virtual machine called Squawk. The sensors include an accelerometer, so the device can sense motion. You can do great things with that. Take this way to transfer data from one sunspot to the other. The magic is done by waving the spot towards the receiving one and pretend it is sprinkling it with some data. By including figures like circles (counter) clock wise a rich instruction set can be built.

    Especially with the combination of the (three color) leds it just looks like magic. Patents pending, no kidding.

    Another speaker took the road inside. Professor Kevin Warwick became world famous for implanting himself with a RFID chip. Opening the door to his lab or logging now only took a hand waive. The application has been followed by quite a lot of others. In Holland we had a bar where waving your injected RFID was a way to pay the bill. Was tested in court and considered in conflict with standing practice. But Kevin has gone further and has  implanted set of electrodes which make direct contact with a nerve in his arm. The electrodes can be plugged into whatever what, including a network adapter. After 6 weeks of training he could control a robot hand by his own hand-movements. Sitting next to it or over the internet on the other side of the world.

    Human to human communication is also possible.

    (picture ripped from beamer projection, sorry about that)

    His wife has a  colored-leds (also) collier with a a receiver and Kevin has plugged in a transmitting bracelet. Now the activity in Kevin's nerves steers the glow in his wife's collier. Cyborgs coming to a conference near you. In (er gaat niets boven) Groningen.

  • Dutch Devdays, what was it like ?

    Last week, March 7th and 8th, we had the annual Dutch Microsoft Developer days.

    A very impressive start was the beamer used for the keynote.

    An immersing stage wide display containing windowed input of several PC's and/or video camera's. Must have been either an expensive rent or it broke down as the second conference day we had just the usual view.

    On a conference like this you get the opportunity to see and hear some international people. We had Scott Guthrie demonstrating Atlas.

    The greatest thing about Atlas is how you use it as an extra layer on top of an asp.net 2.0 application. Just wrap a part of your webform in some atlas tags and you've got partial postbacks. Also quite nice is the way atlas script interacts with existing webcontrols. There are loads and load of resources on Atlas, Scott's blog makes a good starting point. The main thing I've seen is that Atlas is not another new start in web development but a smooth evolutionary step.

    Another great speaker was Bob SQLskills Beauchemin who did an in-depth series on SQL 2005. One of his sessions was in a room approximately 150 chairs wide, just 20 rows deep. In such a setup you have 2 big screens with a presenter in the middle. Nobody knows which direction to look

    A guarantee for a stiff neck at the end of the story. I really don't understand this, it should be no big problem to rotate the whole inventory 90 degrees.

    Always a good show is Rafal Project Botticelli Lucawiecki who did a series on security. He is such a lovely speaker.

    At first ear his talks are a friendly, pleasant and optimistic babble but when the words start sinking in you realize the content is pretty serious, of great depth and keeps you on the tip of your seat.

    A final word on this

    The shot was taken on a presentation on designing a GUI. It was an old show (recognize the Office '97 bullets ?) I had seen before but it's still very true. I know users don't want to think but one aspect of the conference gave the impression developers want to stop thinking as well. Meant as entertainment we had the "singer" Bob Hangop doing Dutch carnival songs all day. You could not stay away from Bob, he was loud and kept popping up again and again. Carnival is something which divides the country. You just had to take side. Most people I've spoken were not at all amused. Please, please, please never again... I do want to think, that's what I visit the Devdays for.

    Having said that my overall impression was that .net is really booming. Not just the evolution of the software but also the enormous increase of job opportunities. Usually the exhibitors mainly try to sell you tools or training courses. This time they mainly were trying to buy something. You ! I'm still a one person shop but with the increasing complexity of software projects and so many interesting opportunities I could change my mind.

  • Salvaging the contents of a (Dell) XP home disk

    Friends of mine fried their Dell family box. The fan outlet had been blocked to long so the poor thing died. They carted in a new one; the new models seem to anticipate on overheating, as they have a very cool air inlet on the front side as well.

    Anyway, I was asked to salvage the contents of the old machine. I took our family Dell and set to work. Some observations which might be of help to others:

    • At first sight the hard disk of an old Dell is connected with a short IDE ribbon cable. This is not a standard cable, after replacing it with a standard cable the drive becomes invisible to the machine.
    • It's no problem to attach the extra disk to the secondary IDE.
    • The My documents folders were all set to a private visibility. This is handled by the NTFS file system and keeps working when the drive is in another machine.
    • To be able to read these folders you have to take ownership of the folder. This is handled in an advanced page of the folders property .
    • XP home does not show this property page by default.
    • When you run your machine in safe mode, (press F8 at boot) the desired property page does show up and you can take possesion of the drive.

    The main lesson I learned is that under the hood XP home is even more like XP pro than I knew. Googling around I found many a suggestion to install all kinds of scary tools or perform bizarre rituals. No need, it's just a (safe) boot away.

More Posts