July 5th, 2014 by Mike Fulton
Categories: .NET Programming, C# Programming, Windows

I’m not ashamed to say it… C# is my favorite programming language these days.  It wasn’t always so.  In fact, I didn’t pay a lot of attention to the C# programming language when Microsoft first introduced it in 2000, mainly because I initially looked at it as being essentially Microsoft’s attempt at an alternative to Java.

It’s Really Just “Microsoft Java” Isn’t It?

Yeah. Kind of.

Well… no, not really.  But it’s easy to think that if you don’t look too close.

In the early days of C# this was a common question, and it was fueled at least in part to the fact that Java creator James Gosling referred to C# as an “imitation” of Java.  As I said above, I have to admit that’s how I thought of it initially myself.

In terms of the basic language syntax, C# is pretty darn similar to Java.  And yes, the combination of C# and the .NET framework is in some ways similar in concept to the Java language and runtime environment, albeit perhaps more in the early days than now.  However, as I’ve become more experienced with both environments over the years, I’ve become more and more aware of the differences, and they can be pretty significant. I’ve come to the conclusion that C# is no more an “imitation” of Java than Java is an imitation of C++.  They have similar design goals in many respects, and a similar heritage, so of course they’re going to be pretty similar.  But ultimately, C# and Java are really more like close cousins than twins.

The Real Microsoft Java

When Sun Microsystems released Java in 1995, it seemed like a very interesting new language and it got a lot of attention in the computer industry press as well as in the mainstream.  However, it simply didn’t seem like it applied to any of the projects I was doing at the time. I ended up writing a few goofy little applets for one of my websites, but that was about it.

Sun told the world that Java was free for everybody to use, so a few years later, Microsoft came out with their own implementation of Java called J++ which used Microsoft’s own virtual machine and runtime support. To nobody’s great surprise, Microsoft’s runtime was different from Sun’s in that it facilitated the use of Microsoft technologies like Active-X.  And Microsoft’s J/Direct framework gave the J++ code access to the underlying Windows API, bypassing Sun’s class libraries.

Microsoft wanted to position J++ as a way to use the Java language for Windows-specific development, but that idea didn’t sit very well with Sun. Their philosophy was that Java should always be as platform-independent as possible and they felt that Microsoft’s efforts, should they succeed, would end up making developers and their code dependent on Microsoft’s platform and tools.

Despite Java being free, Sun had kept a very tight grip on how it was supposed to work, and they claimed Microsoft wasn’t playing by the rules. In particular, in order to use Sun’s “Java” trademark in any fashion, all implementations were required to be 100% compatible, and Microsoft’s version of the runtime didn’t pass Sun’s Java validation tests.

Lawsuits… many lawsuits.

Scratch J++, Enter C#

At the start of 1999, the lawsuits over J++ were still going, but Microsoft was losing ground.  Java had gained popularity, but few developers were doing much with J++.  It wasn’t the big success that Microsoft had hoped.

No doubt there were also many web developers who simply agreed with Sun’s philosophy regarding cross platform compatibility, but it was thought by many that the compatibility problems were introduced deliberately because Microsoft wanted to kill the Java platform.  That first part was never established in court, but there was plenty of evidence for the second part.

Meanwhile, Microsoft had been working on a new system frameworks they were calling Next Generation Windows Services. The new frameworks which would ultimately be known as “.NET”.  You may have heard of it.

At the heart of the new system was the Common Language Runtime (CLR), a new virtual machine that was responsible for running .NET programs. One of the major design considerations of the CLR was avoiding many of the common flaws found with existing programming languages, so that meant that new compilers would be needed.  Microsoft launched the “Cool” project at the start of 1999. Cool was designed to be a managed language that would follow the general example of C and C++ syntax.  In fact, the project name stood for “C-Like Object Oriented Language”.

Because of trademark issues, the “Cool” language was later renamed to C#.

When Microsoft first started talking about the .NET framework, the name had many people thinking that it was a web-only thing, and I have to admit that was my own first impression.  The use of a virtual machine sparked comparisons with Java, and when the new C# language was added to the discussion, it looked like Microsoft was trying to redo J++ in a way that didn’t rely on Sun for anything.

In truth, however, the use of a virtual machine was a tried and true technique that Microsoft had been using for years before anybody ever heard of Java.  The development of  .NET, C# and the new Common Language Runtime (CLR) had a broader scope and much bigger goals than being a Java knock-off.  If you want to learn more, check out this interview with the creator of C#, Anders Hejlsberg, and this one too.

Switching From C++

Despite my misgiving about finding a use for C#, I bought one of the first books released to learn more about it. As I dug deeper, it became clear that the language actually had a number of significant differences from Java.

However, it wasn’t clear that the likely applications of C# were much different, and because the .NET runtime was still in beta, the whole thing just didn’t really seem like it was ready for prime time quite yet. So I waited.

At that point in time,  my Windows-based programming was mostly centered around creating and maintaining GUI-based desktop applications and command-line utilities, using Visual C++ and the Microsoft Foundation Classes (MFC).  I had been using VC++ and MFC since they were first released and was very comfortable with the environment.

However, I wasn’t completely happy with the VC++/MFC environment in some respects, which is why I had my eye out for alternatives.

The first problem was that any project I did with MFC seemed to have memory leaks.  Not necessarily hugely significant ones, but every time I ran a program under the debugger, I would get a length report at the end about memory issues.  The first few times I saw this, I spent a lot of time trying to find the cause in the debugger.  Eventually I discovered the problem would occur even with code that was generated entirely by Visual Studio, so it was apparently something with the MFC libraries and not my code.

That didn’t really make me feel better.

When C# was included in the Visual Studio 2002 release, the .NET framework was far more mature, and its usefulness was more apparent.  It had things like a regular expressions library that was missing from the standard VC++/MFC setup, to name one example. Eventually I started adding calls into the .NET framework from my C++ projects.  The VC++ interface to accessing managed code in the .NET framework was a bit clunky, but it worked.

I still hadn’t found a use for C#, however.

Finally C#

A few years later, I started doing more web-oriented programming that went beyond Flash or client-side Javascript. At first I was using mostly PHP, but eventually I ended up doing some code maintenance on a few projects that used ASP.NET. The projects themselves used Visual Basic, not C#, but it gave me a good excuse to spend some time learning about the ASP.NET environment in general, and I did most of my experimenting with C#. It took me awhile to warm up to the ASP.NET environment, but the more I used the C# language the more I liked it.

Along the way, I finally had some projects where Java was called for, because of a need for cross-platform compatibility.  Then it finally happened… a new project where I could use C#.

I had a legacy project done with Visual C++ and MFC that needed to be updated to access a SQL Server database across the local network instead of reading and writing data files.  The program needed to be able to run on multiple stations at once and share data between them.

I got it working, but I really wasn’t very happy with the way that the database stuff worked.  To be fair, some of that was due to the way the database support got bolted onto the existing project, but I didn’t really care for the way the API was setup either.

After the update was finished, the client had a brand new list full of new features they wanted to implement in the application, and they also wanted to create a new website that accessed the same database. Maintaining the existing C++ project and adding the new features was doable, but when the website idea was thrown into the mix, it didn’t look like a good idea. We decided to redo the application in C# and use ASP.NET for the website.  A lot of the existing C++ code could go into the new version without much change, but things like the database code could be drastically improved by the rewrite and then shared between the two projects.

I was much happier with the way the database connectivity worked in C# and .NET, but writing the database code in C# only for the website and maintaining that in parallel with the C++ code for the application would have been twice as much work overall.

As I started the new C# version of the application, my initial concern was making the transition from using MFC with Visual C++ for the user interface design and coding.  Especially since the client wanted the existing user interface to stay pretty much the same. The first thing I had to decide was if I should use Windows Forms or Windows Presentation Foundation (WPF) for the user interface.

Windows Forms had been around for awhile, and most of the books I’d read about C# had used it for whatever GUI samples they might have.  In fact, I’d recently bought a pretty decent book that focused entirely on it. (Windows Forms 2.0 Programming) That was a big plus.

At the time, Microsoft had only just released the first version of Windows Presentation Foundation and there weren’t a lot of books or other information about it yet.  It looked like it had more power and flexibility overall, but also like it would take more time to learn.

Since I was mostly replicating the existing MFC-based GUI I decided to go with Windows Forms.  The GUI creation tools for Windows Forms were a lot like the Java Swing GUI builder tool in the Net Beans or Eclipse IDEs, which I had recently become familiar with. It turned out that it was very easy to make the transition and it really didn’t take me very long before I was more productive than I’d ever been with MFC.

So How Is C# Different From Java?

I’m not going to make an attempt to enumerate a list here, nor try to keep track of which version of C# versus what version of Java is being discussed, and so forth.  Rather I’m going to try to cover some of the basic differences.

First, I would have to say that Java is arguably more concerned with keeping developers out of trouble at all costs than is C#.  A good example of this is the way that C# allows you to mark off a block of code as “unsafe”.

Normally in C#, using C-language style pointers and related pointer operations is not permitted, just as in Java.  Much of the time this is not an issue, but there are times when you just have no choice, so C# allows use of the unsafe keyword.  By marking a function or code block as “unsafe”, you’re permitted to use C-style pointers and pointer operations on memory.

Under the right circumstances, this allows you to do certain things much, much faster than would be the case with “safe” code. Perhaps most importantly, you don’t have to use a different compiler or programming environment to write, compile, and possibly debug what might be no more than a few lines of code. You can do all that within the main project and go back and forth between the “unsafe” code and the rest of the project pretty seamlessly.

The requirement of placing such code in an “unsafe” block means programmers are much less likely to do something wrong accidentally, but it’s a relatively easy thing to do when you need it. Not so with Java. To do something functionally like an “unsafe” block would require you to write code in another language like C, compile it, and then tell your Java project where to find it.  After all that, then your Java code could call that external function via the Java Native Interface (JNI).

It’s a lot of steps, involves extra tools, and it’s a sufficient pain in the butt that most Java programmers don’t do it unless they expect a rather substantial difference in performance or unless they simply have no other choice.

What’s Missing?

Surprisingly, there are some rather significant items for which C# and .NET languages in general don’t play quite so nicely with. It’s not always a huge problem, but there are things which require the programmer to jump through a few extra hoops to access WIN32 calls or to use 3rd party tools because Microsoft has not made them accessible directly via .NET.

DirectX, the game programming API, is perhaps the biggest example. The lack of a managed version of DirectX means that if you want to write a game for the Windows 8 app store, for example, you have to do it using Visual C++ instead of C#.  Officially, anyway.

Although there was supposed to be an official Microsoft managed version of DirectX at one point, that project seems to have disappeared.  Instead, we have a couple of open source projects like SharpDX and SlimDX which provide access to DirectX.

December 20th, 2010 by Mike Fulton
Categories: Web Design & Programming

I created my first web pages way back in 1994 when the Compuserve information service (CIS) first gave their customers a hosting option.  In mid-1996, my first website glamoursoft.com was born.

The technology for creating web pages back then was pretty basic.  You used a text editor of some kind to hand-code your HTML and then used FTP to post it on your site.  Then you looked at it with your web browser to make sure it looked the way you wanted it to look.  Eventually we got authoring tools like Microsoft FrontPage or Macromedia’s Dreamweaver which made things easier, but there were still certain tasks that were difficult simply because of the limitations of using HTML to do complex layouts and text formatting.

For example, in those early days if you wanted to change the color of a block of text, you would have to surround it by a tag, like this: this text is red.  This wasn’t too bad if you only had to do it once or twice… but imagine having to do it 20 times on a single page, and having 20 pages to worry about.  Search and replace might get the job done in some cases, but not in others.

These limitations were well known and as early as 1994, several proposals for implementing style sheets were submitted to the World Wide Web Consortium (W3C) for consideration.  Style sheets would allow you to define your layout and text formatting separately from the HTML. This ultimately resulted in the CSS Level 1 specification (recommended) being published in December 1996. The W3C’s recommendation for the CSS Level 2 specification came in late 1997, and today’s target is the not-yet-finalized CSS Level 3 specification.

My Own Personal Journey To CSS

I had used little bits and pieces of CSS in my web pages for several years before I made a major effort to embrace it.  Mostly inline styles here and there. I was mostly using the WYSIWYG editor in FrontPage to create my layouts and do most formatting, and in those days FrontPage had very limited support for CSS.  You could hand-code whatever you wanted, but the program didn’t use CSS when generating code and didn’t do much with regards to helping the user create styles or stylesheets.

Microsoft’s FrontPage had a variety of server-side extensions for various things. These were a pre-defined set of CGI handlers for doing specific tasks. This allowed FrontPage to generate code that relied on those extensions to do things that you would otherwise have to hand-code in Perl or PHP or some other server-side programming language.

Ironically, what ultimately got me on the CSS bandwagon was PHP.   Since I was using FrontPage to do everything, the only time I ever needed to worry about server-side code was a few occasions when the basic form-submission handler didn’t do what I needed.  But around 5-6 years ago, I started working on a new website project where I needed to use a database.  I was no stranger to database programming in general, but this was my first time using a database on a website.  After reading about the various options I landed on using MySQL and PHP.

I went shopping for a few books on PHP and MySQL and while I was browsing around I picked up one about CSS.  I think it was an early edition of O’Reilly’s CSS Cookbook. After flipping through the book and a few others, I realized I needed to make a bigger effort to use CSS and this new project seemed like the ideal platform. Since then it’s been CSS full speed ahead and no looking back.

CSS Isn’t Perfect

As I started to use CSS, the one thing I noticed that I was repeating myself a lot. I’d create a style that specified a certain choice of font, and then another, and then another, and each time, I’d have to type out the entire selection. For example:

h2.headline
{
   font-family: Arial, Verdana, Sans-Serif;
}
h3.headline
{
   font-family: Arial, Verdana, Sans-Serif;
}
.normaltext
{
   font-family: Arial, Verdana, Sans-Serif;
}

At first this just seemed like extra typing and since that was largely eliminated by cut and paste, I didn’t worry about it too much. But then came a time when I needed to change those styles so that some things used one font and others used something different. A simple search and replace wouldn’t work because that same font selection was used in other places. I came to realize that what I really wanted was a feature that CSS didn’t have: the ability to create my own constants or variables that could be referenced by the style definitions.

This seemed like such an obvious idea to me that at first I figured it couldn’t possibly be missing. I figured I just hadn’t read about how to do it yet. However, a few web searches later, I realized that this feature just didn’t exist.

While searching, I found a proposal called “CSS Variables” that looks promising. The example below follows the syntax it suggests.

@variables pagefonts {
headlinefont:Arial, Verdana, Sans-Serif;
bodyfont:Times New Roman, Serif
}

h2.headline
{
   font-family: pagefonts.headlinefont;
}
h3.headline
{
   font-family: pagefonts.headlinefont;
}
.normaltext
{
   font-family: pagefonts.bodyfont;
}

Apparently there are a lot of people who think such a feature should be included, but there are also others who are vehemently opposed, including one of the original creators of CSS, Bert Bos, who wrote an essay about why they were a bad idea. Read it for yourself but in my opinion, his arguments come down to “we’ve survived this far without CSS variables so they’re not really necessary” and that they’re “icky”. Those quotes are mine, and by “icky” I mean that they don’t fit in with his grand philosophy of what the web and HTML and CSS are supposed to be about.

It’s ironic and yet not surprising that this essay is presented on a horribly ugly web page. I have to wonder if this guy has ever been involved in any real life web design outside of academia.

Introducing PHP Into the CSS Equation

I know I’m not the first one to come up with this, but I wanted to talk about it anyway. Recently I was working on some custom themes for the WordPress blogging system. I had several instances of what were basically the same theme but with different color schemes and it just got to be a pain to change the colors when needed. These themes might use a total of 6 or 8 colors but there are dozens of places in the style sheet where they are defined. And it’s very easy to have one variation where you want two different places to be the same color while another variation has those in different colors. Basically it’s an ideal example of a situation where having predefined variables would help a lot.

After spending way too much time farting around with changing colors around, I decided that it was time to just dive in and figure out how to do this with PHP. The basics are pretty simple… create a php file, use the header() function to output an HTTP header that says we’re a style sheet, then define our variables. We finish up with our original style sheet, but with references to the PHP variables embedded as needed.

Here’s an example:


header("Content-type: text/css");

// All style definitions are contained in the "bella" object
// This is the name of our WordPress theme and is done
// in order to avoid namespace collisions with other PHP code.
// Don't define EVERYTHING here... just things that get repeated a lot

$bella->backgroundcolor = "#6800b9";
$bella->fonts = "Verdana, Ariel, Helvetica, Tahoma, Sans-Serif";

$bella->tagbar->backgroundcolor = "#723900";
$bella->tagbar->border = "1px solid black";
$bella->tagbar->textcolor = "#DEC9B4";
$bella->tagbar->link = "#DEC9B4";
$bella->tagbar->visitedlink = "#DEC9B4";
$bella->tagbar->hoverlink = "red";

$bella->footer->text = "#DEC9B4";
$bella->footer->link = "#DEC9B4";
$bella->footer->visitedlink = "#DEC9B4";
$bella->footer->hoverlink = "red";

// All style definitions appear as usual below
// References to PHP variables for colors, font names, etc.
// are done by escaping to PHP and outputting the desired variable
?>

div#tagbar
{
background-color: backgroundcolor?>;
text-align: left;
border: none;
padding: 0px;
font-family: fonts?>;
}

I’ve included only one style definition here to keep things short. The original file this is based on has perhaps 60 or 70 styles, and about 40% have references to at least one variable. See how the reference to font-family in the style definition accesses the variable we defined earlier? This might occur a dozen times or more within the remainder of the style definitions.

Also notice that all of our variable definitions in the PHP code at the top are setting properties of the $bella object. This is done mainly to reduce the chance of having a namespace collision with any of the other PHP code that may be used.

Also, for WordPress theme designers, note that even though this file is included as style.php there is still a style.css file contained in the theme because the comment block at the top of the file is used by WordPress to get the information about the theme which is shown on the Dashboard.

Useful, But…

This is a very useful technique but it has its drawbacks. First and perhaps most important is the fact that it requires PHP and server side processing. PHP isn’t available on all web servers. People using a shared hosting service with a Windows-based server may be out of luck. While the basic idea could probably be adapted to other technologies like Active Server Pages, that’s just more work.

And speaking of more work, another drawback is that this requires the server to do more processing to handle the PHP code in our stylesheet. It’s not a LOT of extra work, but that could be an issue for some situations.

Third, since it requires PHP, non-programmer types might have difficulties adopting this technique, or at least be reluctant due to fear of having difficulties.

In Conclusion

I do note that there are a few differences between my implementation of the basic idea and what I’ve seen described elsewhere. In particular the use of a single top-level PHP object to hold all of the definitions is not something I’ve seen elsewhere. I hope someone finds this useful.

Til next time!

Mike

PS. Happy Holidays!