Monthly Archives: April 2011

HTMLWriter

Sometimes you might need to use a technology in a way it wasn’t intended because it has some features that you find useful. Displaying html in a web browser control inside a Winforms application can be useful because it provides built-in support things like printing and exporting data.

There are multiple ways to generate html source code – some ways are not recommended like concatenating strings or even hard-coding text inside the application. A few years ago I came across a library to write RTF (Rich Text Format) that gave me an idea how to write a small little utility class to create html fragments or even documents.

The main goal of the library is to make it easy to create html fragments without much code from the calling application but allow it to be flexible enough to be extended if needed. Internally it use a StringBuilder so it creates a mutable string that makes it much more efficient in handling larger fragments of text/html.

The heart of the library/class is one method:

private void AppendInternal(string value)
{

if (!string.IsNullOrEmpty(value))

{

sbHtmlContent.Append(value);

}

}

Then the rest of the methods follow the pattern – call the AppendInternal in various ways to generate the final html e.g.

public HTMLWriter AppendRAW(string tagName)
{

this.AppendInternal(tagName);
return this;

}

One additional thing you might notice is that the method returns a reference to the containing class. This is a useful  trick so you can queue up methods to group them together if they all contribute to one common goal.

Then you have to remember that html (like xml and other markup languages) require (most) elements/tags to have corresponding closing tags. To make it easier to ‘remember’ what html tag needs to be closed there is a stack object that stores the appended tags that get ‘pop’ of the stack when the AppendTagEnd() method gets called.

There is also a CustomAttribute helper class to help add custom attributes for some html tag that requires it. Think about the href attribute for the anchor (<a >) tag or colspan/rowspan attributes for the td tag.

To illustrate these points look at the following methods:

public HTMLWriter AppendTagStart(string tagName, string className, params CustomAttribute[] customAttributes)
{

this.AppendInternal(string.Format(“<{0}”, tagName));
if (className.Length > 0)

this.AppendInternal(string.Format(” class=\”{0}\””, className));

foreach (CustomAttribute customAttribute in customAttributes)
{

this.AppendInternal(” ” + customAttribute.ToString());

}
this.AppendInternal(“>”);
tags.Push(tagName);
return this;

}

public HTMLWriter AppendTagEnd()
{

if (tags.Count > 0)
{

string tagName = tags.Pop();
this.AppendInternal(“</” + tagName + “>”);

}
return this;

}

Now using these methods to create – say the anchor tag, would look like this:

public HTMLWriter AppendAnchorStart(string url, string className, string title)
{

return AppendTagStart(“a”, className,
new CustomAttribute(“href”, url),
new CustomAttribute(“title”, title);

}

If you want to create full html documents it also provides support for stylesheets. This is handled similarly, but separately with a StringBuilder class that is combined when you call the final ToString() method to retrieve the whole html document.

As a final example look at the following piece of code to create a table:

HTMLWriter h = new HTMLWriter(“Test”);

h.AppendTableStart(“main”, new CustomAttribute(“border”, “0”))
.AppendTableRowStart()
.AppendTableHeaderCellStart()
.AppendRAW(“Name”)
.AppendTagEnd()
.AppendTableHeaderCellStart()
.AppendRAW(“Surname”)
.AppendTagEnd()
.AppendTagEnd()
.AppendTableRowStart()
.AppendTableCellStart(“”, new CustomAttribute(“colspan”, “2”))
.AppendRAW(“test2”)
.AppendTagEnd()
.AppendTagEnd()
.AppendTagEnd();

The output looks like this:

<table class=”main” border=”0″><tr><th>Name</th><th>Surname</th></tr><tr><td colspan=”2″>test2</td></tr></table>

Finally (for now) there is an extension to the class (since it is a partial class) that can handle DataTable objects (like in DataSets). It makes it possible to simply pass a DataTable object to the library and it generates a complete html table with column names, rows and even alternating background colors for rows.

If you like you can download and try the library (at your own risk 😉 ). Find it here.

Update: using this library you can reference only the Framework Client Profile oppose to the full .Net framework. This can help to reduce the total download/install size.

Update: if you need to Normalize html nicely you can use another library you can find at http://systemhtml.codeplex.com.

Fading Windows form in and out

I’ve been using a little class for years to make Windows Forms fade in and out using the built-in OS features. This makes it far more powerful than just playing with the opacity. Using it is also very easy as it is a self contained class that already inherits from System.Windows.Forms.Form. This means all you have to do to use it is inherit from it and everything else is done for you already.

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace HenIT.Windows.Forms
{

public class FadeForm : Form
{

#region Constants
const int AW_HIDE = 0X10000;
const int AW_ACTIVATE = 0X20000;
const int AW_HOR_POSITIVE = 0X1;
const int AW_HOR_NEGATIVE = 0X2;
const int AW_SLIDE = 0X40000;
const int AW_BLEND = 0X80000;
const int FADEINTIMEMS = 500;
const int FADEOUTMS = 250;
#endregion

[DllImport(“user32.dll”, CharSet = CharSet.Auto)]
private static extern int AnimateWindow
(IntPtr hwand, int dwTime, int dwFlags);

private bool _UseSlideAnimation;
public FadeForm() : this(false) { }
public FadeForm(bool useSlideAnimation)
{

_UseSlideAnimation = useSlideAnimation;

}

#region Overrides
protected override void OnLoad(EventArgs e)
{

base.OnLoad(e);
AnimateWindow(this.Handle, FADEINTIMEMS, AW_ACTIVATE | (_UseSlideAnimation ?
AW_HOR_POSITIVE | AW_SLIDE : AW_BLEND));
this.Refresh();

}

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{

base.OnClosing(e);
if (e.Cancel == false)
{

AnimateWindow(this.Handle, FADEOUTMS, AW_HIDE | (_UseSlideAnimation ?
AW_HOR_NEGATIVE | AW_SLIDE : AW_BLEND));

}

}

#endregion

}

}

And that is it!

Thoughts on flying, planes and speed…

Definition of flying: Falling in style without hitting the ground.

Definition of a good landing is when you can still walk away from the plane.

Definition of an excellent landing is when you can re-use the plane again.

And the definition of a superb landing is when you can re-use the plane for flying again.

It’s not falling that kills you… it’s hitting the ground that does. Similarly, speed doesn’t kill, it’s the rapid deacceleration when you hit another object that does. Ask anyone who has experienced that (and still lives)

Water is all soft and wet until you hit it at high speed.

Why is it that whenever your parachute fails and there’s a heap of hay there’s always a fork in it!

Nothing travels faster than light… with the possible exception of bad news.

Another use for .Net Generics

Some time ago I created a simple utility class to quickly serialize and deserialize objects at run-time. It worked ok but had one drawback (probably more but I’m dealing with one specific one here). Because it deals with objects at run time and before the advent of generics you had to pass the object type as a parameter around – possibly I could have kept it dealing with only objects but I was trying to make the calling code easier to maintain and read.

The old methods looked something like this:

static class SerializeUtils
{

public static string SerializeXML(object classToSerialize)
{

XmlSerializer ser = new XmlSerializer(classToSerialize.GetType());
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
ser.Serialize(writer, classToSerialize);
return sb.ToString();

}
public static object DeserializeXML(string serializedObject, System.Type typeOfObject)
{

XmlSerializer ser = new XmlSerializer(typeOfObject);
MemoryStream input = null;
object result = null;
input = new MemoryStream(System.Text.Encoding.Unicode.GetBytes(serializedObject));
input.Position = 0;
result = ser.Deserialize(input);
return result;

}

}

But then at one stage I thought why must the object type be passed as a parameter plus the calling code still has to cast it again. Thankfully Generics make all that easier. Look at this:

public static class SerializationUtils
{

public static string SerializeToXML<T>(T classToSerialize) where T : class
{

XmlSerializer ser = new XmlSerializer(typeof(T));
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
ser.Serialize(writer, classToSerialize);
return sb.ToString();

}

public static T DeserializeXML<T>(string serializedObject) where T : class
{

XmlSerializer ser = new XmlSerializer(typeof(T));
MemoryStream input = null;
T result = null;
input = new MemoryStream(System.Text.Encoding.Unicode.GetBytes(serializedObject));
input.Position = 0;
result = (T)ser.Deserialize(input);

return result;

}

}

In a way the methods still take the type as a ‘parameter’ but this is something the compiler can use at compile time as well – i.e. to make sure the input and return types are actually of the proper class. With the Deserialized method the calling code actually get a fully casted object back.

There you have it.

Who shot first? Han or Greedo

This is a Star Wars universe ‘issue’ – mostly for the ‘fanboys’ as they’re called.

For years now there has been a debate whether Han Solo or Greedo shot first. In the original movie Greedo apparently shot first but in the remastered versions of the movie Mr Lucas had it changed so Han shot first. For the fanboys this is apparently a huge issue with endless debates. Only they will know why…

My take: who cares who shot first. Han won, get over it! If Greedo won the movie(s) would have been a whole lot shorter… 😉

The future and Microsoft

The following is purely an opinion so don’t shoot or quote me – since my opinion apparently doesn’t matter much to most people anyway.

Reading an article about the financial states of Microsoft compared to Apple and from what I’ve seen and experiences in the last couple of years it seems to me things are not going so good for them lately. Sure, most companies, even big ones have their ups and downs but once a trend begins it is hard for any company to turn it around – especially for a big company. Windows and Office traditionally have been the big cash cows for them but that market is not going to last forever – or it will morph into other more diverse markets. There was a time MS was at the leading edge (even cutting) at some time but lately they are only playing catch-up mostly. Perhaps the whole ‘security’ fiasco that plagued the early Windows XP years distracted them from real innovation – or the stupid anti-trust case in which they actually were ‘wrong’…

The only ‘cool’ thing to come out of MS recently is Kinect and that has a very small and ‘ninch’ market – in a market already controlled by competitors. They don’t lead in the market with technology anymore – i.e. with big trendy setting things. Sure, they have a cool research lab that comes up with things that sounds very nice but rarely do these things get to an actual market (thinking about things like the optical table here). Perhaps it is the perception of the ‘people’ that MS isn’t producing anything cool anymore – but seeing Apple is the same or even bigger age than them and doing very well with keeping being ‘in’ that is not an excuse. As far as Kinect goes, they launched it into a small already saturated market instead of the ‘big’ market that they already control (PC market). What if they rather launched it into the PC gaming market – a market that was once much bigger but then they went and neglect that too… I can’t help thinking about some military wisdom here – if you choose to fight an opponent do it in an area that you control – not somewhere where ‘he’ has the upper hand. Sure, in the movies the heros can take on the bad guys at the things they are best at and win, but this is real life! Is MS living in some kind of fairy tail world or something 😉

Then there is the whole ‘thing’ around the leader of the MS pack. I’m sure Mr Balmer is good at what he does (marketing) – but being CEO of a big software company wasn’t it. I’m not saying he is some idiot that does not have a clue, rather that his skills would suit another role better. His notorious outbursts with chairs and so on isn’t exactly helping making the company’s image better. Mr Gates wasn’t perfect but he notoriously and ferociously pursued things that he set his mind to – even to the point of hurting his friends/partners apparently. Yes, times were a bit different then – a smaller less mature market and so on, but back then MS was kicking butt!

Sometimes MS is its own worst enemy as well. The whole backwards compatibility thing was/is a big innovation killer. Apple seems to have a different strategy which is working for them. The issue should not be functionality tied to software/OS versions – in other words, software may be compatible with only one specific OS but if you want to do the same kind of thing on the next version of the OS the new software must have the same or better functionality even though it may not be compatible with the old OS. Yes, in theory it sounds easy but in practice its not. Perhaps they should rewrite Windows/Office keeping only the knowledge and list of requirements of the previous version. It could shut up the security freaks that keeps on complaining Windows is ‘insecure’. But, ‘us’ developers would like to shoot them for breaking all our programs 😉 Just an idea…

If I could add my 2c to suggest something they should try – do new and exciting things in the market that you are already good at and then perhaps even steer it in a new and exciting direction! Think along the lines of new exciting tools/toys for the PC gaming world.

So am I right or am I right? (or wrong at being wrong… 😉 )

IT salaries in SA

I saw an article today about IT salaries in SA on mybroadband.

From the comments made in the article it sounds like there should be more opportunities around and companies should be looking around for more people (in IT) but it’s not quite happening.

The real interesting part is the table that list min/max and average salaries for various fields in IT.

Work and social media

The following is just an opinion about people using online social media complaining about their employer and trying to get sympathy. At work today we got one of those official emails stating that people that use these social media to complain or insult or even discredit them are violating company policies. Someone obviously went over the ‘lines’ again somewhere.

Well, ‘me’ thinks an idiot that does things like these deserve to get what is coming to them. If you’re really that upset about your employer then rather quit or talk/write to your manager/boss directly. The only thing they achieve is to get everyone else’s actions labeled by the company as suspicious or blocked – even if we don’t misuse things. Why is it always a few stupid people that spoils it for everyone else?

I suppose idiots must also make a living somewhere – just wish it was somewhere else!

42

I might have (one of the..) answer… I mean the question to the answer to the ultimate question of life, the universe and everything!

If you’re thinking along the line of primes (seeing the answer is a number…42) then there are a few possibilities like:

1 + 41
5 + 37
11 + 31
13 + 29
19 + 23

Interesting that there are 5 possibilities (well strictly 1 isn’t a prime number by itself) – as 5 itself is a prime number. There are 13 prime numbers smaller than 42 – again 13 is a prime. if you add all the prime numbers (plus the 1 that isn’t really one) up to 13 then you get… yep you can guess, 42 – that is 7 numbers.

All in the name of good fun. I’m sure Mr Adams didn’t have any very deep and comprehensive study into the ‘answer’ to that ultimate question. For those that do not understand the ‘todo’ of the whole story, the irony is really in the simplicity of the ‘answer’ instead of ‘what’ the answer is. Mr Adams loved doing things differently – but not always right.

The Cicada Principle

If you have never heard of this then you’re not alone but after reading this you would understand it a bit better. Basically its about little insects called cicadas that lay their eggs so they hatch only every 7, 13 or 17 years depending on the specific species. In case you know something basic about math you’ll also notice those numbers also happen to be prime numbers…. apparently it helps them avoid their predators hatching every 2 ,3 or 4 years not to match up with their years exactly – or something like that.

Anyway, apparently the same principle makes for good web page (or any large surface) background making algorithm by using simple small colors and have them repeat in such a way that it still looks ‘naturally’.

Read more here..