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

Peter's Gekko

public Blog MyNotepad : Imho { }

May 2005 - Posts

  • ASP.NET Control ID and postback

    Controls on your webforms all have an ID, like TextBox1, LinkButtonAdd, etc. This ID is not the internal Id used by ASP.NET. In case you have a datagrid with multiple rows, each having a Select link button you would have a problem. In case you have a web usercontrol on your page with a Button1 on it and a Button1 on the hosting page that would result in a conflict as well. The internal name is composed of the control id and the control containing the control.

    Internal control names look like

    LinkButton1 A link button on the page itself
    WebUserControl11:LinkButton1 A link button on a usercontrol
    WebUserControl11:DataGrid1:_ctl4:_ctl0   A linkbutton in a datgrid row on an usercontrol

    At runtime you can read this Id from the control's ClientID property. It's value is in the request of a postback. In an earlier post I showed how to read it form the _EVENTTARGET form variable to find out which control had caused the postback. As Andrew noted this form variable is empty in case of a button causing the postback and wondered how he still could find out which button had caused the postback.

    Well, if you inspect the AllKeys property of the Request.Form you will see that item 3 contains the id of the control posting back But this item3 is only in the collection when a button posts back, not when an asp.net specific control like a linkbutton or dropdownlist caused it. So a better version of my previous post would be

    string postbackControlId;

    if (Request.Form.AllKeys.GetUpperBound(0) > 2)
       postbackControlId = Request.Form.AllKeys[3];
    else
       postbackControlId = Request.Form["__EVENTTARGET"];

    // Fiddle the control id out of the string

     

  • Dotned generated code

    Last thursday evening, may 26th, we had a great meeting of the Dutch dotned user group. Sander already wrote a detailed story on this, Frans did one as well. Here come my 2 bits.

    Hosted by Atos origin in their brand new almost futusristic Utrecht office we had a meeting around the theme of code generation. With VS 2005 generating so much code it was interesting to take a deeper look at other code generating tools. Frans Bouma kicked of with a presentation on LLBLgenPro, his code generator for the data-access layer.

    Frans started with a general overview O/R mappers and the different places to hook in. Having covered some theory and the position of tools around (like nHibernate) there was just about enough time to get a first impression of Frans' own tool. The LLBLgen website is full of details.

    The second presentation was on the other side of the spectrum. Jeroen van Helvoort demonstrated RADvolution designer. A very nice tool to create clear and consistent windows forms. It does all that by hooking in the .NET forms designer, so you are not dependent on specific controls. At runtime one assembly has to go with your app. This takes care of things like consistent enableing/disabling of controls and user messages. You can import existing applications. For existing to clean up some mess you just inherited and have to tidy up. Jeroen has made a very nice tool.

    Having seen what you can do with code generation we ended with a good discussion. These days you cannot and should not write all code by hand. Besides using a software package you can outsource the work. In the experience of most people the work done overseas is just as consistent and good quality as the result of a tool. Or just as bad. There is a lock in. When you want to tweak modifying the result of a tool or from outsourcing can be just as difficult. On the long term the tools will be the winner. In ten years time the price of an Indian or Croat developer will be the same as that of of a Western European developer. Or perhaps it will be the other way round, we will be writing code for Indian companies :) So we better make sure we have the right tools and learn to work and live with them. Fort what I've seen that will be not to much of a problem.

    See you next meeting. And to mention one more reason for coming: they are fun. Great fun:

     

  • SELECT * WHERE % ORDER BY why ?

    A sql select query looks something like this :

    SELECT MyCol FROM MyTable WHERE MyCol = 'A' ORDER BY Mycol

    It has a couple of parts
    • SELECT FROM  specifies the output columns
    • WHERE specifies the rows
    • ORDER BY specifies the sort order of the output rows
    What puzzles me is that the order of these three parts is fixed. I cannot interchange parts and state my query like this

    SELECT MyCol FROM MyTable ORDER BY Mycol WHERE MyCol = 'A'

    In my simple view that would be no big deal for the SQL parser. But it (the SQL server one) will throw an error at you. I think this is a pitty; else it would be oh so easy to further specify the WHERE clause like:

    [AirCode]
    string mySQL = "
    SELECT MyCol FROM MyTable ORDER BY Mycol
    WHERE MyCol = 'A'"
    if (TextBoxName.Text != "")
       mySQL+= " AND Name Like @Parameter1"

    Am I overlooking something or is this just sql syntax rigidity ?


  • Heard and not heard: flatpanels, earphones, Ygdrassil and the garden of Jane Delawney

    It's almost weekend, I want to finish this week with some soundbites.

    Recently I complained about my wide screen monitor, which is a marvel to the eye, making irritating noises. At the moment I beleived a design flaw was the cause. But this week the monitor's image started flickering as well and I contacted Philips. Their web-based support is a nightmare but top marks for the phone based version. Within 5 minutes I could explain the problem and give my data. Within 48 hours a man came at the door to change the monitor for a new one. Image is stable again and the squeek has gone. Apparantly it was a signal of some part breaking down.

    In the fight against computer and enviroment noise Scott suggested Shure plugin earphones. Saw a good deal on them and bought me a set. I’m quite disapointed in their acoustic isolation; they do make a difference but by far not what I had hoped for. But their musical quality is absolutely superb; as a whole I’m content with them.

    When it comes to music there’s one more thing I’d like to share with you. Back in the 70–ies CBS released sampler records of their artists, like “Fill your head with rock” On that was a song by a (folk) band named Trees : “The garden of Jane Delawney”. If you were into folk-music (I was and still am) it was quite impressing. Hopelessly romantic and very close harmonies. And after more then 30 years my favorite Ygdrassil have recorded this song, listen to it here. It takes the Shure earphones to unravel Linde’s and Annemarieke’s voice. I love it but please don’t flame me if you don’t.

    Have a good weekend.

  • Using data components on an ASP.NET page

    In my apps I organize all interaction with my databases in components. On my component is a connection to the database and a couple of data-adapters to read and write data.

    These components are housed in a separate assembly. From there I can use them straight to fill the datasets on my web– or win-forms, or write a webservice (or other) remoting layer around them (see this 2005 example). How many adapters a component should have is a point of discussion. In my first 2003 applications they were gigantic. Nowadays I make them a lot smaller. Based on experimenting with datasets 2005–style (and all the SOA stories) I beleive a component should work with just a couple of related tables, like invoices and invoicelines. In this article on 2005 datasets that idea is explored a little further.

    Inside the component the constructor opens the connection to the database.

    public OnderwijsComponent()
    {
       InitializeComponent();
       sqlConnection1.Open();
    }

    The component publishes a couple of public methods which expose the data as XML datasets.

    public StudieOnderdeel StudieOnderdeel(int id)
    {
       StudieOnderdeel ds = new StudieOnderdeel();
       StudieOnderdeelCRUD.SelectCommand.Parameters["@id"].Value = id;
       StudieOnderdeelCRUD.Fill(ds.STUDOND);
       return ds;
    }

    The connection to the database is closed in the componenet’s dispose method.

    protected override void Dispose( bool disposing )
    {
       if( disposing )
       {
          if(components != null)
          {
             sqlConnection1.Close();
             components.Dispose();
          }
       }
       base.Dispose( disposing );
    }

    Using the using statement my webpages can interact with the database and will be sure that the connection to the database is allways closed.

    private void Page_Load(object sender, System.EventArgs e)
    {
       using (StudieOnderdeel onderwijsData = new StudieOnderdeel())
       {
          studieOnderdeel1.Merge(onderWijsData.StudieOnderdeel(id));
       }
    }

    Using will always fire the dispose method of the (Idisposable) object it is using, also when an exception is hit.

    Working this way does have one drawback. Every time I need a componenet it is created, the db-connection is opened, the db is fiddled with and the component is disposed. When I need to do something with the data on several points in the page lifecycle, say in the pagerender (not the pageload) and in a button click, the component is created (and the db-connection is opened) twice on one roundtrip. Ado.net connection pooling is great but there is a more efficient way. To create my components only once on a roundtrip and only when really needed I add the componenets as “lazy” properties of the webform.

    private OnderwijsComponent _onderWijsData;

    private OnderwijsComponent onderWijsData
    {
       get
       {
          if (_onderWijsData == null)
             _onderWijsData = new OnderwijsComponent();
          return _onderWijsData;
       }
    }

    The componenets are now created on demand. But I’ve lost the invocation of their Dispose method. Where to do that ? On a web form the unload event is always fired, also when the page throws an exception. The handler of the unload events checks if the component was created. If so it will invoke its dispose method.

    private void StudieOnderdeel_Unload(object sender, System.EventArgs e)
    {
       if (_onderWijsData != null)
          _onderWijsData.Dispose();
    }

    Following this pattern has the following advnatages

    • A component (and a connection to the database) is only created when really needed
    • A component is never created more than once on a roundtrip
    • The component is always disposed. (And the connection to the database is always closed)

    Works like a charm.

     

  • Meet the robots

    Today was the final of the RoboChallenge where robots compete on the ability to find and catch differnent colored balls. Amongst others the event is sponsored by Microsoft:

    .NET was used amongst the platforms used for the robot software. Amongst others I saw Eclipse and Delphi. Some robots were a PC on wheels. others were controlled by a fixed PC over Wifi. They had to do a couple of rounds. First against the clock. Later one against one. Who gets the balls first ?

    Now quite different robot charteristics come into play. How will it react on the other player ? Herminator was a fast creature, but in the final she locked-up on start. Giving Mars the ability to clean the terrain from balls like a bulldozer. Herminator awakened, made a dash through the field but was to late to make up the difference. Good sport !

    Both these finalists were from the instute for Artificial Intelligence of the Groningen University which had 5 teams. Coming may 24th all of them will give a presentatation on their robots.

    Before you follow the links: they are in Dutch... But the RoboChallenge will go international. Next year is an international open contest. Expect the website to internationalize.

    (Er gaat niets boven Groningen :)

  • Come and see the (.net) robots in Groningen

    Thursday may 12th the finals of the robochallenge will be in held in MartiniPlaza Groningen (the Netherlands). Last year it was great, saw the weirdest thing running .net yet. This year the number of competitors will be even higher. No robot wars, the competition is about finding and grabbing objects smart, fast and efficient.

    The challenge is hosted by the ICT innovation and jobs conference. So besides good fun you can find a good job as well. Admission is free if you register now

  • So what about that Tablet PC ?

    I’m a big fan of the tablet PC and have a category tablet PC on my blog. But havn’t blogged that much on the Tablet recently. I’ve been writing a lot of ASP.NET production code and didn’t have the time to care of my pet. Time for a little catchup.

    On the hardware front things are moving in a steady pace towards main stream adaption. Many brands have tablet models, for instance Toshiba now has a tablet Tecra and even IBM is said to work on one. The main problem was always the extra price but the difference is getting less and less. So your next notebook might as well have tablet capabilities. But you should see a tablet PC as more than just a notebook with added pen capabilities. Bill Gates’s pet, demonstrated at the WinHec keynote, is the Haiku. Which is smaller than a notebook and larger than a PDA. The main diffence between a PDA and a tablet are (at the moment) the screen and the OS. The PDA has a touch screen and the tablet a magnetic digitizer built into the screen. The PDA runs on Pocket PC and the tablet XP tablet PC edition (a superset of XP pro). These intermediate devices are no vaporware, at the moment you can install XP tablet edition on a Sony U750. That machine measures 17 by 11 cm (6.5” x 4.5”), does not meet all specs to be an official tablet, but it worked to full content of the owner.

    So the hardware is making good progress, but what about the software ? Windows XP tablet PC edition is cool and very usefull. MS has realeased a tablet experience pack with some cool add-ons. It includes a number of tools which had the status of Power tool and now are making thier way into the standard feature set of a tablet. My favourites are:

    • A slightly souped up version of the award winning ArtRage app, now dubbed InkArt. This is the app to show when you demonstrate a tablet. Oohs and ahhs from everybody.
    • The energy blue theme realy improves the readability of your screen. The digitizer in a tablet screen significantly reduces that, the theme compensates pretty well.
    • Ink desktop. As you might recall you can scribble on anything which has a windows handle, the Ink desktop lets you scribble right upon the desktop.

    A full review of the pack is on the windows supersite.

    And what’s there for the developers ? The easiets way to add inking to your apps is using the Infinotes suite. Very nice to include inkable notes to your applications, it’s MS journal on the toolbar of VS. But you cannot do things with the pen in combination with existing stuff in your apps. For that you need to explore the Microsoft.Ink namespace. This is a beautifull API, the basics are well described in the only real book on tablet programming. But it’s not the full story. A further step exploring the possibilities should have been the tablet game SDK, presented in the Arcs of Fire game. The beta was launched on the Windows Anywhere conference but since than their website seems to be in state of shellshock. The blog has been dead for months. There is really good stuff in there but you need to be familiar with the API basis to understand what they are trying to do.

    The future for the tablet lies in Longhorn. It’s not yet completely clear whether there will a separate tablet version of Longhorn or not. What is promised is that Ink Data will be a data type which every Longhorn installation can work with. Ink data is more than just the picture scribbeld; it does contain a lot of information how that picture was drawn: which pen strokes were drawn in what order, how do the strokes intersect, what is the local stroke thickness, etc. Under XP you can exchange ink data as ink or as a fortified GIF (and in xml). A fortified GIF is an image of the result and does also have all ink data in the image header. You can install the Microsoft.ink api on a non tablet PC after which you can read and manipulate the ink data on a non-tablet. You can even input ink on a non tablet using the mouse. Trying to do that is the best demonstration why a pen is such a lovely input device. The only thing which you cannot install on a non tablet is handwriting recognition. At the moment the tablet specific software part is quite modular. Fits Longhorn.

    The current Microsoft.Ink is non managed code. Internally it’s a load of COM (and can be used form VB6), for VS there’s a nice managed wrapper. I guess they are working on a native managed version for Longhorn ? Recently there has also been quit some talk on Longorn and a touch screen. At first sight using a pen or just your fingertips is pretty similar. For the hardware there is a big difference. You apply preasure on the screen with anything, for instance the nice goodie pen I got at the MS Windows Anywhere conference. Tablet PC’s use digitizers which respond to changes in the magnetic field caused by a special pen. In some of my previous posts I explored this world and found out that these pens are usually not interchangable. Using a magnetic pen you rest the palm of you hand on the tablet’s screen when writing. No problem. But a touchscreen will detect the palm of your hand and interpret it as a giant click. So there are some problems to bring these two worlds together.

    MS research is also working on pen and fingered input devices. There’s Xnav, a device you operate with just your thumb. In case you’re interested the technology can be licensed. MS says they just don’t have the time to work on this as well. Others research stiching, how to use pen gestures which span multiple displays.

    The tablet hardware is becoming mainstream, tablet software has the potential to change the mainstream. These days a computer is considered incomplete without a mouse. A pen does what a mouse does, far more accurate and has far more possibilities. Trying to look in the crystal ball I wouldn’t be surprised if the pen will take over. For the moment I just can’t wait to find some time to dive deeper into the pen-gestures API.

    Keep scribbling !

  • C++ for .NET at dotned

    Yesterday we had the VS 2005 C++ team at the dotned user group meeting. It was a good meeting and a good talk. Ronald Laeremans is somebody who can, and will, talk for hours. The C++ vision on .net is quite interesting, let me reproduce some of the things I learned.

    To me the C++ language has always been one you had to learn to live with. Never did any real C++ programming but I had to read C++ on a daily basis. All code samples were in C++, incorporating the ideas in my Delphi win32 required translating. These days I do mainly C#, a language whose syntax is far closer to C++ than Object Pascal but whose “architecture” (events, properties, components) comes far closer to Delphi.

    C++ is still a major language at MS, according to the VC team 95% of the MS products is coded in C ++. The team was clearly jealous on the new star C# but gave some good reasons to use (unmanaged) C++:

    • Existing code base. You can’t dump 20 years of Windows and Office development
    • Backward compatibilty.
    • Do your own memory management. Some code has to keep running with 0% memory free. In managed code the smallest things, like boxing an integer, can result in a memory allocation (by the CLR)
    • Directly invoking an unmanaged function is checked at compile time. A dllimport in managed code is checked at runtime.

    The upcoming C++ does a couple of things to bring the world of unmanaged C++ and managed code together

    • To the compiler IL is just another platform target, there’s x86, Itanium and IL
    • When declaring a class in C++ you can prefix the class with the value or ref keyword. The class (type) will than be compiled into a managed class which can be reused by any .net language using the assemby. A class without a prefix is a native class.
    • The clr:safe compiler directive checks your code on the absence of pointers and native classes. When both criteria are met you have a built a managed assembly with C++.
    • A nice feature are trivial properties and events. Declared as a property but you don’t have to write out the (trivial) getter and setter routines.

    Some nice scenarios of mixed code

    • Wrap up DirectX complexities. Directly address DirectX objects iterated in a .net foreach loop.
    • Give an MFC app a .NET Winforms UI. As a demonstration the team had built a customized slide sorter for Powerpoint. Powerpoint in an MFC app and Winforms is very good in building a sophisticated UI.

    C++ is clearly not intended as a mainstream language. You can still do horrific things. And in your app you’re dealing with three kinds of memory: the stack, the managed heap and the native heap. Not for the faint of heart. I will stick to my beloved C# but have seen good things to further expand my horizon. (But will not forget pInvoke.net)

    Another part of a meeting is the social networking part. Of course Sander and Hassan were there and I promissed to restore the broken links to their perfomaces on a former meeting. Is done. See you at the next meeting.

  • Installing SQL reporting services on a machine without SQL server

    SQl reporting services is bound to a SQL-server installation. You can set up reporting services on another machine, fi for development , but the setup has some flaws. It took me some blogreading and guesswork to get it done.

    • The setup needs to do some fiddling in the sql instance (create / alter a db). It needs the credentials of a sa-level user to get that done. In name one of the dialogs gives you the opportunity to enter them. This blog post tells you that that does not work. And describes how to pass the desired credentials in the command line. Which works fine as long as you pass the full path to the msi-file. Like  setup /i D:\ENGLISH\SQL2000\REPORTING_SERVICES\DEV\SETUP\rsrun.msi rssetupaccount=sa rssetuppassword= (bad sql instance,user sa has no password..)
    • A second hurdle is another page in the setup which starts about a webfarm and asks for a servername. Woolly language, it's not clear what they want. What will work is entering the name of the SQLserver followed by the path of the reporting services virtual home directory. Like Brochis\ReportServer. Still don't see what that has to do with a webfarm...

    Now a succesfull setup is just one error away. Something vague, perhaps specific to my network. Clicked it away and reporting services were working.

    Run the report services service pack 2 after this. Else existing apps (which don't use rs) will keep popping up annoying errormessages telling you rs is not properly initialized. My sp2 setup ran without a glitch, can't garantee yours will. With Crystal Reports in mind I keep my fingers crossed..:)

     

    Posted May 02 2005, 03:15 AM by pvanooijen with 2 comment(s)
    Filed under:
  • Learn English (and Dutch, Grunnegs, Frysk..)

    Brendan as wandering if it would make sense to do a multilingual Codebetter site using Babelfish. As a test he created a link to a Babelfish translated Dutch version of the CB home page. Was the result any good ? It was hilarious ! Not only the code went funny, the result of translating a product name can be quite funny to. The overal quality of the text itself varied. Parts of it were excellent, parts of it were just wrong; the total "reading experience" makes you toes curl.

    This is not specific to automated translates like this. My native language is Dutch but all software installed on my machines is (when I get the choice) in English. The first reason is that I want all my software in the same language. There's allways an English version, a Dutch version is  sometimes available but a lot of the translations are so bad.. Also from big companies. A classical example, MsMail, shows clearly what translating without any context can lead to. In Msmail an email message with an attachment needed a handler for the attachment. If the handler was not installed you could not open the message. In the English version the error mesage was "This message cannot be opened". This stands for two things leading to two different translations in Dutch:

    • You cannot open this message: "Dit bericht kan niet geopend worden"
    • This message cannot be in an open state: "Dit bericht kan niet geopend zijn"

    Gues how MS translated ? Guess how the users reponded ? It took translating the message back to English to make clear what MasMail was trying to tell. My point is that as a developer (even as a user) you just have to know your English. Even when localized resources are avallable the quality is often not good enough, be it autotranslated by babelfish or officially translated by a big software company. And when it comes to feedback things get even harder. I do know some foreign languages, Sahil knows quite a lot more but you can't expect the average mid-western developer to respond in German.

    Is all that English still English ? There's the EN-US the EN-UK and loads of other EN cultureinfo's. Time to add another one EN-WWW: the English being made up by all us foreigners, full of grammar mistakes, spelling errors and incomprehensible language constructs. But it does communicate.

    When it comes to conversation language I do like as many languages as possible. Even in a small country as the Netherlands we do have local languages and dialects and I want to make sure I can at least understand and I enjoy it. As long as it doesn't get funny on the web.

    Moi and oant sjens

More Posts

Our Sponsors

Free Tech Publications

This Blog

Syndication

News