Main

April 10, 2007

Deleting files with special names under Linux

In the spirit of this blog being a way for me to remember how to do things, I present a method to delete filenames under Linux that confuse the command-line utilities.

I had a script which, as a result of a syntax error, produced a file called:

—exclude-from=exclusions

Trying to remove this file by simply deleting it yielded this error:

rm: unrecognized option --exclude-from=exclusions' Tryrm —help’ for more information.

So, Googling found this link:

http://www.cyberciti.biz/tips/delete-remove-files-with-inode-number.html

The method described there is simple. Find the file’s internal i-node number and use the find’s ability to execute any command on results it’s finds to invoke rm on the results.

Two simple commands fixed by file:

obraxus:~/backup> ls -il
total 2932488
1746866 -rw-r--r--  1 ncodigno pg51206   48218112 Apr 10 19:39 --exclude-from=exclusions
1746694 -rwxr-xr-x  1 ncodigno pg51206        328 Apr 10 19:41 backup_primordia.csh
1746494 -rw-r--r--  1 ncodigno pg51206        167 Apr 14  2006 crontab_file
1746547 -rw-r--r--  1 ncodigno pg51206   35799040 Jan 28 03:24 d21_200701.tar.gz
1746442 -rw-r--r--  1 ncodigno pg51206         25 Jan 28 03:55 exclusions
3216545 -rwxr-xr-x  1 ncodigno pg51206       2728 Apr 15  2006 moin_config.py
3216543 -rwxr-xr-x  1 ncodigno pg51206       2688 Apr 15  2006 moin_config2.py
1746546 -rw-r--r--  1 ncodigno pg51206 2915876864 Jan 28 03:23 primordia_200701.tar.gz

Then issue this command:

find . -inum 1746866 -exec rm -i {} \;

QED.

March 11, 2007

My trip to the GDC 2007

Last week I went to the GDC 2007. This is the first time, though, that I’ve had even a moment to try and write something down about it. Hey, four kids and gamer friends keep you pretty busy.

During the conference, I managed to finish reading The Power of Events, by David Lukham and I put a good dent in Networking and Online Games by Grenville Armitage, Mark Claypool, and Philip Branch.

Last week was a blast. I spent a lot of the before and after convention hours with my friend Martin who went to the GDC to check out the Indie developer scene. I went to the GDC to see what the gaming industry did about scale. It seems that managing 8 million subscribers shares a lot of similarities to managing millions of trade executions per hour.

I went to the GDC in 2000, also with Martin, while we were developing our first game, Iron Dragon. As I sat through the sessions of this new GDC, I thought a lot about my current work experience and what I did to pump out the Iron Dragon game. This was a huge case of “if I knew then what I knew now…” that left me constantly thinking about how I might attack a new game title if the opportunity ever presented itself.

So, below is a whirlwind tour of what I saw and what I thought as I made my way through GDC 2007.

Blonde_bockMy flight was easy and uneventful (is there a better variety?). I arrived early enough on Monday March 5 to attend some of the Indie sessions on Monday. This was just filler, really, since Tuesday was the day I was most interested in. At night, I went to a nice brewing restaurant/bar called Gordon Biersch. I ordered up some of their garlic fries (on a friend’s recommendation) and two pints of their Blonde Bock. The blonde bock wasn’t as “blonde” as I expected, but it was a delightful malty beer which left me quite satisfied. Our walk to the restaurant took me to a small part of the Embarcadero, a nice walkway along the San Francisco bay which I would get a LOT more familiar with the next day.

One Day 2, I attended the meat of my attendance at the GDC. A large-scale game development tutorial which talked a lot about coping with large teams, large source code bases, and lots and lots of load.

It was clear that agile development techniques were becoming an increasingly popular theme in all the sessions I attended, and this large-scale app development was no exception. There was an entire segment dedicated to SCRUM, for instance.

The speakers were very experienced and I was delighted to miss the pretentious tone I’m so used to at conferences like this. I got the feeling that these guys have been through a lot and their advice was well-grounded and pragmatic. Topics covered were:

  • The importance of rapid iterations, fast build times, and fast game load times. Since C++ is still so popular in this industry, there was a ton of emphasis on build performance. Not a lot of specific pieces of advice… though. Perhaps everyone knows what to do (dependence injection!) but just needs a kick in the ass to start doing it.
  • The importance of automated testing, both for unit tests and system-wide “functional” tests.
  • The importance of a repeatable process for performance management/monitoring.
  • And much more…

The part on performance management was excellent and the speaker from Alcatel-Lucent executed an engaging presentation on the topic. Perhaps I’ll write a bit more about that in a future post.

That evening, my friend Martin and I went on a wild foot adventure that led us from our Hotel (Parc 55) to the Embarcadero, Pier 39 (and dinner), to Coit Tower, and through the vast mountainous jungle of San Francisco. When I say mountainous, I mean hills of course but these feel like mountains when you’re at the end of your day and you have no gasoline-powered locomotion to help you. Martin “Mr. Fit” didn’t seem to mind, but I thought that perhaps we went a few miles too far in our adventure. Still, now that it’s done, it was a nice experience. Oh, and here is a nice pair of pictures:

MartinNickAtCoit
(This image is a composite of two separate pictures of Martin and I… since no one was available to take the shot… The bridge in the background is the Bay Bridge.)

DSCF0345
(That small silhouette at the base of the Coit Tower is Martin)

On the third day, I guess Wednesday, I attended a lot of filler sessions. One of the topics that interested me was how the designers and artists worked with developers. How do the two teams share in-game assets for example? Also, how to artists feel about the new agile methodologies? At one point, the GDC staffer in charge of entry to the lead artist/art director round table shrugged and asked the artists to be creative and make the packed room bigger. The leader of the session laughed and said something to the effect, “I don’t know, that sounds like a coder problem.”

We all laughed, though I was probably the only one in the room on the butt end of that joke.

Thursday was largely uneventful and my trip home was quiet and smooth. So ended my trip to the GDC, but lots of memories and insight to last me for a long time.

 

February 26, 2007

Rails and Flex

I wrote a little bit about my earliest steps in Ruby on Rails in June. Today, I will start a series of posts that describe what I've done with it lately. Also, I'll slowly be introducing Adobe Flex development into my setup and I'm hoping these two platforms will serve as a good foundation for various projects that I have in mind.

This post will talk about my Rails development environment at home on my Mac and how I plan on publishing my apps to my primordia.com website. It's just an intro post, where detailed steps on everything mentioned here will be the subject of subsequent posts.

My Rig

Here is a summary of how I have things set up:

  • My editor is TextMate, although my friend Rob keeps singing the virtues of the VIM editor and Rails together. Tempting... In any case, TextMate is only available for the Mac, but their is a port planned for Windows in the E Text Editor (beta!). There are some very good screencasts on why TextMate is so loved here.
  • MySQL is used for database work. There are a few reasons for this. For one, it seems like the most popular database backend for Rails development. Second, I have some experience with it. And third, it's the database that I get for free on my public server from Dreamhost. I installed MySQL "Community Server" from the binary, but I had to learn quote a bit before getting things working smoothly. I use MySQL Administrator to administer the database which is a pretty awesome tool.
  • I use Apache as my web server, even during development. Rails developers typically use WEBrick, but the thought of starting it up all of the time and adding the extra port name to my browser kind of bugs me. In an forthcoming Apache-specific post, I'll discuss how I figured out how all of the Aliases and virtual directories are supposed to work.

One option to get all of this working in one step is to use Apache Friends Xampp. Under Windows, for example, you get all of this with one simple setup: Apache, MySQL, PHP + PEAR, Perl, mod_php, mod_perl, mod_ssl, OpenSSL, phpMyAdmin, Webalizer, Mercury Mail Transport System for Win32 and NetWare Systems v3.32, JpGraph, FileZilla FTP Server, mcrypt, eAccelerator, SQLite, and WEB-DAV + mod_auth_mysql.

You get similar functionality on both Mac OS X and Linux. Go for it. Why didn't I use this method? I thought Xampp was only for Windows. Plus, I'm wondering what happens when I have this stuff installed already, in piecemeal. I'm pretty scared to mess with things now. Oh, and there was this warning for Mac and Solaris:

WARNING: This version of XAMPP is still in the first steps of development. Use at you own risk!

Two things don't work yet, but I'm working on it. One is fastcgi. This will allow pages to load faster since I believe Ruby and other "stuff" won't need to be completely reloaded on each page hit. For now, cgi is working find for me.

The second thing I still have yet to get working is subversion. I have a subversion repository set up on my primordia.com server and TextMate even has some integration with subversion. Still, I haven't gotten my Mac to talk to it properly yet. I hope to use subversion as the deployment mechanism for my projects, where code that I check in at home can be sync'd from primordia.com and thus deployed that way. I hope to get this workflow working soon.

So, over the next week or so, you can expect these posts from me:

  • The fun that is TextMate, for Ruby on Rails development
  • MySql Setup, in detail
  • Apache setup, in detail
  • Subversion deployment

December 13, 2006

LINQ to Web 2.0

My colleague Kevin Hoffman just told me that his Dr. Dobb’s article on Microsoft new language integrated query technology (known affectionately as LINQ) has been posted online.

Kevin is the author of numerous books, I think 14. Search for him on Amazon and pick up a few of his works <grin>.

Kevin_drdobbs

Go check it out!

December 7, 2006

Graphic Design and .NET Framework 3.0 Apps Part 2: Rich Graphic Design

This is the second post in a series on graphic design with Microsoft’s Expression Blend and Visual C# Express Edition. In my previous post, I talked about the rich integration between Microsoft’s Expression Blend and Microsoft Visual C# Express. I showed how you can code up a collection of Points and databind that to a graphical object and have that object appear in the Blend design environment.

In this post, I’ll explore some of the fun that’s to be had by playing around in Blend and realizing those rich graphics changes in your C# project.

If you recall, we started off with a simple spiral; part of the source code found in Petzold’s Applications = Code + Markup: A Guide to the Microsoft Windows Presentation Foundation.

Spiral0

I could tweak the XAML file by hand, say to thicken the stroke, like so:

<Grid>
    <Canvas x:Name="_canvas" HorizontalAlignment="Center" VerticalAlignment="Center">
        <src:SpiralData x:Name="data1"/>
        <Polyline x:Name="_poly" Stroke="Black" StrokeThickness="5" Points="{Binding ElementName=data1, Path=Points}"/>
    </Canvas>
</Grid>

Spiral0a

While this is completely possible, there is a better way. You can use Blend’s rich design tools to brighten up the spiral. First, I can load in my C# project into the Blend editor. Interestingly enough, I get to see the extent of the spiral beyond the edges of the window.

Spiral1

I can now click on the spiral in the visual tree to select it. Interestingly, I could not easily select it in the editor. In any case, I can select the StrokeThickness property and change it to 5:

SpiralTools1

Yielding this design-time view:

Spiral2

It gets better. How about I play around with some of the gradient settings. I save my changes and “run” the project as a regular .NET Framework 3.0 app:

Spiral3

Here I am having some more fun:

Spiral4

Nice dropshadow. That’s a trivial effect, by the way, and I have full control over the degree of blurring, the opacity, and the distance the shadow is from the object.

Spiral5

Dizzy yet? What’s even better is that the XAML generated by Blend is almost exactly what I would have done myself if I had memorized all of the property and effect names. It’s ultra-clean XAML:

<Grid>
     <Grid.Background>
      <RadialGradientBrush>
       <GradientStop Color="#FF3F4AB9" Offset="0"/>
       <GradientStop Color="#FFFFFFFF" Offset="0.774"/>
      </RadialGradientBrush>
     </Grid.Background>
  <Canvas x:Name="_canvas" HorizontalAlignment="Center" VerticalAlignment="Center" Background="#FF000000">
   <src:SpiralData x:Name="data1"/>
   <Polyline x:Name="_poly" Points="{Binding ElementName=data1, Path=Points}" RenderTransformOrigin="0.5,0.5" Fill="{x:Null}" StrokeThickness="12" Canvas.Left="-62" Canvas.Top="-61" TextElement.Foreground="{x:Null}">
    <Polyline.BitmapEffectInput>
     <BitmapEffectInput/>
    </Polyline.BitmapEffectInput>
    <Polyline.RenderTransform>
     <TransformGroup>
      <ScaleTransform ScaleX="0.55" ScaleY="0.55"/>
      <SkewTransform AngleX="0" AngleY="0"/>
      <RotateTransform Angle="0"/>
      <TranslateTransform X="0" Y="0"/>
     </TransformGroup>
    </Polyline.RenderTransform>
    <Polyline.Stroke>
     <RadialGradientBrush>
      <GradientStop Color="#FF001392" Offset="0"/>
      <GradientStop Color="#FFFFFFFF" Offset="0.928"/>
     </RadialGradientBrush>
    </Polyline.Stroke>
   </Polyline>
  </Canvas>
</Grid>

In my next post, I’ll play around with creating a “timeline” in Blend and activating it with a mouse click. This will realize a designer’s vision for how something should bounce around the screen, but allow the programmer the ability to activate it via application code. 

December 6, 2006

Graphic Design and .NET Framework 3.0 Apps Part 1: Code in the Designer

Starting Off, from Code to Markup

I'm reading the Petzold book on WPF  (part of the .NET Framework 3.0), Applications = Code + Markup: A Guide to the Microsoft Windows Presentation Foundation, and one of the exercises I put myself through was taking one of his code-centric samples and making it more declarative. I do most of my programming at home in Microsoft’s free Visual C# Express Edition. It’s a simple clean interface and I find that I don’t generally need all of the features of Visual Studio 2005 Professional.

Back to Petzold. In his book, he has a piece of sample code that declares a minimal display tree in the XML markup language XAML, and does the rest in code. The XAML looks like this:

<Grid>
</Grid>

He then adds a Canvas child and a Polyline object as children to the grid in code. Grid is defined in markup, and the children are defined at runtime in code. He has a C# method which loops through 20 revolutions of a spiral. Not rocket science.

Adding the canvas and polyline was done in code in Petzold's book, as follows:

// Make Canvas content of window.
Canvas canv = new Canvas();
canv.SizeChanged += CanvasOnSizeChanged;
Content = canv;

// Make Polyline child of Canvas.
poly = new Polyline();
poly.Stroke = SystemColors.WindowTextBrush;
canv.Children.Add(poly);

While I'll be the first to admit that I love code, this is the kind of thing that separates the "old" way (Win32, OSX) of constructing UI's from the new way (XAML). I wanted to do more delaratively, so I added as much as I could into the XAML, like so:

<Grid>
    <Canvas x:Name="_canvas" HorizontalAlignment="Center" VerticalAlignment="Center">
        <src:SpiralData x:Name="data1"/>
        <Polyline x:Name="_poly" Stroke="Black" Points="{Binding ElementName=data1, Path=Points}"/>
    </Canvas>
</Grid>

Now, notice that the points of the spiral are defined elsewhere, via databinding. Consider the "SpiralData" markup; this instantiates a C# class I wrote which supplies the points needed for the spiral as a PointCollection (Path=Points).  Now *that* is what code is for.

So fine, no big deal. Here is the running app:

Spiral0

Programming XAML by hand in this way feels like programming HTML by hand. It’s easy and precise, but can get time consuming. It also can get tedious and downright impossible to manage as the complexity of the scene increases. Ideally, you would set properties like stroke, fills, and alignment in a visual editor of some kind.

The Awesome Part

Now comes the AWESOME part. Yes, I said that already. Microsoft has a tool called Expression Blend, which used to be called the Expression Interactive Designer. It’s free now, but I guess that it will cost between $150 and $250 bucks when it’s released. Blend is a tool like Shockwave/Flash, allowing you to build vector assets and animate them. Microsoft is also coming out with a tool called Expression Designer which will be analogous to Adobe Illustrator; concentrating on providing an optimal toolset for vector art creation, leaving animation workflows to Blend.

Blend is tightly integrated with C# project files. You can even load a C# project, build it and even launch it as an EXE (just like you would build and run in VS).

However, ...I'm giddy here so bear with me, the visual designer was able to honor my databinding and showed me the spiral in the designer!

Read that again, Blend showed me the spiral in the designer! It looked like this:

Spiral_blend

I could click on the spiral, which was immutable and read-only in it's shape, but I could translate it, scale it, and modify the presentation (like the stroke), all using the designer! There is a complete integration between arbitrarily complex object shapes defined in code and the rich design user interface!

The Designer / Developer Work in Harmony

This is truly the holy grail of app development. Designers can work directly with the code and hopefully a much more rapid feedback loop will be possible.

What About Illustrator?

If I wanted to accomplish a similar feat in Adobe Illustrator, I’d have to learn their complex plugin API and be able to manipulate their internal data structures. Granted, Adobe provides a nice automation interface to do this, an interface exploited by my colleague Pavan Podila in his XAML Exporter for Illustrator. However, it’s not THIS simple. I can’t use C#, my preferred programming language, and I absolutely can’t get this kind of tight intergration between the development and design tools.

I must admit, I can’t imagine that Microsoft will ever (and I mean ever) create a tool as powerful and intuitive as Adobe Illustrator and I can’t see any serious designer using anything but Illustrator. Perhaps Microsoft’s Expression tools will become “good enough” over time to bring some designers on board. Perhaps not. What I think is most likely is that tools like Pavan’s XAML Exporter will mature and get backed by real companies that will provide very robust integration between Illustrator and XAML, Illustrator and Expression, or some other combination.

So, What’s Possible Now?

In a later post, I’ll explore some of the editing features of Blend and how changes in Blend can be realized within your running C# projects based on the .NET Framework 3.0.

December 3, 2006

Bouncing Ball - Source Code

GreenBackground

.NET Framework 2.0A while ago, I offered the source code to my simple physics (gravity) demo I made using Microsoft’s XNA Game Studio Beta. This was a simple change to the default Microsoft XNA Game Studio demo program. Don’t get too excited because the code is pretty basic.

The Trouble Begins

I was all ready to post the code when I thought it would be nice to include the binaries for your immediate gratification. It was then when I fired up fresh copy of XP SP2 running in virtual machine using Microsoft’s free Virtual PC software.

This is when the trouble started. The executable didn’t run. I immediately figured I needed some kind of XNA runtime and sure enough I did. However, the game still didn’t run after I installed the runtime. It looks as if I had compiled by binaries with the first public beta of XNA, but the latest redistributable was for Beta 2.

So, I uninstalled Beta 1 on my desktop and re-installed Beta 2. Then my project didn’t compile. You would not believe the amount of framework changes made between these two betas. At this point, I had to completely rewrite my code just so it would work on Beta 2.

Ok, I thought I was ready so I tried the new binaries on my clean XP virtual machijne. No dice! I had everything installed:

  • .NET Framework 2.0
  • DirectX 9.0c
  • XNA Game Studio Redistributable Beta 2

At this point, I plain give up. I’ll NEVER post this code if I try and figure this out. I can’t believe that I’m that stupid so I’ll just assume it’s a problem with the SDK. In short, you’ll need to install the full XNA Game Studio SDK if you want to run this code.

Code Overview

I basically tweaked these variables until the bouncing looked realistic:

//coordinates to draw the sprite at
double gravityAccel = 3.0;
double frictionDecelY = 1.003;
double frictionDecelX = 1.0075;

Then, we have the UpdateSprite function, which does all of the motion calculations:

        void UpdateSprite()
        {
            //move the sprite by speed
            spriteX += m_dSpriteHorizSpeed;
            spriteY += m_dSpriteVertSpeed;

            double MaxX = Window.ClientWidth - myTexture.Width;
            double MinX = 0.0;
            double MaxY = Window.ClientHeight - myTexture.Height;
            double MinY = 0.0;

            //check for bounce
            if (spriteX >= MaxX)
            {
                m_dSpriteHorizSpeed = -m_dSpriteHorizSpeed;
                spriteX = MaxX;
            }
            else if (spriteX <= MinX)
            {
                m_dSpriteHorizSpeed = -m_dSpriteHorizSpeed;
                spriteX = MinX;
            }

            if (spriteY >= MaxY)
            {
                m_dSpriteVertSpeed = -m_dSpriteVertSpeed;
                spriteY = MaxY;
            }
            else if (spriteY <= MinY)
            {
                m_dSpriteVertSpeed = -m_dSpriteVertSpeed;
                spriteY = MinY;
            }

            m_dSpriteVertSpeed += gravityAccel - 1.0;
            m_dSpriteVertSpeed /= frictionDecelY;
            m_dSpriteHorizSpeed /= frictionDecelX;
        }

Please find the attached zip file which contains the entire source tree, with all temporary and final binaries.

Enjoy!

UPDATE: This code drop seems to work with the released version of the SDK.

October 26, 2006

XamlXporter Released!

Pavan Podila has released his new XalmXporter app.

As promised I've uploaded the source and binaries of XamlXporter. XamlXporter is a script for exporter Illustrator artwork in WPF/XAML. It is written in C# 2.0 for easier maintainence.

It currently exports the following objects from Illustrator CS2:

  • Strokes
  • Linear and Radial gradients
  • Text (single - line only)
  • Opacities
  • Visibility
  • Paths
  • Colors (CMYK, RGB, Spot, Gradients, Gray)
  • Layers, Groups, CompoundPaths
  • XAML comments

For more details about this project visit http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=xamlxporter

 A previous blog post about this project can be found here

October 14, 2006

Cool WPF Blog

My coworker, Pavan Podila, has been doing some amazing things with WPF. He has his own WPF Blog and when he posted a sneak peak at his new XAML Exporter for Adobe Illustrator CS2, I just had to point to it.

Before that, he posted an amazing sample of what you can do with WPF’s 3D mesh support:

Water

Notice the ripple is being dragged by the mouse! Check out this video of the water effect:

http://video.google.com/videoplay?docid=1536259699335459617&hl=en

Oh, and while you’re at it, check out this sample of his OSX “Genie” effect, done i n WPF:

http://video.google.com/videoplay?docid=8775170776607857561&hl=en

 

 

October 10, 2006

Cylons. Why debugging matters.

A work colleague sent me this awesome targetted ad for Visual Studio! It’s placed on Sci Fi’s Battlestar Galactica homepage. Here is the screenshot:

Ms_cylons1-full

October 5, 2006

Google Unveils Code Search - Death of Krugle?

Codesearch_logo

I had previously wrote about the Krugle code searching engine. I never wound up using Krugle because it simply didn't match up to Google's default search. Now, Google has a specific frontend for searching code. What happens now?

I decided to experiment with some of the common searches that I do.

Let’s Compare

Let’s compare what Google Search, Google Code Search, and Krugle all return for the WPF class LinearDoubleKeyFrame.

Google Search returns these results. The first hit is as follows:

LinearDoubleKeyFrame Class (System.Windows.Media.Animation)

Animates from the Double value of the previous key frame to its own Value using linear interpolation.
windowssdk.msdn.microsoft.com/en-us/library/system.windows.media.animation.lineardoublekeyframe.aspx - 24k - Cached - Similar pages

Google Code Search returns these results. The fist hit is as follows:

   331:   DoubleAnimationUsingKeyFrames da = new DoubleAnimationUsingKeyFrames();
          da.KeyFrames.Add(new LinearDoubleKeyFrame(0.0,KeyTime.FromTimeSpan(TimeSpan.Zero)));
          da.KeyFrames.Add(new LinearDoubleKeyFrame(0.0,KeyTime.FromTimeSpan(delay.TimeSpan)));
          da.KeyFrames.Add(new LinearDoubleKeyFrame(1.0, KeyTime.FromTimeSpan(delay.TimeSpan + duration.TimeSpan)));
          da.Duration = delay + duration;

Notice how the Google Code Search is focused on finding me source code and not the API. This tells me that a combination of Google Search and Google Code Search is what I’m looking for.

Now let’s see what Krugle returns.

No standard Code files found for LinearDoubleKeyFrame language:c#.

Suggestions:

  • Make sure all search terms are spelled correctly.
  • Try broader/different search settings for Language, Project and Found In.
  • Check "Related Results" (to the right) for relevant Tech Info results.
  • Try different keywords.
  • Try more general keywords.

Know of a repository we should have found?

Help us improve our search results by sending us your feedback.

Oooh, that’s just NO GOOD. Krugle was very exciting to me, but my gut tells me that it’s very focused on open-source projects. They never seemed to penetrate MSDN, which should be easily indexed and added to their arsenal. So, Krugle is pretty much dead to me since I have a growing confidence that I’ll always get what I need by a simple combination of Google’s default search and their new code search.

Exploring Code Search

Like Google’s regular search, you can do an Advanced Search to fine-tune your results. You have extensive regular expressions support. I could, for instance tell the engine to search for this regular expression: Linear[A-Za-z]*KeyFrame. This correctly returns me results like “LinearDoubleKeyFrame,” “LinearColorKeyFrame,” and “LinearRectKeyFrame.” All of these results are relevant and exactly what I was looking for.

You can also filter on language, much like Krugle, but somewhat difficult/impossible with Google’s old-fashioned search (Did I just call Google search old-fashioned?!). However, VB.NET wasn’t a choice and neither was XAML. They may be added or forever omitted, who knows.

You can also filter your results on the kind of open-source license supported. I don’t personally have a use for this (maybe I should?) but I’m sure tons of open-source developers will find this feature essential. Choices range from the Apache License to the BSD License, to the venerable GPL and GLPL.

Finally, you can limit your search on packages and files. Packages seem to be domain and repository filters. The example they give is kernel.org, but I’m sure you can probably put in sourceforge.net or perhaps even codeplex.com. The filename filter is also pretty awesome and something I feel would be pretty difficult to accomplish precisely with Google Search.

What about Krugle, is it dead?

I personally feel that Google Code Search is going to kill Krugle in the long run. However, I fear that Krugle will suffer a painful extended demise rather than a quick and painless one.

Consider that the Google search engine is extremely basic just like all things Google. Perhaps Krugle can be of value to an audience that finds Google’s simple results lacking.

For instance, Krugle has links to Safari Books Online and their code search results have some pretty cool syntax highlighting. Furthermore, Krugle adorns their basic search feature with multiple result tabs as you dig deeper and deeper in your search journey. They also have UI elements allowing you to save results, add notes, and visualize where the source file lives in the project hierarchy.  That last item is pretty powerful.

That said, I still feel like a quick fix is all I need when I do my searches. I’ll probably use Google Search first and fall back to the source code search when I run out of ideas.

In my head, it’s better to provide a highly specialized yet simple tool that allows your users to combine and mash up multiple tools in in imaginative ways. A huge swiss army knife tool, like Krugle, is probably doomed to get too large, too confusing and ultimately unusable.

 

 

Continue reading "Google Unveils Code Search - Death of Krugle?" »

September 17, 2006

Bouncing glass ball... almost

I’m making some progress on my planned glassy bouncy ball animation. I did this with Microsoft’s XNA Game Studio. However, the ballw as a pre-rendered PNG file… not very sexy.

Here is a screenshot of a resolution-independent screen grab of a static image generated using XAML.

Green_ball_wpf1

I don’t have the animation working yet. I have to do most of it by hand, I think since I’m not too sure how I would express the gravity calculations using the storyboard elements I would ordinarily use for animation in XAML. The code to do this follows very closely to my original post called Easy Glass Buttons.

You can dowload the XAML file for this, here. Kids are pulling at me now so I don’t have time to pick it apart and explain what’s what. Maybe another time ;-)

File Attachment: green_ball_wpf1.xaml (2 KB)

September 13, 2006

What the heck is XAML?

One of my friends asked me what XAML was. I replied to  the best of my ability:

At some point, I'll glassify my blog logo.

XAML is the XML markup which is one way to get visual stuff done in WPF, the Windows Presentation Foundation. The other way is  through code. Vista and soon extensions to XP will let you write applications with a declarative interface. Typically, in Java or C#, you might write a UI by doing something like this:

Button btn = new Button();
btn.Foreground = Brushes.LightSeaGreen();
btn.FontSize = 32
btn.Content = "Hello, XAML!"

In WPF, you can do that but you can also declare the UI like you would HTML... which has some nice succinctness and layout power:

<Button Foreground="LightSeaGreen" FontSize="32pt">
    Hello, XAML!
</Button>

This example was taken from Charles Petzold's new book: Applications = Code + Markup: A Guide to the Windows Presentation Foundation sure to be the next classic just like his original Programming Windows.

Next up is a bouncing ball demo done in WPF, and not Microsoft XNA. The ball will bounce on a glass surface and the reflection will show in real-time. This is the power of the visual brush which is used to paint the reflected surface. It dynamically changes as the source image used to create the visual brush changes.

I think amazing games can be written in WPF, which has support for 3D. You can, for example, create a nice visual and then stick it on a cube and rotate it in 3D. The visual can even animate as the cube rotates.

It’s also kind of a flash-killer. Eventually, Microsoft plans on writing a scaled-down engine to run on other platforms such as Linux and the Mac. This scaled down platform is called WPF/E (E for Everywhere, I think).

Cool stuff.

September 11, 2006

Bouncing ball

I tweaked my XNA Game, adding gravity and bouncy behavior.

The code is pretty easy to get 90% of it right, but there is still some strangeness that I could spend some time cleaning up.

Gravity is merely adding speed over time. So, the stock code provided by the MS tutorial simply kept the “speed” at 1 and updated the Y height by 1 on each update. When the ball hit the bottom, it then moved up at a “speed” of 1.

For this demo, I modified the speed adding gravity which sped up the ball. Speed simply increases and I update the Y height by speed on each update.

When I hit the bottom, speed reverses in a perfect elastic collission. On the way up, speed is negative since Y=0 is at the top. Gravity, however, keeps pulling speed from negative to 0, and then back into positive, causing the ball to fall back down.

I added a friction coefficient which slows down the ball over time, multiplying speed (positive or negative) by a  constant factor.

If you’d like me to post my code, let me know. If you’d like to correct my math, please do!

XNA doesn't like Vista

While I was speeding home from NYC on the LIRR, I tried to get Microsoft’s XNA Game Studio Express to run on my copy of Vista (build 5536). It didn’t work. What’s more annoying is that the problem was at the very end of the install and happened either when it was installing project templates (which is the last thing the installer said it was working on) or when it was trying to install the latest DirectX runtimes. I suspect the latter, or perhaps some other issue. I tried to perform a custom setup but I couldn’t deselect the DirectX portion… nor any portion of the setup for that matter.

It looks like I’ll only be doing WPF on my Vista box.

September 9, 2006

Microsoft's XNA Game Studio Express Beta

I just installed Microsoft’s XNA Game Studio Express (beta). This is a highly anticipated game developer toolkit which allows you to write games for both Windows and XBox 360.

What XNA provides is an application framework so you don’t have to write a bunch of boilerplate code to get stuff done. Your main Game class derives from a framework class called Microsoft.Xna.Framework.Game. This class provides you with a few simple overrides such as:

  • OnStarting() so you can initialize your objects. Their example code seems to suggest this is the best time to subscribe to the DeviceReset event. This is the event called when your graphics device is reset such as when you change color depth or screen size. I test this and yes, it’s true.
  • Update() so you can update your on-screen sprites or game state depending on what’s happening
  • Draw() so you can render all of your graphics

I’m sure the framework does a whole lot more than that, but I’ll write about that at another time.

The first tutorial they show you is a simple bouncing ball (no physics here). They asked me to create my own graphic so I borrowed my easy glass button:

Green

The results are as follows, a simple bouncing ball:

By default, the default render did not honor the transparency in my png file. I had to modify the sample code by adding a SpriteBlendMode.AlphaBlend to the SpriteBatch Begin() method. Also, to make the video smaller than the default window size, I modified the AllowUserResizing property on the Game1 object to true. This was not straightforward to do:

Xna_screen1

I noticed that the game framerate was quite smooth on my 2.7GHz Pentium 4 (w/HT), 2GB of RAM and a ATI Radeon 9800 Pro 128MB graphics card. However, framerate immediately collapsed when I did anything on my machine. Strangely, the game never actually ate cpu. Must be some kind of graphics/bus IO contention going on somewhere.

There is an excellent help system that installs itself. Hitting F1 on a framework class name brings up the framework documentation in a jiffy.

Strangely, the SDK only works with Visual C# Express Edition. That’s kind of strange to me, since I figured it would work with any flavor of Visual Studio 2005.

I hope to experiment more with the XNA SDK in the coming weeks. Sadly, I’m still more excited about posting some of the work I’ve been doing in WPF, Microsoft’s new graphics layer that runs Vista and will be available for XP later this year.

Fun times ahead.

June 22, 2006

bloglines.py: back from the dead

SplashscreenA very long time ago, almost 2 years, I wrote a simple Python module which ran through an OPML file and printed out the feed URL to the console. I used it to extract the podcasts from my bloglines account for all feeds i n a partifular named folder. I tghink at the time I organized bloglines in such a way that my podcasts were all contained in a particular folder. I have since just switched to iTunes. Not a great podcatcher, but good enough.

I was contacted today by someone working on the open source Linix podcatcher client Cast Podder. They were using bloglines.py and wanted to know if it was ok to use the file since I didn’t specify any kind of license. Of course I said sure thing.

When I’m famous, I promise to remember all of you.

May 12, 2006

RailsHelp.com FireFox Search Plugin

I created a quick and dirty Firefox Search Plugin for RailsHelp.com. You can install it here. When you install it, you can type in a Rails search term in the Firefox search box, like so:

Rails_firefox

This will basically bring you to railshelp.com. In the example above, the results returned by entering “render” in the search box.

Stupid, but wonderfully useful!

If you don’t like this search plugin and you want to delete it (or any Firefox Search Plugin) make sure you download and install the SearchPluginHacks extension. Once installed, restart Firefox, right-click on the offending search plugin in the search box dropdown and select ‘delete.’

April 13, 2006

Krugle: Still Waiting...

Krugle

So, I’m still waiting for my Krugle beta...

A colleague of mine were discussing the amazing opportunity these guys could have by selling their engine to corporations. If the search engine really does what it says, it would be a no-brainer for most organizations to install it behind their firewall and provide a search engine optimized for their own source code trees.

Plus, they can get the world to test it for them ;-)

Their survey results from their Alpha testers don’t offer any clues as to their strategy. They seem purely focused on indexing the developer communities out there in the public domain.

UPDATE: I got on the beta, I'll review it here at some point.

April 3, 2006

Krugle: The Source Code Search Engine

I just got a beta notice from Krugle:

You are getting this email because you signed up to test the Krugle search
environment. Either that or a friend/enemy signed you up as some cruel hoax.
If that is the case, you can opt out right now by replying with “Opt Out” in
the subject line and we’ll never contact you again.
 
Assuming you want to be part of the beta test, you are probably wondering why it
took so long for us to get back to you. One big reason was figuring out how to
send mail to 35,000+ people. We had no idea this many would sign up, but we got
that sorted out, so here we are.
 
We started the beta last week with the first 1,000 testers. So far, it's looking
good. Those of you in the 34,000 left will begin getting login credentials (in the
order you signed up) beginning April 5.  We hope to get the lot of you in the test
before April 14 or so, assuming nothing really unexpectedly bad happens.

I have no idea where I am in that queue but I’ll be sure to write a short review when I get my hands on the beta, er, link to the beta. The e-mail went onto offer a link to a 4–minute screencast overview of the project and what they’re trying to accomplish.

Technorati tags: , , , ,

March 11, 2006

Some minor CSS updates

I made some minor changes to the CSS on the site, not that any of you actually visit the site. I’m using Blue Crush by Lilia Ahner (Six Apart). However, there were some things about the theme that I didn’t care for. For one, there was a gap between the module headers and the left edge of the beta element. I closed this gap. I also got rid of the asterisk.

I couldn’t have done this editing without the Web Developer plugin for Firefox. This plugin gives me a lot of options for CSS styling, manipulating images, checking browser compatibility, and a whole lot more.

Web_developer
(click to enlarge)

If you were curious as to how people get here, here is my latest readership breakdown as a pie chart:

Stats_march11

Here is a breakout of the actual feed readers used:

Stats_march11a

Finally, what kind of web browser are you using?

Stats_march11_browsers

 

March 2, 2006

BLOCKQUOTE

Don’t ask me why I just figured this out now.

There are areas of the HTML spec that I simply haven’t covered yet. I’m not a “web” developer so I guess this is to be expected. Discovery is a daily exercise for me. However, I do like to respect standards and I’ve been doing a lot of reading lately on CSS and standards-based web design. A few months ago I read The Zen of CSS Design Visual Enlightenmenet for the Web by Dave Shea and Molly E. Holzschlag.

One of these areas of recent enlightenment is the HTML tag BLOCKQUOTE. BLOCKQUOTE is meant to be used to cite someone else’s words or to otherwise reproduce text found elsewhere. You can even add a CITE attribute with a URI to the originating source of the information. Most default browser implementations style a BLOCKQUOTE as an indentation, but this is not a guarantee. A CSS designer is free to make BLOCKQUOTE do whatever they want. Perhaps the text is instead italicized. A lot of people use BLOCKQUOTE simply for it’s indentation capabilities and are thus misusing the element.

However, as some authors have used BLOCKQUOTE merely as a mechanism to indent text, in order to preserve the intention of the authors, user agents should not insert quotation marks in the default style.

The usage of BLOCKQUOTE to indent text is deprecated in favor of style sheets.

It’s even worse when your tool misuses the element!

Once I read about BLOCKQUOTE, I wanted to see if my favorite blog posting tool supported it. I use a really good (but not perfect) tool called BlogJet((Hey, I just noticed that BlogJet automatically inserts the URL when I type it in… sneaky).

It turns out that BlogJet(grrr) uses BLOCKQUOTE when you indent text. I’ve been indenting text for years using this feature and every time I’ve thus been using BLOCKQUOTE. If you find me going back and editing all of my entries to get into conformance, you know I’ve gone off the deep end.

Vista Sidebar Gadgets - WPF = WTF

From Digg:
Apparently the sidebar for vista will not support WPF ... the new UI technology in Vista! How do I say this, this is insane. Digg this story if you think that this is a mistake ... send the Microsoft Gadgets team a clear message.

read more | digg story
UPDATE: Thanks to Rob for a better title to my post!

February 25, 2006

Raw

Over my vacation to the Dominican Republic, I had some time to do some programming. You might be wondering why in the world I would be programming on my vacation. I have a few answers.

First, I like programming in serene environments. The sound of the beach, the lapping waves and the wind against palm trees is very soothing. I enjoy this almost as much as sitting by the pool or beach drinking a good beer. Second, my son was sick and he basically layed in bed all day like a log. I had to watch him part of the day while the rest of the family enjoyed the sun. Third, the raw files my camera was generating were eating up like 20MB each. Many of my shots were crap and I wanted the raw files gone.

What’s a raw file? A raw file is a proprietary file format stored by most medium to high-end cameras. A raw file stores a lot more color and pixel information than a regular jpg file. First, it’s uncompressed so when you zoom into little details you won’t find jpg compression artifacts. Second, it stores more colors. Typically 12–bits of color per channel. That’s 4096 shades of gray instead of 256. This can make a big difference in certain circumstances, especially when you are changing your image brightness, contrast, or doing color correction. Without this extra color information, an innocent image brightening can wipe out a lot of detail in that very white sand.

I use Google’s Picasa software to manage my photos.  When my camera records raw, I also told it to store a 3 mega-pixel jpg file. Picasa easily imports these and ignores the raw files. I have to manually copy the raw files onto my hard drive.

Picasa is awesome software and I use it to crop photos, delete bad ones, and basically review everything. However, any time I delete a jpg-based photo in Picasa, the raw file remains.

Fortunately the raw file has the same file name as the associated jpg file. It was easy to write a program that will find all *.sr2 (my raw extension) files that have no associated *.jpg file in a given directory tree. Vioa, enter Raw Version 0. Download Raw Version 0. I do have to come up with a better name.

The program will only work under Windows XP and you’ll need to download and install the Microsoft .NET Framework Version 2.0 Redistributable Package (x86).

Raw_v0

Now I can manage my photos in Picasa and clean up the crappy raw files consuming gigabytes of space on my hard drive.

August 31, 2005

Astronomy, and programming, and kids

A friend bookmarked this site on del.icio.us, which is the homepage for an astronomy library for Python called PyEphem. I’ve been toying with a new project idea since January when I took my kids to the New York Hall of Science in Queens. One of the displays was an interactive computer program that teaches you about where to find life in the galaxy. It was kind of a treasure hunt. While  the program was a bit shallow for me, it provided a lot of entertainment for my oldest son.

I played with the idea of writing something myself. Long ago, I bought a book called Astronomical Algorithms by Jean Meeus. I believe this is jean Meeus’ second work on the subject, the first being a book on astronomical algorithms on a pocket calculator. Man that sounds painful.

Anyway, the program I’d like to start and not finish (he, he) would be similar in concept to the NYHoS version, but with a bit more depth and perhaps some real astrometric data. I would either need a library like PyEphem or I’d need to read Jean Meeus’ book very carefully.

I doubt I’d write anything like this in Python, but who knows…

May 8, 2005

Help in Visual Studio .NET 2005 Beta 2

I’ve been playing around with VS .NET 2005 Beta 2. The MSDN Online help integration is amazing. In the previous betas it started to become amazing. They allowed you to integrate help from multiple sources for your search terms.

Notice how in this first search window, I can choose to see help on the MoveWindow API from multiple sources:

Msdn_help1

When I click on MSDN Online, I get many choices (since MoveWindow() is such a common function):

Msdn_help2

I can click on the one that I’m interested in, namely MoveWindow() from the SDK:

Msdn_help3

I could also have seen results from the CodeZone community, a source that I’m not terribly familiar with, but I can certain guess as to its purpose and utility:

Msdn_help4

 

March 27, 2005

Online dice rolling

When we play D&D on Friday nights we need to roll dice. When you’re playing over the Internet it would be nice if everyone could actually see the roll. The solution we came up with a while back was to write a chat program  that had a built-in “roll” command. You could say d20, which means roll a 20–sided die and tell me the result. Or, roll 2d6 which rolls a 6–sided die twice and adds the result.

Writing a chat program is like network programming 101, but I still never got motivated to do it.  So we’ve been using the honor system so far.

Last night I got motivated to be lazy and productive at the same time. I googled for “python chat program” and came up with a Python chat client called Nekkid chat written by Jari Rytilahti. It’s a chat program written in Python (duh) that works with the Naken chat server written by Michael Kohn.

I downloaded and installed the Naken chat server and installed it on my Debian linux server. I use a New Moon dedicated server by Dreamhost. The server is written in straight C and took, oh, about 0.5 seconds to compile and run. It took me longer to review the supplied configuration file than it did to download it and get it running.

Once it was running, I fired up the Nekkid chat client and connected to the server with no problems. I looked at the source code (the beauty of having it written in Python) and saw where I could peek at the client chat input text.

I detected the first word, “roll” and parsed out nds, where n = the number of dice (which can be omitted) and s is the number of sides on the die. I replaced the input text with the result of the evaluation and sent it to the server.

Obviously this is not a “secure” change. A better change would be to detect the command on the server and output text that couldn’t otherwise be faked by a client.

I’ll probably make incremental enhancements from here on out, but it works and that’s probably good enough.

 

 

March 26, 2005

Wobbly and Transparent Windows on Linux

I’m not so much up on the latest and greatest news on the Linux platform, so please excuse my ignorance here. I did minimal research to bring you this news.

There are some cool Avalon-like Windowing magic coming to Fedora and thus the rest of the Linux world. It’s all based on a new OpenGL based window/compositing manager called Luminocity, written as a “toy” project by Owen Taylor.

From what I can tell, it’s not revolutionary technology like I feel Avalon is. More like smoke and mirrors. It doesn’t seem like Luminocity is a generalized graphics renderer. It seems more like a window manager that can take 2D content, warp it in 3D, and then rasterize the result s on top of your display. You still rely on “plain old X” to draw the contents of a Window and then Luminocity will go and warp and twist the 2D rendered surface.

Avalon, on the other hand, creates a display list of hardware-accelerated primitives that can be arbitrarily played with at any level in the hierarchy.

If you go down the page (on the “cool” link, above). You will see some cool widget rendering samples based on some technology called, “Cairo”. Funny how Cairo used to be the code-word for a “future” Windows release that never really was, but which Windows 2000, Windows XP, and Longhorn have some elements of.

 

March 25, 2005

Automating Photoshop in .NET

I found this great link (via Joe Beda’s blog) to a guy who tinkered with the Photoshop CS automation interface. This is not a new trick, but what seems new is the way the ScriptListener plugin was used to log the automation actions Photoshop takes when you do things manually and reverse engineering the necessary script commands.

Here is my tryout of some of the things written about in the link above.

With photoshop running with a few documents loaded, this code:

Ps_auto_code

Produces this console output:

Ps_auto_run

 

Avalon gorgeousness

This stuff makes me drool for Avalon. While I don’t plan on writing any apps that look that good, the point is that everything will look that good by default.

My Avalon vision… where closing a window causes it to explode into butterflies, which fly away with the wind.

Ruby

I’m tinkering with Ruby tonight. Tim Germer keeps yapping about how good Ruby on Rails is so I thought I’d check it out once I read up on ruby. My web host is a dedicated Debian Linux host and I can’t see a Debian RPM here, so who knows if I can use this stuff.

Like eons before when I ran through the Python Tutorial, I’m now going through the Ruby Tutorial (or at least the #1 link in my google search on “Ruby Tutorial”).

We’ll see how it goes.

Now playing: New York Public Radio - The Leonard Lopate Show - Stephen Petronio -03/24/2005

January 21, 2005

Python and SPE

Someone at work sent me a link to what appears to be a new Python IDE. I thought that it couldn’t hurt to mess around with it.

The installation was easy, but a few things bothered me. First, the installer didn’t have an icon. So, I immediately thought that my download was corrupted.

Spe_no_icon

But I’m just being picky. Once installed I was all excited at first but got confused when I tried to locate the launch icon. It seems like there is no launch icon.

I then started hunting around my hard disk for something which started with “spe”. Found nothing in C:\Program Files. I then looked into C:\Python23 and I found spe.py in C:\Python23\Lib\site-packages\_spe. What the fuck is that?

I ran it and some error message about wx package not found happily popped out of my command line. I figured that I needed to install wxPython a Window toolkit. That did the trick. I got a bunch of output that looked like this:

Spe_output

What the hell is Blender, I thought to myself. It seems to be an integrated suite of tools enabling the creation of a broad range of 3D content. It offers full functionality for modelling, rendering, animation, post-production, creation and playback of interactive 3D content with the singular benefits of cross-platform operability and a download file size of less than 2.5MB. Not sure what kind of support the IDE could have for this but I’m certainly intrigued!

Anyway, I waited 10 or so seconds, I got this IDE screen.

Spe_ide

I thought that I’d load one of my simpler Python programs into it. It’s a calendar program that displays a calendar year in my imaginary world of Primordia.

I immediately switched the IDE from Courier New to Lucida Console. It boggles my mind why anyone would code in Courier, but I’m probably just being picky.

The code coloring is turned out to be very attractive. The statement completion, or Intellisense, or whatever, worked perfectly. Here is a snapshot of what my code window looked like once I downloaded the source for my calendar program:

Spe_code

You can see from the screen shot that the “Shell” tab toward the bottom is showing some output from the program. I had to code the go() function on the fly since the original version output HTML via cgi. No fancy Python http servers here. Raw output all the way.

In the shell, I got statement completion when I invoked go(), which was pretty cool.

Also notice that there are tons of other tabs available. Oh yeh, Blender is a 3D modeler:

Spe_blender

Looks like someone used Blender to create this:

SPE also has a cool regular expression tester. You can enter any arbitrary text and write Regexp against it. Here is a sample session where my text buffer had “This is a test” and my Regex was “.*test.*:

Spe_regex

In a nutshell, if you’re doing Python than I couldn’t imagine why you’d use Pythonwin when something like SPE is available for free.

Get real Pythonwin fanatics!

On a side note, I’m listening to a fantastic episode of Coverville, a Podcast by Brian Ibbott.

Now playing: Coverville - Coverville-050118

December 30, 2004

.NET Framework 1.1 SP1

I had trouble installing the Windows Update for the .NET Framework 1.1 SP1. If you have similar problems, uninstall the .NET Framework 1.1 SDK. I think there was an update or “hotfix” to the SDK at some point, which the 1.1 SP1 redistributable complained about.

Once I removed the SDK, I was able to re-install the 1.1 SP1 with no problems.

December 7, 2004

XAML + Sparklines

Via a tip from a colleague who read Chris Sells’ blog, I poked around with Sean Gerety’s Sparklines XAML samples. I’m still a XAML newbie, but I struggled through the syntax and created a XAML sample that is closer to Tufte’s Sparklines samples on the Tufte site.

Sparklines2

And here is my XamlPad window:

The point of this graphic, which I think might have been lost in Sean’s version, is that the red dot represents the last data point in the sparkline and that red color is associated with the red ticker price after the MSFT symbol. There is nothing wrong with Sean’s sample, but I didn’t feel like the sparkline was a word-sized graphic the way Tufte envisoned them. That said, the concept can be stretched many ways, I’m sure and Sean’s interpretation is probably very valid. 

Here is my code.

<Border ID="root" xmlns="http://schemas.microsoft.com/2003/xaml" Height="30" Width="200">
<Canvas>
 <Canvas Left="0" Top="13"><Text>Blah, blah, blah</Text></Canvas>
 <Canvas Left="80" Top="-10">
  <TransformDecorator>
   <TransformDecorator.Transform>
    <ScaleTransform ScaleX="0.3" ScaleY="1.2" />
   </TransformDecorator.Transform>
   <Polyline Points="1,26.23&#xD;&#xA;2,26.19&#xD;&#xA;3,26.14&#xD;&#xA;4,26.1&#xD;&#xA;5,25.76&#xD;&#xA;6,25.89&#xD;&#xA;7,25.73&#xD;&#xA;8,25.62&#xD;&#xA;9,25.83&#xD;&#xA;10,25.54&#xD;&#xA;11,25.86&#xD;&#xA;12,26.1&#xD;&#xA;13,25.94&#xD;&#xA;14,25.94&#xD;&#xA;15,25.93&#xD;&#xA;16,25.78&#xD;&#xA;17,26.12&#xD;&#xA;18,26.3&#xD;&#xA;19,26.33&#xD;&#xA;20,26.35&#xD;&#xA;21,26.13&#xD;&#xA;22,26.48&#xD;&#xA;23,26.56&#xD;&#xA;24,27.22&#xD;&#xA;25,27.24&#xD;&#xA;26,27.54&#xD;&#xA;27,25.95&#xD;&#xA;28,25.45&#xD;&#xA;29,25.33&#xD;&#xA;30,25.53&#xD;&#xA;31,25.16&#xD;&#xA;32,25.22&#xD;&#xA;33,25.51&#xD;&#xA;34,25.45&#xD;&#xA;35,25.61&#xD;&#xA;36,25.48&#xD;&#xA;37,25.59&#xD;&#xA;38,25.8&#xD;&#xA;39,25.95&#xD;&#xA;40,25.85&#xD;&#xA;41,25.08&#xD;&#xA;42,24.93&#xD;&#xA;43,25.2&#xD;&#xA;44,25.31&#xD;&#xA;45,25.03&#xD;&#xA;46,25.19&#xD;&#xA;47,24.41&#xD;&#xA;48,24.15&#xD;&#xA;49,24.5&#xD;&#xA;50,24.63&#xD;&#xA;51,24.89&#xD;&#xA;52,25.13&#xD;&#xA;53,25.18&#xD;&#xA;54,25.16&#xD;&#xA;55,25.38&#xD;&#xA;56,25.09&#xD;&#xA;57,25.37&#xD;&#xA;57,25.72&#xD;&#xA;59,25.83&#xD;&#xA;60,26.35&#xD;&#xA;61,26.37&#xD;&#xA;62,26.37&#xD;&#xA;63,26.39&#xD;&#xA;64,26.7&#xD;&#xA;65,26.53&#xD;&#xA;66,26.5&#xD;&#xA;67,26.7&#xD;&#xA;68,26.88&#xD;&#xA;69,26.61&#xD;&#xA;70,26.57&#xD;&#xA;71,26.46&#xD;&#xA;72,26.77&#xD;&#xA;73,26.99&#xD;&#xA;74,26.59&#xD;&#xA;75,26.95&#xD;&#xA;76,27.15&#xD;&#xA;77,27.02&#xD;&#xA;78,26.9&#xD;&#xA;79,27.08&#xD;&#xA;80,26.96&#xD;&#xA;81,27.01&#xD;&#xA;82,27.29&#xD;&#xA;83,27.4&#xD;&#xA;84,27.65&#xD;&#xA;85,27.91&#xD;&#xA;86,27.71&#xD;&#xA;87,28.25&#xD;&#xA;88,28.8&#xD;&#xA;89,28.48&#xD;&#xA;90,28.01&#xD;&#xA;91,28.3&#xD;&#xA;92,28.1&#xD;&#xA;93,27.81&#xD;&#xA;94,27.54&#xD;&#xA;95,27.7&#xD;&#xA;96,27.43&#xD;&#xA;97,27.57&#xD;&#xA;98,27.66&#xD;&#xA;99,28.16&#xD;&#xA;100,28.21&#xD;&#xA;101,28.24&#xD;&#xA;102,28.14&#xD;&#xA;103,27.45&#xD;&#xA;104,27.37&#xD;&#xA;105,27.52&#xD;&#xA;106,27.46&#xD;&#xA;107,27.21&#xD;&#xA;108,27.04&#xD;&#xA;109,27.15&#xD;&#xA;110,27.18&#xD;&#xA;111,27.36&#xD;&#xA;112,27.4&#xD;&#xA;113,27.04&#xD;&#xA;114,27.06&#xD;&#xA;115,26.74&#xD;&#xA;116,26.65&#xD;&#xA;117,26.61&#xD;&#xA;118,26.59&#xD;&#xA;119,26.38&#xD;&#xA;120,26.24&#xD;&#xA;121,25.98&#xD;&#xA;122,26.2&#xD;&#xA;123,25.67&#xD;&#xA;124,25.66&#xD;&#xA;125,25.84&#xD;&#xA;126,25.71&#xD;&#xA;127,25.45&#xD;&#xA;128,25.4&#xD;&#xA;129,25.73&#xD;&#xA;130,25.11&#xD;&#xA;131,25.1&#xD;&#xA;132,25.35&#xD;&#xA;133,25.15&#xD;&#xA;134,25.15&#xD;&#xA;135,25.5&#xD;&#xA;136,25.69&#xD;&#xA;137,25.98&#xD;&#xA;138,25.8&#xD;&#xA;139,26&#xD;&#xA;140,26.1&#xD;&#xA;141,26.23&#xD;&#xA;142,26.1&#xD;&#xA;143,26.07&#xD;&#xA;144,26.68&#xD;&#xA;145,26.14&#xD;&#xA;146,26.12&#xD;&#xA;147,26.74&#xD;&#xA;148,27.2&#xD;&#xA;149,26.91&#xD;&#xA;150,26.61&#xD;&#xA;151,28.91&#xD;&#xA;152,28.89&#xD;&#xA;153,29.35&#xD;&#xA;154,29.35&#xD;&#xA;155,28.93&#xD;&#xA;156,29.23&#xD;&#xA;157,29.07&#xD;&#xA;157,28.68&#xD;&#xA;159,28.78&#xD;&#xA;160,28.91&#xD;&#xA;161,28.94&#xD;&#xA;162,28.82&#xD;&#xA;163,29.14&#xD;&#xA;164,29.19&#xD;&#xA;165,29.08&#xD;&#xA;166,28.5&#xD;&#xA;167,28.52&#xD;&#xA;168,27.8&#xD;&#xA;169,28.83&#xD;&#xA;170,28.19&#xD;&#xA;171,28.24&#xD;&#xA;172,28.46&#xD;&#xA;173,29.6&#xD;&#xA;174,29.07&#xD;&#xA;175,29.96&#xD;&#xA;176,29.5&#xD;&#xA;177,28.5&#xD;&#xA;178,28.9&#xD;&#xA;179,28.36&#xD;&#xA;180,28.34&#xD;&#xA;181,27.84&#xD;&#xA;182,27.55&#xD;&#xA;183,28.37&#xD;&#xA;184,28.84&#xD;&#xA;185,28.38&#xD;&#xA;186,28.43&#xD;&#xA;187,28.3&#xD;&#xA;188,27.26&#xD;&#xA;189,26.52&#xD;&#xA;190,26.51&#xD;&#xA;191,26.42&#xD;&#xA;192,26.57&#xD;&#xA;193,26.5&#xD;&#xA;194,26.22&#xD;&#xA;195,26.24&#xD;&#xA;196,26.45&#xD;&#xA;197,26.62&#xD;&#xA;198,25.7&#xD;&#xA;199,25.54&#xD;&#xA;200,25.63&#xD;&#xA;201,25.6&#xD;&#xA;202,25.73&#xD;&#xA;203,25.61&#xD;&#xA;204,25.58&#xD;&#xA;205,25.71&#xD;&#xA;206,25.65&#xD;&#xA;207,25.66&#xD;&#xA;208,26.18&#xD;&#xA;209,26.17&#xD;&#xA;210,26.41&#xD;&#xA;211,26.23&#xD;&#xA;212,26.47&#xD;&#xA;213,26.61&#xD;&#xA;214,26.89&#xD;&#xA;215,26&#xD;&#xA;216,26.45&#xD;&#xA;217,26.38&#xD;&#xA;218,26.04&#xD;&#xA;219,26.89&#xD;&#xA;220,26.69&#xD;&#xA;221,27.52&#xD;&#xA;222,27.27&#xD;&#xA;223,27.4&#xD;&#xA;224,27.31&#xD;&#xA;225,26.91&#xD;&#xA;226,27.47&#xD;&#xA;227,27.7&#xD;&#xA;228,27.42&#xD;&#xA;229,26.5&#xD;&#xA;230,26.88&#xD;&#xA;231,26.15&#xD;&#xA;232,25.64&#xD;&#xA;233,25.63&#xD;&#xA;234,25.75&#xD;&#xA;235,25.26&#xD;&#xA;236,25.7&#xD;&#xA;237,25.78&#xD;&#xA;238,26.33&#xD;&#xA;239,26.07&#xD;&#xA;240,26.07&#xD;&#xA;241,25.96&#xD;&#xA;242,25.39&#xD;&#xA;243,24.65&#xD;&#xA;244,24.99&#xD;&#xA;245,24.88&#xD;&#xA;246,24.68&#xD;&#xA;247,23.75&#xD;&#xA;248,23.67&#xD;&#xA;249,24.09&#xD;&#xA;250,24.87&#xD;&#xA;251,24.88&#xD;&#xA;252,24.64&#xD;&#xA;253,24.61&#xD;&#xA;254,24.4&#xD;&#xA;255,24.41&#xD;&#xA;256,24.79&#xD;&#xA;257,24.22&#xD;&#xA;257,24.16&#xD;&#xA;259,24.03&#xD;&#xA;260,24.63&#xD;&#xA;261,24.76&#xD;&#xA;262,25.57&#xD;&#xA;263,25.79&#xD;&#xA;264,25.62&#xD;&#xA;265,25.99&#xD;&#xA;266,26.2&#xD;&#xA;267,26.36&#xD;&#xA;268,25.74&#xD;&#xA;269,25.99&#xD;&#xA;270,26.37&#xD;&#xA;271,25.86&#xD;&#xA;272,26.1&#xD;&#xA;273,25.72&#xD;&#xA;" Stroke="Black" StrokeThickness="0.5" Opacity="1"/>
  </TransformDecorator>
  <Ellipse CenterX="83" CenterY="31" RadiusX="2.0" RadiusY="2.0" Fill="red"/>
 </Canvas>
 <Canvas Left="170" Top="13"><Text>MSFT</Text></Canvas>
 <Canvas Left="199" Top="13"><Text Foreground="Red">29.96</Text></Canvas>
</Canvas>
</Border>

The major problem with my code, of course, is that I manually placed the text elements via pixel coordinates. I don’t know enough about XAML layout to avoid this. This is unfortunate as it would have been a beautiful syngergy between the XAML layout model and the visual use of the sparkline as a graphical word amidst the rest of the text.

But that is a lesson for another day. I suppose I’ll experiment with creating a Sparklines class where I can grab data from an XML file or some arbitrary query and lay it out like text, like so:

<Text>This is a test and here is Microsoft’s performance: </Text><Sparkline Type=”Graph” data=”msft.xml” Foreground=”Black” DotColor=”Red”/><Text>MSFT</Text><Text Foreground=”Red”><Sparkline Type=”LastValue” data=”msft.xml” Foreground=”Red”/>

 

November 25, 2004

First steps in XAML and SVG

As you read this, keep  in mind that I'm on my third Sierra Nevada Pale Ale. SN Pale Ale is, IMHO, one of the tastiest beers your money can buy.

I took my first steps in trying to understand how SVG and XAML can coexist. I'm not really interested in SVG, per say, but I have a nice tool for generating SVG and it's called Adobe Illustrator. Having this tool makes it very pressing for me to get SVG and XAML to play together. I could write a XAML exporter plugin for Illustrator and I might just do that. I downloaded the Illustrator CS SDK and it seems like an awesome SDK... to be continued.

Chris Anderson's XamlPad looks like a clone of the XamlPad application that's part of the Xamlon tool. They have an article on how to use their converter to convert SVG to XAML, but I want to do all of this myself so I'll kind of ignore that.

Now, the Xamlon tool is somewhat puzzling to me. Why the hell would they create a tool that WILL BE obsolete when Avalon on XP or Longhorn ships? Perhaps they see a 2-3 year market for which they think they can capitalize on? Perhaps they are building internal expertise and plan om developing a real XAML on Avalon product? Perhaps they want to be bought out by Microsoft? In any case the tool is impressive and in a vacuum seems like a no-brainer if you're currently developing apps in Visual Studio .NET 2003 and want to use XAML markup for your apps.

Ok, enough of that.

I created a simple polygon in Adobe Illustrator CS, that looks like so:

Star

I exported this as an SVG. There are a lot of options presented and I kind of chose the options that I thought would yield the cleanest SVG file. It just so happens that the options I chose were the same (or very similar) to the ones suggested on the Xamlon article (above). I won't go into that. In any case, this file was generated and attached.

If you look at the file, there is a lot of crap in there. Included in this crap is a whole thumbnail i mage which makes up for most of the file's size. Within all of this crap is the essence of the illustration, which is the following:

   <polygon fill="#8BD3E5" stroke="#0A50A1" points="125.623,186.813 75.582,145.052 12.81,162.6 37.063,102.102 0.977,47.826
    66.008,52.197 106.477,1.104 122.414,64.304 183.512,87.004 128.332,121.691 "/>

I typed this into CA's XamlPad and got some errors that were a cinch to fix. Xaml seems case sensitive and the Adobe Illustrator SVG plugin emits all-lowercase tags. Fixing these casing errors up, yielded something quite exciting:

Star_xamlpad

That's enough thinking for now.

Now playing: Spinecar - Release

November 21, 2004

Easy tryout for Avalon

Wow, Avalon is a cinch to get running on a clean machine. You'll need Windows XP with Service Pack 2 to start.

If you download the CTP, you can find a avalon.msi installation file. Run this on a client and you might get a message like this:

Dotnet20

Ah, well that's easy to fix and you don't even need access to the Avalon CTP. Just point your browser to the .NET Framework Beta 1 and rerun an Avalon sample.

If you forgot to install the Avalon CTP, you'll get a FileNotFound exception. Installing avalon.msi fixes this, of course. However, when you run an app like Chris Anderson's XamlPad (now available via ClickOnce), you  might get this?

If you'll remember, I use the Royale XP theme and you need to copy this file:

C:\WINDOWS\Resources\Themes\Luna\PresentationFramework.Luna.NormalColor.FxStyles

to

C:\WINDOWS\Resources\Themes\Royale\PresentationFramework.Luna.NormalColor.FxStyles

and rename the ".Luna" to .Royale". Then, you'll get the full app that looks just like it does on Chris Anderson's site:

http://www.simplegeek.com/default.aspx?date=2004-11-20T00:00:00

 

 

November 20, 2004

Longhorn, Avalon, WinFX

Quick note. All of my posts on anything about Longhorn, Indigo, Avalon, WinFS, WinFX, etc. will all go under the mega-umbrella Longhorn category.

Avalon Community Technology Preview unleashed!

The WinFX SDK CTP has been released on MSDN Subscriber Downloads. This means you can write XAML appls on Windows XP! I wonder what this means for Xamlon?  I can't wait to start playing around with Adobe Illustrator to create crisp scalable user interfaces.

18% done with my download...

I wonder when this will eventually go RTM and we can begin distributing apps.

 

November 7, 2004

PyBloglines

I wrote earlier about having written a Bloglines OPML (Outline Processor Markup Language) extractor in python. It was fun little project but someone took the topic more seriously and wrote a generic library to access the Bloglines API.

Go check out PyBloglines over at www.josephson.org.

The part of the code that fascinates me most is their use of expat, the fast XML parser for Python. I've never used it, but the syntax is so easy it only took me a few seconds to see what they did and realize how superior it was to what I did. Check out  this code from PyBloglines:

class OpmlParser:

    def __init__(self):
        self.parser = xml.parsers.expat.ParserCreate()
        self.parser.StartElementHandler = self.start_element
        self.parser.EndElementHandler = self.end_element
   
    def parse(self, opml):
        self.feedlist = []
        self.parser.Parse(opml)
        return self.feedlist
   
    def start_element(self, name, attrs):
        if name == "outline":
            if attrs.has_key('title') and attrs.has_key('xmlUrl'):
                sub = Subscription()
                sub.title = attrs["title"]
                sub.htmlUrl = attrs["htmlUrl"]
                sub.type = attrs["type"]
                sub.xmlUrl = attrs["xmlUrl"]
                sub.bloglinesSubId = int(attrs["BloglinesSubId"])
                sub.bloglinesIgnore = int(attrs["BloglinesIgnore"])
                sub.bloglinesUnread = int(attrs["BloglinesUnread"])
                self.feedlist.append(sub)
   
    def end_element(self, name):
        pass

When done, a list of feeds is returned quite handily.

October 4, 2004

Reflections on Programming

A friend of mind started his own blog a few months ago and I kept meaning to point it out. John's blog concentrates on, "design techniques, project management, and the little things that make the day to day slog through coding fun, rather than a chore. " He just moved from bloglines over to blogger.

Subscribed.

As a point of note, I've switched over to bloglines for RSS aggregation. I still use NewsGator, but mainly to read my company's internal blogs. Bloglines has some cool features including blog recommendations, desktop alert clients, straightforward and fast page layout, and much more. The Feed and User directories are always interesting.

 

August 13, 2004

SimpleBits, SimpleQuiz

I started reading SimpleBits blog (Syndication links) to learn more about web design. The author has been running a rather interesting discussion and has modeled that discussion as a quiz called SimpleQuiz. The latest entry is entry XVII.

In this quiz, he proposes a number of formats for markup and his readers discuss the pros and cons of each approach. The entries are easy to digest and I'm sure you'll learn a thing or two about HTML.

If you want to skip the original blog-entry format, as the questions were proposed and go right to the original problem statement and the conclusion, go here.

 

August 8, 2004

Short but complete programs

Short but complete guide on how to write short but complete programs when asking for help in Newsgroups...

http://yoda.arachsys.com/csharp/complete.html

By the way, the Matt Reynolds' site (where I got that link) has consistently answered most of my questions over the past few weeks, through existing Q/A recorded in their forums. Definitely worth a visit.

Matt also has a blog.

 

July 16, 2004

On the way to partial classes, I nearly pulled out all of my hair...

I have an project written in Visual Studio .NET 2003 at home. Around midnight, I get the bright idea to take my two forms and convert them to the newer style of form, which uses partial classes to separate the designer-inserted code and the user-code for a form class.

Great.

The first step was to remove Main() from my form. When you create a new project in Visual Studio .NET 2005, you get a Program.cs file which contains the global main. It looks like this:

#region Using directives using System; using System.Collections.Generic; using System.Windows.Forms; #endregion namespace WindowsApplication1 { static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.EnableRTLMirroring(); Application.Run(new Form1()); } } }

The ApplicationModel class above is my experiment, not default code. The second step is to divide your form class into two sections. So, I generated a new project and used it as a reference. I noticed a few things:

  • The designer class dosn't show up in the IDE's file list. I saw in the csproj file (a simple XML file) that the designer file is simply a dependent file to the main form file that you own.
  • The designer file has the definition for Dispose(),
  • It is home to all of your control member variables,
  • It doesn't specify a base class (this is done by your main form class, though no error is generated if you re-specify it... this has some interesting implications).
  • Finally, the designer file declares the components IContainer variable.

So, in about 5 minutes I cut and paste myself into a corner and was left with a form with no controls on it and multiple compilation errors.

I resolved the compilation errors and guess what? I still have a form with no controls on it.

I decide to re-do my entire form, using my old form as a reference. Note that it's about 12:30am and I'm getting tired.

Now I have a form with controls on it, but the designer code is inserted into my regular class file and not the designer file.

Bitch!

I decide to go to bed, leaving my code in ruin. This is almost as bad as going to bed mad at your spouse. I really wanted to make up with the code, but it left me on the couch and a fitful sleep it was.

 

July 15, 2004

if comparisons in properties

In C++, when I compare variables against constants and "value" in a property "set" method, I put “value” first like so:

if (value == _myProp)

This habit prevents the following catastrophic typo:

if (_myProp = value)

For most types, this statement won't compile in C#. The resulting statement is equal to the resulting type and the if clause expects only a bool. The above line would fail to compile If _myProp were an int. Seeing this for the first time, I was almost ready to switch back to the more attractive form:

if (_myProp == value)

Then I thought what if _myProp is a bool? As you can expect, the line compiles just fine. Therefore, I'm back to the "safe" form of the if statement:

if (value == _myProp)

 

July 12, 2004

Mono 2.0

I see on the Mono web site, that they plan on delivering Mono 2.0 around Q2 2005. Not coincidentally, they plan on providing updates to System.Xml, ASP.NET, and Windows Forms to match the .NET 2.0 API.

I'd love to experiment with writing assemblies in Windows and deploying them on MacOS X. Is that possible? I suppose as long as the referenced libraries are available (like Windows Forms), this should work right out of the box.

I've pretty much decided that my mapper program is going to be written in C# 2.0 running under the .NET Framework 2.0. This ties me to the "Whidbey" timeframe, but that's ok. I can be in beta for a very long time and get lots of feedback.

Getting back to Mono, I also see that Code Access Security (CAS) is missing. This basically means that all applications running on Mono require/have full trust capabilities.

If you want to read more about the Mono roadmap, go to the Mono Roadmap page, which has lots of interesting info.

July 10, 2004

Scrollable control fixed in 2.0 Framework

In my first .NET Annoyances post, I talked about how the ScrollableControl class was broken. There was no way to be notified when a scroll occurred. Well, this seems to have been remedied in the .NET Framework 2.0.

All I had to do was to write a delegate to handle their new Scroll event. The new Scroll event addresses my earlier concerns about knowing the type of scroll. They address this with a new ScrollEventArgs class, which has a Type property of type ScrollEventType.

Anyway, life is good now.

Scrollable control fixed in 2.0 Framework

In my first .NET Annoyances post, I talked about how the ScrollableControl class was broken. There was no way to be notified when a scroll occurred. Well, this seems to have been remedied in the .NET Framework 2.0.

All I had to do was to write a delegate to handle their new Scroll event. The new Scroll event addresses my earlier concerns about knowing the type of scroll. They address this with a new ScrollEventArgs class, which has a Type property of type ScrollEventType.

Anyway, life is good now.

Microsoft Visual C# 2005 Express

I downloaded Microsoft's new Visual C# 2005 Express beta today. Here's a [very] brief overview of my experience.

Installation

You can get the distribution here: http://lab.msdn.microsoft.com/express/vcsharp/

My hopes are that the beta won't mess with my existing installation of Visual Studio 2003. So far, the experience has been a pleasant one.

The installation has minimal steps to it, but it had some quirks. After installing the .NET Framework 2.0, I had to reboot. When my system restarted, the ISO image wasn't mounted so the installation halted with an "Abort, Retry, Cancel"-like message. I mounted  the volume and said retry, but that didn't work. I restarted the installation and it picked up right where it left off.

My version installed these components:

  • Microsoft .NET Framework 2.0 Beta
  • Visual C# 2005 Express edition Beta
  • Microsoft MSDN Express Library 2005 Beta
  • SQL Server 2005 Express Edition Beta

I'm writing a little Battlemap program in C# using VS 2003 and I'm going to try and code it up in the beta for a little while. If I send the build to anyone, they will have to install the .NET Framework 2.0 Beta 1 distribution.

Project Migration

Project migration from VS 2003 was a snap. In fact, a Wizard came up and asked me if I wanted to backup my project in case the upgrade didn't go well. I had no problems.

Editing

It's fast! Invoking the IDE is fast and editing is butter smooth.

I use a plugin called C# Refactory from XtremeSimplicity for refactoring in Visual Studio 2003. However, the refactoring support in the beta seems more solid. I guess that feeling is mainly based on the fact that the refactoring dialogs are invoked much more quickly.

There are numerous other editing enhancements that I'm sure to like, but I won't go into them here.

Designing

What can I say? The beta's form designer is light years ahead of where it was in VS 2003. The toolbox is organized better and gives you a better idea of where your components and controls are coming from.

Help

Finally, MSDN help is integrated both locally and on the Internet. If a help item isn't found locally, it searches the Internet. It took way too long for this to happen.

Conclusion

The download is small (267MB) and it seems to work side by side with my regular development tools. I'll find it hard to go back to VS 2003.

 

July 6, 2004

.NET Annoyances #1

The Annoyance

I have a control that derives from System.Windows.Forms.ScrollableControl. Great. I write my control, which is a kind of square grid that extends beyond the Window's bounds. Great. I scroll my control and see that my control is not repainted the revealed areas. Curious. I think to myself, oh, simple, I'll just override the scroll event and invalidate my Window. I mean, a ScrollableControl has to have a bloody Scroll event, right?

Wrong!

There is no scroll event for a Scrollable Control. I thought I would inaugurate my new column with a gem like this. Providing a Scrollable Control that doesn't have a Scroll event is like providing a custom control that can't be customized. Or, to put it in everyday terms, it's like going into a candy store with your son and leaving without buying him so much as a lollipop.

The Solution

I wanted my lollipop. As usual Code Project came to the rescue. However, once I saw the solution I kicked myself since I should have thought of it myself. The key to the solution is the override of the WndProc and simply handling the WM_HSCROLL, WM_VSCROLL, and SBM_SETSCROLLINFO messages. Here is the class that I found on Code Project, written by Martin Randall:

    public class ScrollableControlEx : System.Windows.Forms.ScrollableControl

    {

        private sealed class NativeMethods

        {

            public const int SBM_SETSCROLLINFO = 0x00E9;

            public const int WM_HSCROLL = 0x115;

            public const int WM_VSCROLL = 0x114;

        }

 

        [Browsable(false)]

        public Point ScrollPosition

        {

            get { return new Point(-AutoScrollPosition.X, -AutoScrollPosition.Y); }

            set { AutoScrollPosition = value; }

        }

 

        public event EventHandler Scroll;

 

        protected virtual void OnScroll()

        {

            if (Scroll != null)

            {

                Scroll(this, EventArgs.Empty);

            }

        }

 

        protected override void WndProc(ref Message m)

        {

            base.WndProc (ref m);

 

            if (m.Msg == NativeMethods.WM_HSCROLL ||

                m.Msg == NativeMethods.WM_VSCROLL ||

                m.Msg == NativeMethods.SBM_SETSCROLLINFO)

            {

                OnScroll();

            }

        }

    }

 

Discussion

 

If your drawing is particularly expensive, you probably want to invalidate only the portion of the Window that gets exposed as a result of the scroll. The above code doesn't do that since the Scroll event doesn't contain the needed information. This information is contained in the low and high words of the WParam property of the Message class shown above. In addition, you'll need the page size found in the SCROLLINFO structure (see the Win32 SDK).

 

A more complete implementation of this extended class would provide this information to the Scroll event so you should be able to invalidate the proper portions of the display.

 

In my case, invaliding the Window was fast enough so I didn't bother. If this changes, I'll write up the solution and post it.

 

 

.NET Annoyances #1

The Annoyance

I have a control that derives from System.Windows.Forms.ScrollableControl. Great. I write my control, which is a kind of square grid that extends beyond the Window's bounds. Great. I scroll my control and see that my control is not repainted the revealed areas. Curious. I think to myself, oh, simple, I'll just override the scroll event and invalidate my Window. I mean, a ScrollableControl has to have a bloody Scroll event, right?

Wrong!

There is no scroll event for a Scrollable Control. I thought I would inaugurate my new column with a gem like this. Providing a Scrollable Control that doesn't have a Scroll event is like providing a custom control that can't be customized. Or, to put it in everyday terms, it's like going into a candy store with your son and leaving without buying him so much as a lollipop.

The Solution

I wanted my lollipop. As usual Code Project came to the rescue. However, once I saw the solution I kicked myself since I should have thought of it myself. The key to the solution is the override of the WndProc and simply handling the WM_HSCROLL, WM_VSCROLL, and SBM_SETSCROLLINFO messages. Here is the class that I found on Code Project, written by Martin Randall:

    public class ScrollableControlEx : System.Windows.Forms.ScrollableControl

    {

        private sealed class NativeMethods

        {

            public const int SBM_SETSCROLLINFO = 0x00E9;

            public const int WM_HSCROLL = 0x115;

            public const int WM_VSCROLL = 0x114;

        }

 

        [Browsable(false)]

        public Point ScrollPosition

        {

            get { return new Point(-AutoScrollPosition.X, -AutoScrollPosition.Y); }

            set { AutoScrollPosition = value; }

        }

 

        public event EventHandler Scroll;

 

        protected virtual void OnScroll()

        {

            if (Scroll != null)

            {

                Scroll(this, EventArgs.Empty);

            }

        }

 

        protected override void WndProc(ref Message m)

        {

            base.WndProc (ref m);

 

            if (m.Msg == NativeMethods.WM_HSCROLL ||

                m.Msg == NativeMethods.WM_VSCROLL ||

                m.Msg == NativeMethods.SBM_SETSCROLLINFO)

            {

                OnScroll();

            }

        }

    }

 

Discussion

 

If your drawing is particularly expensive, you probably want to invalidate only the portion of the Window that gets exposed as a result of the scroll. The above code doesn't do that since the Scroll event doesn't contain the needed information. This information is contained in the low and high words of the WParam property of the Message class shown above. In addition, you'll need the page size found in the SCROLLINFO structure (see the Win32 SDK).

 

A more complete implementation of this extended class would provide this information to the Scroll event so you should be able to invalidate the proper portions of the display.

 

In my case, invaliding the Window was fast enough so I didn't bother. If this changes, I'll write up the solution and post it.

 

 

June 9, 2004

James Avery invented the Internet

Now that I have your attention I'd like to talk about a pretty good article I just read in the new issue of MSDN Magazine. It's called Ten Must-Have Tools Every Developer Should Download Now and it's written by James Avery. I'm a regular reader of James' .Avery blog. He's the guy that does the ".NET Nightly" thing, where he spits out quick links to various tools and articles that interest him at the time. A few other bloggers that I read do this too. Sam Gentile does his own "New and Notable" thing and Mike Gunderloy has his Daily Grind.

His latest article does have a few annoying points, though. In three places (maybe more) he seems to believe that .NET invented something when it actually didn't.

First, when talking about a cool regular expression tool called Regulator he says, and I quote, "There is renewed interest in regular expressions because of the excellent support for them in .NET Framework." Say what? RE's have been around for a long time and you either need them or you don't. If you do, there were and are still plenty of good libraries out there. In the C++ world, we've always had Boost RegEx. Perhaps he's talking about the Visual Basic programmer's perspective? I'm not sure how VB programmers coped with regular expressions in the past. Yeh, perhaps he's talking about them.

Second, he introduces us to a cool reflection tool called Lutz Roeder's .NET Reflector. However, he goes and says, "The .NET Framework introduced the world to the concept of reflection which can be used to examine any .NET-based code, whether it is a single class or an entire assembly." Are you joking? Java has had the Reflection API for years. They were the innovators there.

James also talks about the .NET build tool called NAnt and the .NET based unit testing tool called NUnit and doesn't even mention the original Java-based projects these bad boys were based off, namely Ant and JUnit respectively. Quite expectedly, he does mention Microsoft's upcoming MSBuild technology (which competes on a feature basis with NAnt) which will ship with Visual Studio .NET 2005.

In any case, the tools he talks about are very cool indeed.

May 27, 2004

Revelation: 3D in Avalon

Greg Schechter wrote a blog entitled, Introducing 3D in Avalon and 2D/3D Integration. He says, and I quote:

2D/3D Integration

The programming model of Avalon is fundamentally a 2D one.  Elements are rendered via painter's algorithm, back to front.  There's no notion of interpenetration of elements.  A challenge for 3D is figuring out how it fits into this 2D world.  The approach we arrived at is pretty straightforward - each 3D “world” or “scene” (called a Model3D) is an island onto itself.  It takes a Model3D to be paired up with a Camera before it can be incorporated into the 2D world.  The Model3D+Camera can be thought of as a 2D projection of the model from the viewpoint of the camera, and that projection is what gets incorporated into and composited with the 2D scene.  The 2D element that represents this combination is called a Viewport3D, and is just as full-fledged an element as our Image element, Text element, etc.

As other bloggers have said before. This model works for most desktop applications, but falls short for games programming where the 3D experience needs to be much more emersive.

May 26, 2004

Seductive Longorn: Part Deux

As a followup to my original "Seductive Longhorn" blog, I wanted to point out some new relevant information. I also explore some ideas on how Windows Forms could solve some of my "Wit h Great Power Comes Great Responsibility" concerns with Longhorn.

In my original entry, I admitted my fear that all of the sexy stuff in Longhorn will wreak havok on the user experience. With all of that power and expressiveness, perhaps every Longhorn application will look and act differently from the next.

It just so happens that I'm not the only one to be thinking of this (thank God, because if I were the world would be in trouble). Joe Beda points us to some Aero User Experience Guidelines: Sampler for PDC 2003.

The last section called "Application Archetypes" was most relevant to my rantings, but mostly useless. They present different application  types:

  • Document Editor Applications
  • Database Applications
  • E-Commerce Applications
  • Information/Reference Applications
  • Entertainment Applications (A picture of Halo for the PC)
  • and Utility Applications

All of these application types were merely screenshots of existing applications. They all seemed to be running under Longhorn, given the way controls looked, but few if any were Longhorn-specific applications. So, there was little guidance in how to contruct a form or a dialog in such a way that you can make your form or dialog look cool, but which wouldn't require a massive investment in time to understand how to manipulate.

Perhaps Windows Forms is the answer. A Windows Form application has familiar structure. You start with a form, you slap controls on that form, and you program the form from there.

I suppose some future version of Visual Studio (Orcas?) could allow the user to write standard Windows Forms application, but suddenly present a family of properties and options enabled by the power of Avalon. For instance, when working with a Windows Form and controls, perhaps you are presented with these additional Longhorn-specific options:

  • When the form is dismissed, would you like it to explode into butterflies and fly away?
  • When a combo drops down, would you like the selection list to be fade in and remain semi-transparent?
  • Would you like me to auto-generate a algorithmic texture for your form and etch your controls on this canvas? Would you like marble, quicksilver, or stone floor?
  • When you expand your options dialog to show advanced options, would you like the the advanced options controls to be caught off guard, scream at being suddenly exposed, and quickly fall into their proper places?

You get the picture.

 

May 17, 2004

Extreme Programming vs. Interaction Design

Jon Udell writes about "personas":http://weblog.infoworld.com/udell/2004/05/17.html#a1001 and points be back to an "blog entry":http://weblog.infoworld.com/udell/2002/06/13.html he wrote a while back about a well-covered topic (though he recognized this in the end by providing a link to a "google search":http://www.google.com/search?hl=en&ie=UTF8&oe=UTF8&q=extreme+design%2C+extreme+programming on his entry's title). My favorite quote form the article was:
It's extreme design versus extreme programming. I don't buy either one completely. Call me an extreme anti-extremist. Call me a bundle of contradictions. There's more than one way to do it. I'll never sign up for a methodology, no matter whose. But I'll learn what I can from all of them.
He points out an interesting contradiction between Extreme Programming and Interaction Design ("Extreme" design). The former school promotes interative discovery. The latter school promotes a complete up-front thought process about the problem domain which is aimed to produce a complete specification. The google link points to an article specific to this topic in which Kent Beck (of XP fame) and Alan Cooper (of Interaction Design fame) defend their philosphies. The article is called "Extreme Programming vs. Interaction Design":http://www.fawcette.com/interviews/beck_cooper/ In the article, Copper explains how XP is a developer's self-defense against problems in the organization. Rather than try and solve the problem through the tenets of XP, Cooper would rather fix the organization. Cooper says,
I think XP has some really deep, deep tacit assumptions going on, and I think the deepest tacit assumption is that we have a significant organizational problem, but we can't fix the organization.
Beck holds fast that all of the interaction analysis doesn't have to hold up the production process. He contests that once the customer sees what has been created, they can tell you what's right, what's wrong, and what needs to happen. Cooper's main point is his assertion that the customer cannot give the correct answer. Cooper says,
This is one of the fundamental assumptions, I think, that underlies XP—that the requirements will be shifting—and XP is a tool for getting a grip on those shifting requirements and tracking them much more closely. Interaction design, on the other hand, is not a tool for getting a grip on shifting requirements; it is a tool for damping those shifting requirements by seeing through the inability to articulate problems and solutions on management's side, and articulating them for the developers. It's a much, much more efficient way, from a design point of view, from a business point of view, and from a development point of view.
Fascinating. I can't help but to raise the glove of Alan Cooper. Even though the two tried to kiss and make up in the end, they got back into a fight and Kent Beck just seemed desperate to validate the code-right-away philosphy. Alan Cooper's lets-just-think-about-the-problem approach seemed to much more rational to me. I say that with one caveat, though. IMHO, The waterfall approach is fundamentally flawed and my agreement with most of what Alan Cooper says does not in any way imply I approve of long discrete phases of development. It's damaging for a developer to work on a recent bug in code he wrote months ago. There is information and understanding achieved once development begins. When Kent Beck and Alan Cooper were both charged with finding a way their philosophies could interoperate, it was Alan Cooper's description that seemed to make more sense to me. Read the article and tell me if you disagree.

May 14, 2004

Suductive Longhorn

I just installed the WinHEC build of Longhorn. It didn't seem any different than the PDC version I had previously. Before the install, I was aware that there were some spectacular changes available, but I didn't know if it was part of the new WinHEC build. Then, a colleague told me to run "sbctl.exe start" in my \Windows\i386 directory and I instantly saw what all of the gasps and awes were about. Holy cow! The shading effect below all Windows is neat. The fade/scale-in technique used by appearing dialogs is neat. The Alt-tab 3D task-switch stuff is also neat. There are all sorts of new UI tricks for standard stuff like Wizards that MS is playing with. Some of it's kind of icky, IMHO. I saw a lot of different UI styles in a lot of different Windows. I think each team must be experimenting since the experience seems a bit of a hodge-podge. This made me think of a danger Longhorn poses to the user. I think that standardization of UI’s will start to fall away once the developer starts XAML'ing their way to UI Nirvana. Each application will be as unique in Longhorn as each web site you visit on the web. I don’t think I like that. I think there is a productivity gain, an intuition, in knowing that the Tools menu has an Options item and that the File menu us used to save and load files. Obviously a menu bar is probably one UI element that will stay around in the Longhorn world, but I feel so much will change from application to application that the user experience will suffer. Perhaps this isn't true. Perhaps the tools in place and the UI guidelines will be clear enough that I'm worrying about nothing. I'll just have to read more and see for myself.

April 20, 2004

VS 2005 Visualizers for managed code only

I just found out that the cool visualizer feature of VS 2005 is for managed code only. This feature is extremely cool and I was hoping that it would have been available to unmanaged C++ projects. Duncan Mackenzie wrote up an entry called "Scott Nonnenberg on Debugger Visualizers in VS 2005":http://weblogs.asp.net/duncanma/archive/2004/04/17/115418.aspx, where you can find a lot more information on debugging. The visualizer feature allows you to write any Winform code you want in order to debug a variable. You basically select your watch variable, for instance, and select a visualizer like "Image", "XML", "spreadsheet", etc.

April 15, 2004

Change now, change later...

I'm going to refer to the article I mentioned in my last blog entry once more, the article where "Bill Venners speaks with Luke Hohmann on Marchitects (ug)":http://www.artima.com/intv/marketect.html (ug). The article has a nice quote on the difference between an XP approach and a pragmatic approach: Both the XP crowd and the Pragmatic Programmer crowd are making a bet. Either bet is a future option: the option to not spend the money now, or the option to spend the money now so that the cost of future change presumably is less. If the Pragmatic guys make the bet to spend some money now, and they're right, we're all happy. If they're wrong, we may have some crud to take out or clean up. If the XP guys make the bet to not spend the money now, and they're right, then we haven't incurred the cost, and we're happy. If they're wrong, if it turns out you need to make the change, then you've got to go back and refactor and retrofit. Personally, the pragmatic approach seems more natural to me. I'm a big fan of many XP concepts but to "Do The Simplest Thing That Could Possibly Work":http://xp.c2.com/DoTheSimplestThingThatCouldPossiblyWork.html just seems stupid to me in many situations. I suppose if I could map out a project and all of the decisions I'd have to make while working on it, a good baseline for all of my decisions might be "Do The Simplest Thing That Could Possibly Work". I kind of dig this baseline since it helps you start out in a mode where you aren't in danger of over-designing a project. However, it's just a baseline! However, I'd treat this map like an graphic equalizer and push up the sophistication of pieces that I felt are in danger of change. I'd do this in advance of any requirement. I think that philosophy violates XP a bit, but I think the violation is warranted and I kind of fault XP for promoting it so strongly. I mean, if I look at a piece of poop, I know it's going to smell like crap. I don't need to discover this by getting too close. Likewise, if I were writing a feature that depended on a few business rules that I felt could change, I'll design the rules tests in a way that new rules can easily be added. Obviously if I'm inexperienced, especially in the problem domain, such risk-taking could bite me. I suppose you have to take that philosophy with a grain of salt. The rules behind some features may simply never change and if you don't know this then you should probably "Do The Simplest Thing That Could Possibly Work".

April 5, 2004

Indigo on Windows XP

Juval Lowey, in his blog post on why Windows Forms should be embraced, despite the Longhorn buzz, confirms a rumor I'd been hearing lately. That "...we know Indigo will be available on Windows XP too." Sweet.

March 31, 2004

When not to use SOA

Jason Bloomberg talks about "Why SOA may not be right for you":http://www.zapthink.com/report.html?id=ZAPFLASH-02162004. Specifically, he states that it might not be a good fit in a heterogeneous IT environment. I'm not sure I understand that (notwithstanding the fact that I doubt any of these exist). As I take each step in my journey to understand all of this stuff, I find myself at an interesting crossroads. Is SOA a fit for the issues I face each day or should I create a more specific solution? My gut tells me that SOA, at face value, is a manifestation of some pretty sound principles like abstraction, separating implementations, and de-emphasizing objects (and instead emphasizing getting some work done). Plus, it seems like a lot of good technology is being developed to make this stuff a dream to work with. So, on my to-do list is to learn about how SOA scales and what technologies exist that help out with that. If a single server implements my service, how do I distribute that to some idle worker machine?

March 29, 2004

Dialog Editor

Check out the dialog editor in Whidbey: Whidbey.png Notice a few things: * The spacings are marked with dotted lines. These appear when your control snaps to the correct position, say to the edge of a dialog or to another control, both veritcally and horizontally. * The red baseline is to line up text in controls that have different heights! How cool is that?! On that last point, I wonder how your own custom control can play nice in Whidbey and integrate with this feature. Perhaps you implement an interface or provide a baseline property that allows the environment to adapt.

March 25, 2004

VSLive! - Wireless access... good

Wireless access is good here. I'm getting 5.5Mbps now, but I was geting up to 16Mbps at times (I have a Wireless-g PCMCIA card). This is good news for blogging in the middle of sessions...

VSLive! - Richard Hale Shaw on better C# class design

So, I'm sitting here listening to Richard Hale Shaw talk about better class design, CLS compliance, and FxCop, among other things. I guess I'm writing a brief overview of the talk, complete with my own comments on the content. Kdeep in mind that this is a stream of consciousness post, so expect sudden stops, spelling mistakes, typos, and lost of unfinished business... CLS compliance is all about what you expose outside of your assembly, not the private interface. - Create consistent usage: delegates 1st param sender, 2nd param e use specific suffixes for certain types, such as "Attribute", "Collection", "Exception". etc. MyException, etc. some prefixes and suffixes to avoid, like Delegate, Enum, Before, After. I;m not sure I agree with this one. _btnMine, _cboMembers, leading underscore and common type prefixes. Underscores show up first when you use intellisense. Possibly a plus. The acronyms help group the items within the Intellisense UI. Base classes have some advantages in that you can version them and free the deriver from the problems that would otherwise follow. This is interesting and requires more investigation. The reflection stuff is cool... and easy... lots of cool ways to exploit it. Use static classes instead of creating a regular class with all static methods. This is new for C# 2.0. This is perhaps an alternative for cases where you might want to use sealed. Again, I need to re-read this stuff since I'm not sure when I'd use one or the other. Richard went into quite a bit of detail when he described the differences between Value types and Reference types. He presented lots of his own guidelines and guidelines that he's gathered. For instance, ValueTypes are useful when yoiu have many of them, lifetime is short, and they are relativelky small, say 16 bytes or less. Boxing and unboxing is an issue with ValueTypes. His rule of thumb is to write most types as reference types and prototype and look for hotspots. Only change to ValueType when there is a performance bottleneck. Brute force casts are evil (necessary for ValueTypes) but everyone should prefer as and is keywords. Static casts bypass the compiler and force cast exceptions at runtime, which is really bad. Checked exceptions, not a good idea. They are in Java, but they are enormously cumbersome and stick on poor performance. The as keyword will simply return null, like C++ dynamic_cast (when RTTI is enabled). You can check for it (efficiently) and move on... Here's an interesting one. Avoid properties that return arrays. They look like indexers, but aren't indexers. The returned array is a copy and has no built-in semantics. I've never written an indexer property, though I know the basic idea, so some experimentation is in order. Do you see a common theme here? Delegates vs. Event objects. Hmmm. I missed some of the details on his point here, when to avoid delegates. I'll have to talk to him afterwards to resolve this. Looks like Richard Hale Shaw went over, so things are closing down quite abruptly. I'll be thinking about a lot of this stuff and I hope to post followup posts. Comments on any of this are welcome.

March 24, 2004

VSLive! - VS 2005 - Windows Forms

Wow, incredible stuff. I attended a Windows Forms demo this morning, where many of the new features of Visual Studio 2005 ("Whidbey") were demonstrated to spectacular effect. Here are some quick notes I jotted down: Dialog Editor Holy crap. The dialog editor can snap controls to alignment. I knew this from the PDC bits. However, what's new is the control auto-spacing, matching Windows design guidelines. If that weren't enough, they provide guidelines for different control types so the fonts all align, even though the frames of the controls may differ. Are you kidding me? You can edit common string properties without going to the properties menu. I could swear I saw this before, perhaps in Sheridan's VBAssist from the old days? Anyway, cool feature. FRefactoring support pervades the designer, the code editor, the property editor and the solution explorer. Changing class names ripples through everything. For VB, the "My application" project designer was cool. Most of the functions yoiu might set in an installer were part of the project properties, enabling seemless distribution later on, with ClickOnce, for instance. Toolstrip control is cool. SmartTags are cool. You can perform common actions on various controls that support it, which seems like most or all of the out of box components. Partial Types allow you to put user and designer code in separate files. This has some profound benefits, allowing you to take advantage of some of their code generation features without worrying about blowing away your customizations. Security I was blown away by the "Calculate Permissions" feature, where VS iterates over your code and suggests permissions that will be needed. They even integrated this notion of required permissions into Intellisense, to the point where you are warned when you are about to call a method that will require permissions you aren't set up for. Oh yeh, you can set up a debug sandbox, where you can similate the permissions you plan on deploying with. "PC in the wild", allowing the user to acknowledge possible problems that can be detected at install time (like permissions needed, but not initially granted due to deployment config). More to come...

March 18, 2004

SOAWiki

"James Avery":http://dotavery.com/blog/ blogs about his new "Wiki":http://www.c2.com/cgi/wiki dedicated to Service-Oriented Architectures. The Wiki is called "SOAWiki":http://www.soawiki.org/default.aspx/SOAWiki.HomePage, though that's not a real "WikiWord":http://www.c2.com/cgi/wiki/wiki?WikiWord in the purist sense, but you get the point. Enjoy.

March 13, 2004

Avoid the GAC

Chris Sells tells us to Avoid the GAC.

In my previous DeepSize post, my instructions include using gacutil which, of course, installs DeepSize into the GAC. While my little application will never get updated by another party and possibly installed over the a version you may have already installed (wishful thinking), I suppose I should reconsider my choice to use the GAC for DeepSize.

After doing some research, it looks like I have to put the explorer extension in the GAC. I tried various configurations such as placing DeepSize.dll in a directory on my SYSTEM path and calling regasm. I understand that COM doesn't deal with the path since explicit references to the path a COM DLL is located is hard-wired into the registry when regsvr32.exe is invoked on the library. However, none of those scenarios worked.

I Googled for a few more articles on the topic of Explorer extensions and one link in particular corroborated the original Code Project article's instructions on placing the Explorer extension in the GAC. See Extending Explorer with Band Objects using .NET and Windows Forms (also on Code Project).

Furthermore, I'm beginning to understand the role of RegAsm.exe as opposed to regsvr32.exe. You can't register a .NET DLL using regsvr32.exe since a .NET DLL doesn't support the old COM registration functions. RegAsm.exe works through COM Interop, which, while it exposes .NET objects as COM objects, it doesn't do it through old fashion means of DllRegisterServer() and DllUnregisterServer().

I definitely dig having the Chris Sells piece in my mind. However, I'm also glad I've gained a little personal experience on when to do and not to do something.

March 12, 2004

Miguel de Icaza "C is dead"

I just read this fascinating article over at LinuxWorld. "Still Bringing Windows Developers Over to Linux, Mono Gathers Speed":http://www.linuxworld.com/story/44050.htm Being a regular reader of Miguel's blog, I've been watching this unfold on a daily basis. This article made me snap out of the miniscule and see he big picture. After reading the article and the discussion that followed. I have a few short observations. First, people starting beating up Java saying that it's not used by any serious Linux developer. The obvious choice is C. I guess that's true for Linux developers on the desktop but it's obviously not at all true for Web developers. People working with SOA are almost exclusively working in Java from what I understand (caveat, I'm not a Web developer!) Second, I wonder which group of developers Mono development will more displace? I'm also curious about when Miguel and his team will start targetting the WS-specs that Indigo has latched onto. Hmmm. That last thought is interesting. Once Mono is mature, how much of the IL and assemblies produced by the Microsoft team can be directly used on top of Mono? I'd like to think I could answer that question myself, but I still haven't wrapped my head around all of the architecture involved here...

March 11, 2004

ADO .NET Links

I'm mostly bookmarking here since I'm reading a lot into ADO.NET lately... ADO.NET Articles on Know .NET: * "Efficiently Using ADO.NET - Part I":http://www.knowdotnet.com/articles/dataviews1.html Efficiently Using ADO.NET - Part I * "Efficiently Using ADO.NET - Part II":http://www.knowdotnet.com/articles/expressions.html Efficiently Using ADO.NET - Part II Some migration tips from J2EE to ADO.NET: http://www.c-sharpcorner.com/Code/2003/March/J2EEtoDotNet.asp "From ADO to ADO.NET: A Gradual Approach":http://www.developer.com/net/net/article.php/2228221 (This is where I'm coming from...) Some interesting thoughts on "performance of ADO.NET/Oracle":http://groups.google.com/groups?q=ADO.NET&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=128401c2342d%24db1a45e0%249be62ecf%40tkmsftngxa03&rnum=7 "Wintellect ADO.NET FAQ":http://www.wintellect.com/resources/faqs/default.aspx?faq_id=1 Another "ADO.NET FAQ":http://www.able-consulting.com/dotnet/adonet/adonet_faq.htm "A decent introduction to ADO.NET?":http://visualbasic.about.com/library/weekly/aa041203d.htm Code Project strikes again with an article on "Using ADO.NET in a managed C++ application":http://www.codeproject.com/managedcpp/adodemo.asp. I must admitm though, that I'm looking for the same thing for an unmanaged C++ application hosting the CLR. And again, "ADO.NET – Get the notification events from Managed Providers":http://www.codeproject.com/dotnet/usingado3.asp Got any other good ADO.NET links?

Visual Studio Debugging Tips

Min Kwan Park put together a nice document on how to troubleshoot your VS7 debug sessions. Over the years, I've collected a few links that have been useful to me. Here are a few: * "Making the Visual C++ 6.0 debugger not 'step in' ":http://www.codeguru.com/Cpp/V-S/devstudio_macros/debugging/article.php/c3207 * "Remote Debugging With Visual C++ 6.0":http://www.differentpla.net/node/view/67 * "Microsoft Visual C++ Tips and Tricks":http://www.highprogrammer.com/alan/windev/visualstudio.html (this site has incredible information) * "Debugging in Visual Studio - getting started.":http://visualcpp.net/index.php?qID=25 * The Code project just posted this nice link on "Tips and Tricks for the Visual Studio .NET IDE":http://www.codeproject.com/useritems/VSnetIDETipsAndTricks.asp * I just found this link, and I hope to watch it soon. Software Legend Juval Lowy demonstrates his "Tips and Tricks for Visual Studio .NET and C#":http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20030701VSNETJL/manifest.xml * "Tips and Tricks Using Managed Code (Managed DirectX)":http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/directx9_m/directx/tipstricks.asp Got any of your own links?

March 10, 2004

DeepSize

Sometime last summer, I saw a cool article on the Code Project called "Explorer column handler shell extension in C#":http://www.codeproject.com/csharp/columnhandler.asp.

While I had some desire to see MD5 checksums of certain production files, I was more excited by the idea this article gave me. What if I modified the code to provide a "deep size" column in Explorer that would show the total size of all files in a directory? To me, this is a very useful thing.

So, I went and wrote the thing and it officially became my first C# program... or first C# Class, since I just modified the existing assembly.

I have a pre-built version here, along with my source (which is a modified version of the Code Project original).

Download file

I didn't find any kind of copyright in the source files, so I didn't include anything in mine. I hope I didn't miss anything there and I offer apologies in advance to the original author if I did.

To install it, I like to copy if to my Global Assembly Cache. Just execute:

gacutil /i DeepSize.dll

Then, you need to register the assembly as a COM server via:

RegAsm.exe DeepSize.dll (register the version in your GAC).

You may need to restart explorer by logging out than back in. Once you do, right-click on any explorer file ListView (aside from My Computer and My Network Places) and select "More...". "DeepSize" and "MD5 Hash" should be new choices.

I exclude certain directories from consideration, since it's well known that they are big. These are directories "ending" in:

* "PROGRAM FILES"

* "DOCUMENTS AND SETTINGS"

* "WINDOWS"

* "WIN98"

* "WINME"

* "I386"

* "WINNT"

When I included those, performance suffered and the other directories I was interested in had to wait until those monsters were calculated.

Feedback welcome. If you want the rest of the Visual Studio files, let me know and I'll provide them.

Enjoy!

Copy and Paste Files from the Command Line

I'm one of those programmers that tries to use the keyboard and mouse equally. I do this mainly because I hate to clutter my desktop, Quick Launch bar and Start menu with a zillion icons. I tend to write a lot of batch files. I have a directory called C:\utils, which has interesting binaries I've collected over the years. I also have a C:\utils\bat directory with abotu 150 batch files I've written over the years. Some of the common batch files are: *n* —Starts my default text editor *eb* —edits a batch file in C:\utils\bat, without having to specify the path *set_env* —Using Python and Win32all, I can set an environment variable permanently, not just in my shell *desktop* —Changes to my desktop folder, at the command prompt: C:\Documents and Settings\ncody\desktop. I'm also a big fan of Cygwin, since I need to ssh and scp files to my web server almost daily. To copy files from my desktop to Cygwin, I generally type "explorer ." while in my Cygwin home directory and drag the file from my desktop to the new explorer instance. I close explorer and now have the file available. I also have a bunch of batch files that switch me to important directories. All of these batch files use the most excellent *pushd* and *popd* commands, so I can move from directory to directory and always have the ability to go back up my current directory stack. One welcome addition to this workflow is a new utility, written in C# that allows you to copy files from one directory into another. You can read about it here. All you need to do is say: ezclip copy myfile.txt cd some_other_directory ezclip paste Done. I've already been using this tons, which is a lot easier than navigating my complex directory tree in explorer. UPDATE: I noticed that wildcards, directories, and sub-directory traversal are not supported. It seems to me that this wouldn't be hard to implement after looking at the source. UPDATE #2: With a minor tweak, I made a minor improvement to the code. Unfortunately, you can no longer use the multi-file syntax using my method (file1 file2 file3), but you can use wildcards. To do this, I simply changed this like: --
string[] files = new string[args.Length - 1];
Array.Copy(args, 1, files, 0, files.Length);
-- To this: --
string[] files = Directory.GetFiles(@".", args[1]);
-- To make this code production quality, of course, I shouldn't have to specify "." as the current directory. If args[1] specifies a directory, I should extract it and use that. Also, it wouldn't be hard to accept multiple files as Gus Perez did originally, allowing each argument to be a single file or a filespec (myfile.txt *.log *.xml)

March 9, 2004

Waiting for GaXAML

(No, not a blog entry about "Samuel Beckett":http://samuel-beckett.net/Waiting_for_Godot_Part1.html) Rather, Chris Sells pointed out that Chris Anderson pointed out that Mike Harsh tells us about an interesting WinForms markup written by Joe Stegman. Using Windows Forms Markup Language (WFML), you can use markup today! That little tidbit opened up my browser to the entire windowsforms.net. What a kick ass site that is.

March 4, 2004

More on .NET Code Access Security

I've been doing a lot of reading on .NET Code Access Security lately, which is the new security security model for .NET. CAS represents a stark contrast to traditional Windows permissions, which are based on the permissions of the user. Most developers log into their machines as Administrators since that's the only way to get anything done! For instance, it's the only way that you can install software, the only way you can adjust system wide settings and, most unfortunately, the only way most Windows programs work properly! My kids have their own computer, an older machine I've been keeping healthy over the years. I'll be damned if I can find a single kid's game that works properly out of the box while running as a non-priveleged user. If you are a skilled Windows user, you may be aware that you can run a program as an Administrator even when your regular user account is non-privileged. The steps are documented in the "online documentation for Windows XP Professional":http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/windows_security_runas.mspx. Personally, I don't have the guts to try running my day as a non-privileged user. I tried it a few times and I nearly pulled out my hair. Despite the limitations imposed on non-privileged users, they still have full access to their profile and they can write to most areas of their hard drive (excluding areas owned by other users and the system areas.) Thus, under the Windows security model, any program that you launch as a non-privileged user can still do things that you or your system administrator may not want it to do. A good example of a situation where a program should have a subset of a user's permissions is a financial application that displays sensitive information to the user. The administrators may want to prevent the application from printing, writing to files, allowing itself to be screen captured, use the clipboard, etc. Obviously a programmer can omit these features, but will the administrator believe them? Probably, but that's another problem entirely ;-) Microsoft seems to have nailed a far better approach to this problem. Under .NET CAS, the administrator can define rules of use on the enterprise level, the machine level, or the user level. The rules are extensive! Here is a taste on the types of permissions you can grant or deny to an application: * Writing to a file, a directory, or a network share * Opening top-level windows, dialogs * Access to domain resources * Ability to establish network connections * Web access * Reflection * Printing * Use of the clipboard * and much more! Applications are defined by membership in something called a code group. You can define a code group in a few ways. One way is to specify a directory, the presence of a hash, the presence of a strong name, etc. When an application starts, the security system looks at the zone the application was launched from, directory the application started in, the presence of a hash, the presence of a strong name, etc. The security system gather's all of this "evidence" and determines the appropriate code group for the application. A set of permissions (called, you guessed it, a permission set) is associated with each code group. The permission set thus defines everything that the application is allowed to do. If you have the .NET Framework installed, you can launch the .NET Configuration Utility (Control Panel | Administrative Tools | Microsoft .NET Framework 1.x Configuration) and look at the different types of evidence available. You can also look at the rich set of permissions that can be used. The Code Project has a good article titled "Code Access Security from the perspective of the Developer and Administrator":http://www.codeproject.com/dotnet/casdevadmhtml.asp This article kind of inspired this post. It explains what Code Access Security is and how developers and administrators should look at CAS. I recommend that read in addition to the excellent Webcast by software legend Juval Löwy (as "previously noted":http://www.primordia.com/blog/archives/000034.html in this blog). Finally, I watched an "MSDN TV episode on CAS":http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20040212securityml/manifest.xml starring Matt Lyons.

Want to write for MSDN?

"Duncan Mackenzie":http://weblogs.asp.net/duncanma/ dug up inspiration in the form of guidelines for submitting articles for the "Microsoft Developer Network (MSDN)":http://msdn.microsoft.com/aboutmsdn/submit.asp and for "MSDN Magazine":http://msdn.microsoft.com/msdnmag/submit.aspx. I think most developers fancy the idea of getting published in some way and I'm no different. I'd be thrilled if I was able to meet the challenge once my current work project winds down. I have so many ideas it's hard to decide where to focus.

March 3, 2004

.NET Code Access Security

I just got through Juval Löwy's most excellent WebCast on .NET Code Access Security. What can I say, it's enlightening, it's profound, it's a WebCast that everyone interested in .NET should tune into. The WebCast is long, about 90 minutes, and I had to listen to it in two sessions. I have a lot of notes that I plan on posting here. The great thing about the presentation is that it didn't merely go through the motions, it was more than a drag through the CAS API. It was a comprehensive guide to what CAS is and how it can be used. Juval gave some insightful examples that just made it all clear.

February 17, 2004

Avalon, Illustrator, Visual Studio ideas...

Chris Sells pointed out how Nathan Dunlap and Jonathan Russ created Splitter Bars in Avalon. Chris went on to describe how important XAML is going to be in getting designers and coders working more efficiently. This hits a chord for me and represents something that has always excited me about Avalon. You can design something in Illustrator (or have it designed), and import it into your code. I can see a great opportunity for an Adobe Illustrator plugin that allows a fine-grain of control over the export process (XAML markup, class attributes, etc.) Or, better yet, an Illustrator plugin for Visual Studio! Amateur illustrators, but who are really developers [like me] would appreciate that side of the coin. A key feature of this integration would be, of course, the ability to allow the visual to evolve as the code evolves, as a separate entity that can be checked in and out of source control, etc. The day is coming, indeed.

February 4, 2004

More on Google Web API

I am now using a built-in feature for Movable type to access the Google Web API's. My last post seems kind of naive but it's all good. I've had some problems getting it to work right, however, so stay tuned...

Google Web API's

I just stumbled across "Google Web API's":http://www.google.com/apis/ . Looks to be some very cool stuff. I hope to play with them soon. The service is free and once you sign up, you're assigned a license key that gets you 1000 queries a day. It looks like you can issue a general search, duh, and get the results back in XML so you can traverse and process the results any way you'd like. Second, you can get a binary cached representation of any URL, so long as Google's crawlers visited the page. Third, you can get spelling corrections, just like google does, when you make a query. This is useful if you've mistyped a word or words in your query and want to know if an alternate spelling will yield the search results you were really looking for. Finally, you get a lot of options for all of these query types. Most or all of these options are available through Google's standard browser interface, but perhaps you can envision a better interface or an interface that conveniently compares results when various filters are applied. Yum.

January 7, 2004

More on web services

On a note related to my earlier rant on free web services, I just found one by accident. Jason Nadal over at weblogs.asp.net created a natural language translation web service. He announces "WinTranslate 1.0 with Source Code released" This software allows you to perform translations on your desktop. The source demonstrates how to create your own solutions. Way cool. I have to start wondering how many hidden web services are lurking around the Internet and how to find them. Any suggestions? Thanks Jason.

December 17, 2003

Musings on the Semantic Web

People who regularly develop web services will not find much of interest in this post since, in all likelihood, they have already "seen the light". I wanted to explore a few concepts here after reading an article on "Publicly available Web Services at Microsoft":http://msdn.microsoft.com/msdnmag/issues/03/12/XMLFiles/default.aspx . Tim Berners-Lee (you may recognize him as the inventor of the Web) once said that, "The Semantic Web is not a separate Web but an extension of the current one, in which information is given well-defined meaning, better enabling computers and people to work in cooperation." Before I knew what the potential for "Publicly Available Web Servers" meant, I thought he was simply referring to XML markup, where the current generation of "dumb" web pages (based on plain HTML) would be enriched with context. The potential I saw back then was simply additional context to existing pages. Say, a news site marked all of their headline copy ("President's dog is found") with special markup such as a "headline" XML element. Local features, entertainment news bites, moview reviews, etc., would all be similarly marked. The wishful part of me was hoping ads would be marked up, but we all know this will never happen. Once the markup was in place, one would be able to write a spider to troll over a site and extract the types of information they wanted. XML markup, as I originally conceived the "semantic web", is somewhat trite when seen in the light of full-blown Web Services. Still, XML markup has it's advantages. For instance, the developer may use the XML markup in ways not originally conceived by the Web Service designers. Now, more on that... I can't remember the first time I heard of the phrase "Web Service", but it was surely before the turn of the millenium. A whole industry was erected on top of the Web Service idea while I was sleeping in ActiveX land. Tools like Weblogic, J2EE, WebSphere, etc. (I've never actually used these technologies so please don't be too critical at my ignorance if you comment on this post!) Companies started using the paradigm to further the reach of their empires, for it's a very empowering technology. My point is not so much the details behind these technologies, which ones are better, nor even what they are capable of. My point is that these technologies seem to be used primarily for proprietary development. Whether a company is facilitating Intranet development or dividing their public-storefront into multiple tiers, the majority of Web Services developed seem to be largely unavailable to the general public (i.e. the average application developer with a compiler and a dream). Lots of signs are pointing to a change in this area. The MSDN article mentioned above kicked off this post so let me explore for a bit what it means to me. The MSDN article talks about four publicly available web services on their site. One service allows you to write a standalone program to get satellite images, another allows you to write your own MapQuest clone, another allows you to manage alerts, etc. The article goes on to say that Amazon and Google have started exposing some services to the public as well. That's the trend I'm hopeful for and for which I see a huge potential. As a developer, I'm used to an entire market of off-the-shelf components that I can use to build a user interface, access a new database technology, or even to access Web Services. However, power will truly be realized when a true public Web Service market is available for Internet-enabled applications. Is the state of the industry beyond infancy? I did a search on google for "Publicly available web services" and didn't find much. Am I missing something? In my head, the industry will have moved beyond infancy when there are as many public Web Service providers as their are tool and library vendors. Here are some ideas: * An application that leverages public recipe services, nutritional services, shopping services, and restaurant services to create diet plans and dining out recommendations that keep people in a healthy lifestyle. * An application that can leverage farms of computers for calculations that the application defines. You buy time on a massive matrix of machines and use them as you wish. The application can gather data on the Internet, possibly from other Web Services and use that data to provide a solution. There's lots of proprietary activity in the grid computing sector, but I personally haven't seen anything as generic and publicly available as I'm talking about here. * An application that combines "live" celestial data collected from the Hubble Space telescope, Chandra, GLAST or whatever, to create an educational space exploration program for students. Currently, this data is purchased in database form, packaged in CD-ROM, and shipped out as a snapshot. If a new celestial event is recorded in the news, the current generation of programs have no real ability to present the new data in ways the user is able to view their snapshot data. * An application that combines mortgage rate information, home availability, broker fees, neighborhood statistics, and lifestyle data on a regional or national level. Lots of small proprietary solutions exist in this area, but there is no opportunity for a third party to create a best-of-breed solution with user-defined algorithms. * Same thing for investments. A Financial Consultant might want to have a developer write her an application which combined publicly available financial data in ways that is unique to her style and not currently available anywhere else. * Etc. Many services will never appear unless there is a business model to support them. I can't see that being too huge a problem since tool and library vendors currently have a pay-for-use market that works. I'd be interested in hearing about any roadblocks in this area.

December 9, 2003

Learning C#

I was asked today to recommend a good book on C#. Harking back to my Windows and COM/ActiveX days, I always heed the words of Jeffrey Richter and Charles Petzold. These two pioneers authored such seminal works as "Advanced Windows":http://www.amazon.com/exec/obidos/tg/detail/-/1572315482/ref=pd_sim_books_3/104-4160386-0064736?v=glance&s=books and "Programming Windows":http://www.amazon.com/exec/obidos/tg/detail/-/157231995X/qid=1070973876/sr=1-1/ref=sr_1_1/104-4160386-0064736?v=glance&s=books, respectively. Recently, they've authored new works on .NET and C#. Jeffrey Richter wrote "Applied .NET Framework Programming":http://www.amazon.com/exec/obidos/tg/detail/-/0735614229/qid=1070973763/sr=1-1/ref=sr_1_1/104-4160386-0064736?v=glance&s=books" and Charles Petzold wrote "Programming Windows with C#":http://www.amazon.com/exec/obidos/ASIN/0735613702/qid=1070973876/sr=2-1/ref=sr_2_1/104-4160386-0064736. Neither of these sources is really meant to teach you C#. One suggestion would be to start at the source, Microsoft has the "C# Langauge Reference":http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cscon/html/vclrfGettingStarted_PG.asp online. Another suggestion is to look at "O'Reilly Associates":http://oreilly.com. O'Reilly has proved an excellent source of quality books for many years. I haven't read any of their books, but I'm seriously considering "Programming C#, 3rd Edition":http://www.oreilly.com/catalog/progcsharp3/index.html by Jesse Liberty and "C# in a Nutshell, 2nd Edition":http://www.oreilly.com/catalog/csharpnut2 by Peter Drayton, Ben Albahari, Ted Neward. O'Reilly has an "entire section":http://dotnet.oreilly.com/ dedicated to .NET. They also sponsor an interesting "C# Learning Lab":http://oreilly.useractive.com/courses/csharp/. Other books on C# include "C# Cookbook":http://www.oreilly.com/catalog/csharpckbk by Stephen Teilhet and Jay Hilyard, "C# Essentials 2nd Edition":http://www.oreilly.com/catalog/csharpess2 by Ben Albahari, Peter Drayton, and Brad Merrill. O'Reilly has an excellent resource for evaluating and reading books on line in their "Safari Bookshelf":http://safari.oreilly.com/ . I have an account and I recommend looking into this great service. I'd love to hear about some personal recommendations. Aside from the "Microsoft Developer Network Web Site":http://msdn.microsoft.com and Applied .NET Framework Programming, I haven't read any of these books. I'm just as curious as anyone on where to start reading next...

December 8, 2003

C# Patterns

There has been a lot of discussion on applying "Design Patterns":http://hillside.net/patterns/gang_of_four.html to the C# language. I found many useful links on the C2 Wiki entitled "CsharpPatterns":http://www.c2.com/cgi/wiki?CsharpPatterns . The point of this article is to explore how C# langauge features can be leveraged when implementing patterns. I'll start with a few examples in C++ and Java before I describe some of the advances available in C#. The "Singleton Pattern":http://www.c2.com/cgi/wiki?SingletonPattern , for instance, is commonly implemented C++ as: == class Singleton { public: Singleton() {} Singleton& getInstance() { static Singleton singleton; return singleton; } protected: Singleton() {} }; == The approach is very explicit in it's aim to create the first instance of the singleton with it's first use (a call to getInstance()). This approach could have serious problems in a multithreaded environment as two pieces of code on two different threads might be able to create two instances of the singleton. A simple workaround would be to instantiate your singletons before your threads start up... In Java, many applications choose to use the double-checked locking mechanism as illustrated by the following example: == // Broken multithreaded version // "Double-Checked Locking" idiom class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) synchronized(this) { if (helper == null) helper = new Helper(); } return helper; } // other functions and members... } == You can plainly see that Java enables synchronization with the synchronized keyword. However, the "article":http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html that the code was copied from explains how this approach is flawed. Read the article for the full discussion. Consider this almost trivial implementation of the Singleton Pattern in C#: == // .NET Singleton sealed class Singleton { private Singleton() {} public static readonly Singleton Instance = new Singleton(); } == This approach is also possible in Java, but there is a subtle difference in the two implementations. In Java, the singleton gets instantiated when the class is loaded. In C#, the singleton gets instantiated the first time the Singleton member is accessed (much like static allocation in C++), lazy instantiation. In addition, the .NET Framework guarantees the thread-safe initialization of static members. This is a common task that's finally automated and enforced by powers other than our own diligence. I welcome that. The sealed class modifier is used to prevent Singleton subclassing, something the "GoF":http://hillside.net/patterns/DPBook/GOF.html describe as dubious and prone to error. Credits: "Exploring the Singleton Design Pattern":http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/singletondespatt.asp by Mark Townsend "The C2 Wiki":http://www.c2.com/cgi/wiki

December 2, 2003

Feel the code

I decided to do all of my work using command-line tools and the "TextPad":http://www.textpad.com editor. I came into programming using command-line tools and I suppose old habits die hard. Granted, the Visual Studio .NET IDE is terrific. I plan on using it once I've felt enough code, but naked code seems the best way to learn how everything works. The first step was to get syntax highlighting for C# source working in TextPad. Although I've been aiming at naked coding without the IDE, a little lipstick goes a long way. TextPad has syntax highlighters for most languages. You can get a "C# Syntax File":http://www.textpad.com/add-ons/syna2g.html on the TextPad web site. Once you download the file, you simply need to copy the file to a Sample subdirectory off your TextPad installation directory. Launching the command-line tools from within TextPad was next on my list of required amenities. The main impetus for my effort in this area was the ability to double-click on a compiler error and be brought to the offending line of source. Yeh, my efforts are beginning to sound like I really miss the IDE. I could compile in a command-prompt, but I'm not a barbarian for pete's sake. I learned quite a bit about assemblies and the way they're loaded by the C# compiler. My initial programs were simple, so the default core assemblies were all I needed to compile and go. However, as I started requiring the various managed DirectX components, I needed to find these on my hard drive. I did find them, but they were buried deep within my C:\Windows directory. I found the ones I needed and copied them to C:\SharedAssemblies. This made my command-line simple. I added the
/lib:C:\SharedAssemblies
option to the C# compiler and I was able to refer to the managed DirectX components via a simpler syntax: /r:DirectX.Drawing (or whatever), without re-specifying the entire path. I suppose I could have utilized the GAC (Global Assembly Cache) but since the default install didn't already install these there, I got scared and punted on the issue for now.

November 27, 2003

Image Loading Goodness

Happy Thanksgiving!

I took a crack at two things this morning. First, I took some old C# code I wrote that traverses a directory structure and gets information on each file. Second, I use the System.Drawing library to get image information. Finally, I output all of the results.

The directory traversal turns out to be trivial. I implemented this as a simple recursive function as follows:

==


static int traverseFiles(FileAction action, DirectoryInfo dir)
{
int numFiles = 0;

FileInfo[] files = dir.GetFiles();
foreach (FileInfo f in files)
{
if (action.doAction(f))
{
numFiles++;
}
}

DirectoryInfo[] subdirs = dir.GetDirectories();
foreach (DirectoryInfo d in subdirs)
{
numFiles += traverseFiles(action, d);
}

return numFiles;
}


==

The FileAction argument is my simplistic shot at making the loop generic. My default implementation tries to load the file into a Bitmap() object. If this fails with a throw of System.ArgumentException, doAction() returns false. Here is the implementation of doAction().

==

public bool doAction(FileInfo file)
{
ImageInfo image = new ImageInfo();
try
{
image.Load(file.FullName);
Console.WriteLine(file.FullName + " " + image.Width + "x" + image.Height);
image.Unload();
return true;
}
catch (System.ArgumentException)
{
return false;
}
}

==

The ImageInfo class was lifted from AspHeute (AspToday, a German site I think). Thanks Christoph Wille. There is one error in their example, where the Width() wrapper returns the internal Bitmap() Height property.

The code for the sample I, uncreatively, named FindFiles.cs is available for your compiling pleasure.

Compiling can be done at the command prompt as follows:

==


csc FindFiles.cs
==