Code Snippets

Multiple UDP listeners on 1 computer

If you want to have multiple apps listen for the same UDP broadcast on a single computer, setting it up in .NET is a couple of extra lines of code. If you don't do this, it will only let the first app bind to this port/address.

Two key issues here:

  1. Set the option to ReuseAddress
  2. Bind to IPAddress.Any

string stringGroupAddress = "224.168.101.200";
IPAddress groupAddress = IPAddress.Parse(stringGroupAddress);
int groupPort = 1707;

UdpClient groupSocket = new UdpClient();
groupSocket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
groupSocket.Client.Bind(new IPEndPoint(IPAddress.Any, groupPort));
groupSocket.JoinMulticastGroup(groupAddress);

May 24, 2008 | Permalink | Comments (0) | TrackBack (0)

Technorati Tags: .net, ReuseAddress, udp broadcast, UdpClient

Digg This | Save to del.icio.us

indent positioning in DOCX

Many thanks to Jialiang Ge at Microsoft for this.

  • First, to get the final state of any property (including indents), we need to follow the style hierarchy rules in §2.7.2 of the specification
    • There, it correctly states that the direct formatting (the pPr under the p element) supersedes the version in the list definition
    • Since tab stops are additive, we just gather them all up and we have the full set of tab stops
  • Now, we display the list as follows:
    • First, check the numFmt element §2.9.18 to see the format of any numbers in the list definition.
    • Next, place the text in the lvlText element §2.9.12 at the location of the final left indent.
      • If the numFmt isn’t “bullet”, we need to replace the %[1-9] syntax appropriately.
    • Now, look at the suff element §2.9.30 to see what separates the bullet from the text.
      • If it’s space or nothing, add a space or nothing.
      • If it’s tab, add a tab. (Note: this is the default if suff is not set!)
        • Then we just need to know what the next tab stop is.
        • For that, any tab stop after the end of the displayed level text is valid:
          • Tabs set with the tab element
          • Any hanging indent (as long as the doNotUseIndentAsNumberingTabStop element §2.15.3.2 is not set)
          • Default tab stops at the distances set by the defaultTabStop element §2.15.1.24
  • Finally, we justify the result – from start of the level text to end of the line. You justify now so that it’s always relative to the same tab stops.

One more thing - the use hanging tab only occurs in Word 2007 - and it's the default in 2007 which makes it sort of weird:

  • For Word xml file, the default behavior of Word 2003 and 2007 is to omit the virtual hanging tab (If Word 2007, we have an option to make Word enable the hanging tab)
  • For normal Word 2003 doc files opened in Word 2003, the virtual hanging tab is always omitted.
  • For normal Word 2003 doc files opened in Word 2007, Word 2007 will automatically set the option “Don’t use hanging indent as tab stop for bullets and numbering” selected, and omit the hanging indention.
  • For normal Word 2007 docx files opened in Word 2007, Word 2007 will use hanging indent as tab top for bullets and numbering by default.
  • For normal Word 2007 docx files opened in Word 2003, Word 2003 will omit the virtual hanging tab, and therefore, may misaligned the document. (see KB http://support.microsoft.com/kb/937936)

But there is another caveat on the virtual hanging indent - in RTF/DOC/WordML the virtual hanging indent tab stop is used - if and only if - there are no tab stops set in the list, paragraph, or styles (list/paragraph style) after the virtual position.

And one more... If there is a <w:tab val='clear'.../> then that tab is cleared and not only does not count as a tab, but clears out any parent tabs (style, list) that are at the same position.

April 13, 2008 | Permalink | Comments (0) | TrackBack (0)

Digg This | Save to del.icio.us

Elevated user rights - just say yes

It seems like everybody is recommending that users not be given admin rights on their computer. This has become such a part of the conventional wisdom that no one even questions if we should do this anymore.

Well I disagree.

Lets take a look at how we use our cars. Do they refuse to drive if our seat-belts are not fastened? After all, it's dangerous to drive unbuckled? Are most cars designed to carry a load of lumber? Yet we all at one time or another do have to bring some stuff home from Home Depot sticking out of the trunk. We use our cars in ways they were not intended - we have admin rights.

Now why do users need admin rights? Well reason 1 is so they can install software. Yes they will sometimes install something that is a problem or mucks up the machine. But other times they will install something that makes them a lot more efficient. Yet the approval process to install something at many companies is, in practice, so onerous that people will not even try to get approval to install software.

Second is program capability. Restricted rights stop programs from performing certain tasks, communicating with other programs, etc. Again, the user with restricted rights finds that they can not use the full functionality of a program.

This restricted approach has reached it's nadir with Vista where the default security makes it impossible to do anything and the new IE security which makes it impossible to visit any website. Guys, if I turn the computer off, encase it in a block of cement, and bury it then yes it's secure. It's also unusable.

A lot of this in my opinion is due to the laziness of the programmers involved. Much easier to say no setup programs than to come up with a reasonable list of allowable actions for a setup program. For example, if I am running setuproadrunner.exe from Acme Software then HKLM\Software\Acme Software should be writable. And it is very legit to require a setup program be digitally signed to allow this activity.

And in many cases, we should ask the user a different question. Don't say wrtzyx.exe is accessing port 43 - allow? Instead it should be "the program RoadRunner is trying to read from the database coyote - is this expected?"

Yes it's much harder to implement the above. But the computer is supposed to help us. It's not supposed to be that we change our activity to make the programmer's life easier.

And with that said, yes all programs should be written to run with least privileges. We went to a lot of effort to get the Windward programs to run with Vista in it's totally locked down mode.

April 12, 2008 | Permalink | Comments (0) | TrackBack (0)

Digg This | Save to del.icio.us

BufferedImage to bitmap using JAI IIO

And here we have converting in the other direction, from a BufferedImage to the bitmap image (the byte array if you want to write the bitmap to a file).

/**
  * Create a png bitmap.
  *
  * @param image   The image to render.
  * @param resolution The DPI of the image.
  * @param format The format to convert to.
  * @return A file image of the bitmap.
  */
public static byte [] imageToBitmap(BufferedImage image, float resolution, String format) throws IOException {

  // define PNG resoultion, etc.
  PNGMetadata png = new PNGMetadata();
  int res = (int) Math.ceil(resolution / 0.0254f);
  png.pHYs_pixelsPerUnitXAxis = res;
  png.pHYs_pixelsPerUnitYAxis = res;
  png.pHYs_unitSpecifier = 1;
  png.pHYs_present = true;

  IIOImage iioImage = new IIOImage(image, null, png);

  // Save as PNG
  ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName(format).next();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  ImageOutputStream ios = ImageIO.createImageOutputStream(out);
  writer.setOutput(ios);

  writer.write(iioImage);
  writer.dispose();
  return out.toByteArray();
}

Do you find this useful? If so please check out Windward Reports.

December 08, 2007 | Permalink | Comments (0) | TrackBack (0)

Technorati Tags: bitmap, BufferedImage, convert, IIO, ImageIO, JAI, java

Digg This | Save to del.icio.us

Bitmap to BufferedImage using JAI IIO

Using the Java JAI IIO library to convert from a bitmap image (the byte array of a bitmap file) to a BufferedImage, do the following:

/**
  * Convert a bitmap to an Image object
  *
  * @param data The bitmap file.
  * @param format The format the data is in.
  * @return The Image of this data.
  * @throws IOException thrown if a problem reading the data or the format is wrong.
  */

public static BufferedImage bitmapToImage(byte [] data, String format) throws IOException {
  ByteArrayInputStream inb = new ByteArrayInputStream(data);
  ImageReader rdr = (ImageReader) ImageIO.getImageReadersByFormatName(format).next();
  ImageInputStream imageInput = ImageIO.createImageInputStream(inb);
  rdr.setInput(imageInput);
  return rdr.read(0);
}

Do you find this useful? If so please check out Windward Reports.

December 08, 2007 | Permalink | Comments (0) | TrackBack (0)

Technorati Tags: bitmap, BufferedImage, convert, IIO, ImageIO, JAI, java

Digg This | Save to del.icio.us

ImageIO on AIX - turn the cache off!

There is a bug in the AIX file system that leads to very slow Java ImageIO operations on AIX. They will only occur if you call the ImageIO methods from multiple threads.

To avoid the bug, call ImageIO.setUseCache(false); before making any ImageIO calls. And testing on Windows and Linux setting the cache off is no slower so you can set this for all platforms as far as I can tell.

Do you find this useful? If so please check out Windward Reports.

December 08, 2007 | Permalink | Comments (0) | TrackBack (0)

Technorati Tags: AIX, cache, ImageIO, java

Digg This | Save to del.icio.us

Top 7 Problems with the iPhone

Ok, I love my iPhone but it's not perfect. So without further ado, here is my top 7 (I tried to come up with 10 but couldn't) list of imperfections with it.

7. Has a problem with Cyrillic letters for songs.
6. No album art for any of my CDs - not one. And they are all top selling European (mainly Russian) pop music CDs.
5. Out of all the Eurovision 2007 final and semi-final songs - one, that's right, just one is available in the iTunes store.
4. Can't share between my home and work iTunes. It's fine if you want to limit how many computers I can copy my music to but almost everyone has home and work.
3. Having to switch between a letter and number keyboard (entering a wireless security key is constant switching).
2. You cannot touch type with a touch sensitive keypad. (I think the trade off of getting a large screen is worth it - but typing is still a pain.)
1. It does not sync with Exchange

What are your pet peeves (please add as comments)?

August 26, 2007 | Permalink | Comments (0) | TrackBack (0)

Technorati Tags: iphone, ipod, review, top 10

Digg This | Save to del.icio.us

Sidekick vs Treo vs iPhone

I was a Sidekick user for 4 years (Sidekick I, then Sidekick II). I recently decided to replace my Sidekick and first tried a Treo 750w then went to an iPhone. So here is my review of the trade-offs of each.

Sidekick:
The Sidekick has the best physical design. The keypad is wider than any other and has a 4th row with the number keys. Having physical keys makes typing a lot easier and allows for touch typing. You can feel if your thumb is between keys and then look down. As for having the number row, entering a hex code, like a wireless security key, is a breeze with the sidekick and a giant PITA with the Treo and iPhone where every 2 - 3 characters you have to switch keys.

The software interface in the sidekick is a close second to the iPhone and blows the Treo Windows Mobile system away. You have everything you need and each app owns the screen and is designed precisely for the Sidekick's screen. And it has everything you will need from email to web browser to calendar.

The sidekick's synchronization is superior to the iPhone's. But clearly inferior to the Treo which can sync with Exchange. With the sidekick you install a synchronization program on your PC and run it once or more a day and it synchronizes with Outlook (Outlook must be running). The data goes from Outlook to Intellisync to T-Mobile's server to the sidekick. The sidekick is never connected to the PC which is great.

So what's the downside of the sidekick? It's that this whole system just doesn't work a lot of the time. I would guess 75% of the time web browsing does not work. About 10% of the time IM does not work and it is always dropping the IM connection so others can never get you. The email and calendar synchronization usually works but there was one time where it was not working for 6 weeks straight.

And their tech support is awful. For sidekick specific support you usually have to get forwarded through 3 levels of support, with a 5 - 10 minute wait time at each level. And then many times they either drop the phone call or can't answer the question. And forget email questions - they answer them about 2 months later (this is not an exaggeration). Basically you are on your own.

The mail and calendar synchronization stopped working on mine and after investing an hour on the support lines with no answers, when the support call dropped (that's the problem with making a call on T-Mobile - the calls drop), I decided that it was time to move on.

So great hardware, good software on the phone, horrible support and back-end software. For a business user depending on synchronizing your calendar and contacts it can't be depended on.

Treo:
So the first place I went was Verizon. My wife and daughters have Verizon phones and are very happy with them and the ActiveSync capability in Windows Mobile to sync with my Exchange mail and contacts was compelling.

So lets start with Windows ActiveSync. This is what is used to synchronize your Treo with Exchange pushing mail and updates in both directions. This includes mail you send from the Treo being placed in your sent folder on Exchange. Oh, what a wonderful world.

Not so fast. You install everything following some very long instructions. And if everything works, great. But if it doesn't work you get error codes like 80072F0D. Gee, that's informative. It be just as useful to have an error of "something didn't work." (The Exchange group at Microsoft seems to have a motto of no error code is too obtuse.)

Reading the web about this specific error code half the people had a self-generated certificate and switched to a purchased one. The other half had a purchased certificate and switched to a self-generated one. I took this to mean that if one approach didn't work, try the other and maybe that one would go right.

I just switched to no SSL and got error code 85010014 for which there is no information. So after 8 hours of hitting my head bloody pounding it against a brick wall, I surrendered. Exchange's hiding of what the actual problem is beat me.

But during that time I used the Treo for phone calls, web browsing, and played with the messaging and calendar. So I was using it somewhat for a couple of days.

And my conclusion is it's too small. The keyboard is too narrow and does not have that all important 4th row of numbers. And the screen is small and Windows Mobile wastes screen real estate making the usable part even smaller. Moving around from app to app is also a challenge. The Windows desktop is great on a regular computer but it's a lousy UI for a 2"x2" screen.

It's web browsing is also slow compared to the iPhone. But it is a dream compared to the sidekick. Everything worked, web pages downloaded, the connection was always good. And calls to Verizon support were answered quickly and I never had a dropped call.

Also kudos to Verizon for their 30 day try it policy. I took the phone back after 5 days and they were very polite, no problems on returning it, and actually told me they get a lot of them back because people cannot get the phone to sync with Exchange. (Probably the best gauge of how difficult it is to connect a Treo to Exchange, Verizon provides no support for doing so. They would rather lose you as a customer than go through the expense of getting a phone connected).

Blackberry:
I did not bother with a blackberry because I figured if I can't get ActiveSync to work, might as well go with an iPhone.

iPhone:
Ok, I am no Apple fan. I use iTunes with my iPod and find it slow, clunk, and with a so-so UI. I've always used PCs and really like how Windows works. But it's the new thing and a number of friends were raving about the iPhone. So I tried it next.

So I download iTunes, connect up the iPhone, and get ready to go through a couple of hours of pain. The sidekick can't do this well. The Treo can't do it at all. All I want is after a couple of hours, I finally have it working.

So it pops up, asks me for my billing info, asks me what it wants synced, and then takes 10 minutes syncing everything. I actually spent 5 minutes verifying that everything worked. It's not supposed to be painless. This was absolutely amazing.

The iPhone uses a wireless connection if one is available. And you think - that's cool. But you don't realize what that really means. You click on a YouTube video and if you are using wireless, it starts playing. And the resolution is stunning. You can't get that if you use the cellular data network. Instant response is a gigantic difference over wait a minute. Absolutely gigantic.

All of the software is laid out well, is easy to get to, and is designed perfectly for the form factor of the iPhone. Apple knows how to make something so easy to use it just happens.

This is not to say it is perfect. The keypad is just part of the touchscreen that slides up as needed and is gone when not needed. It's a good trade-off because you get all the screen for the web, videos, etc. But it is a trade-off and a touch screen keyboard means you have to watch your typing. And no 4th row of numbers - they have the same stupid toggle which keyboard mode.

Email is via IMAP and calendar and contacts is synced with iTunes. No ActiveSync (not that that works anyways). Even worse, you have to connect the iPhone to the computer to sync it. The iPhone has the worst sync system of the three. And iTunes is slow and clunky. It works but it's slow and clunky.

Recommendation:
So which do I recommend? Well if you have a large enough IT department that they can put in the hours to get the Treo talking to Exchange, I would consider that. Because true synchronization between the Treo and Exchange is a really useful idea.

But if you don't have the IT resources to get it working. Or you do but the synchronization is not key, then get the iPhone. It's easily the best system aside from the synchronization issue. And the wireless speed for data makes it worlds better for web browsing, etc.

As to the sidekick, it's not dependable.

ps:
Why, why, why do the phones do the display **** when entering passwords? Especially for a wireless key? Do you know how most people get a wireless key, it's on a piece of paper passed to everyone new in the room. It's not a secret to others in the room. Show the password so you know you didn't mis-type on the itty-bitty keypad.

Do you find this useful? If so please check out Windward Reports.

August 08, 2007 | Permalink | Comments (3) | TrackBack (0)

Technorati Tags: iphone, review, sidekick, treo

Digg This | Save to del.icio.us

always do "using (Dialog dlg = new Dialog()" with ShowDialog

If you don't do this dlg.Dispose() will not be called until when your application exits - which is very bad.

There is a great discussion of it here. I've tested and found the same thing - the Dispose method is not called until either it is called explicitly or the app exits. Closing a dialog created with ShowDialog does not call dispose.

Do you find this useful? If so please check out Windward Reports.

June 11, 2007 | Permalink | Comments (0) | TrackBack (0)

Digg This | Save to del.icio.us

Passing an enumerated list to a PropertyBag for a PropertyGrid

I've been using the PropertyBag class to build up a set of properties to pass to a PropertyGrid control. However, it required passing a type for each enum to list the strings and that meant creating a StringTypeConverter derived class for each enum - which is a problem if you will have N enums.

Download PropertyBag.cs is derived from the original but includes a property constructor that takes an array of string rather than a type and displays those strings as the enum choices. I made a couple of other small edits to the original code but otherwise it's the original PropertyBag.

Answer

To set a default property you do it like for any other property - you just do:
PropertyTable props = ...
props["name"] = value;

Do you find this useful? If so please check out Windward Reports.

May 29, 2007 | Permalink | Comments (2) | TrackBack (0)

Technorati Tags: enum, enumerated list, PropertyBag, PropertyGrid

Digg This | Save to del.icio.us

« | »
My Photo

About

Programmer's Tools

  • My Blog
  • My Toolbox

Windward Reports

  • Java Reports
  • .NET Reports
  • Cubicle War

Recent Posts

  • I've moved
  • Windward Arrow for SharePoint
  • I hate Camtasia
  • Verizon & Blackberry == awful squared
  • Got an opinion on charting UIs?
  • XmlZipResolver - an XmlUrlResolver for files in a zip file
  • Opening an XML file that requires a username & password
  • Get all types a COM object implements
  • Great Windows programming resource
  • Named Pipes in .NET

My Blogs

  • Programming Thoughts
  • Liberal & Loving It
  • Management Thoughts
  • Random Thoughts
  • My web site
  • java reports
  • .net reports
  • My YouTube Page
  • A World of Music

Archives

  • February 2010
  • October 2009
  • July 2009
  • May 2009
  • April 2009
  • February 2009
  • December 2008
  • May 2008
  • April 2008
  • December 2007

More...

Subscribe to this blog's feed
Add me to your TypePad People list