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

Karl Seguin

.NET From Ottawa, Ontario - http://twitter.com/karlseguin/

March 2006 - Posts

  • Language Proficiency - C# or VB.NET?

    In a somewhat unrelated comment to Sahil's really-should-remember-but-gonna-forget-and-get-bit-in-the-ass post, Scriptor pointed out how little VB is used here at CodeBetter. While I'm too new at CodeBetter to really comment to that specific charge, I've always have something to say about the VB.NET vs. C# thing.

    When it comes to writing .NET material, it obviously depends where your material is going to end up. Although blogs have become leading sources of technical information, it's unreasonable to ask bloggers to use more than one language (I know that's not what you were getting at Scriptor). When you are writing an online publication however, any downloadable samples should be available in both languages (unless the example is extremely trivial). If you only make it available in one language, someone will ask for it in the other (sooner rather than later). What about code samples within the article? Well, every time I wrote an article for MSDN, I was gently encouraged to make sure the samples were available in BOTH languages.  Personally I find this makes articles too cluttered and is really unnecessary (though I did do it at first). I strongly believe that the best approach for article samples is to use C# and VB.NET interchangeably. I haven't written a book, but I'd think that's the best solution there also (unless you want to sell a C# and VB.NET version, which I consider lame in most cases).

    Now, this really leads to my main point. Every VB.NET developer should be able to easily read C#. Every C# developer should be able to easily read VB.NET. First, it's bound to come in handy more than once. Second, it's nice to have on your resume or in interview tests. Third, neither language is the dark side - stop being such a nerd. Forth, it should take a very small amount of time to get up to speed with the new syntax. Fifth, if everyone writes their articles/books the way I think they should (see above), you won't have a choice. Spend 2 hours every Friday with Snippet Compiler and play around in the other language.

    Although you should be able to easily read both languages, what should you write real code in? Whichever you feel more comfortable in. If people are telling you that one's better than the other, or that VB.NET sucks, then there's a good chance they aren't very good programmers (ignorance isn't a good quality to have in this business). VB.NET isn't more productive, and C# isn't more powerful. A good programmer will write good code in either language. A bad programmer will write bad code in either language. Part of me wants to say VB.NET makes it easily to be sloppy, for example one could turn off option strict or use on error resume next, but a bad programmer in C# could just as easily only use System.Object and swallow exceptions. I do wish VB.NET had a 3rd "option really really strict" option that disabled a handful of more "features", but in the end it really is the person and not the language.
  • log4net's good

    I know I'm about 4 years behind, but figuring others might be as well, I just wanted to say that I'm using log4net religiously in my applications. I'd say it "rocks", but a better explanation would be to say it does what I want it to do with little effort.  If you are using a different logging library, such as Microsoft's Logging and Instrumentation Application Block, and it's doing what you need of it, then don't switch. But if you're using a library that's not working out for you, or aren't at all, go visit the log4net homepage right now.

    log4net is really flexible, and let's you output the result of warnings and errors any number of ways (called appenders). It can also be configured a number of different ways. It can be a little too much at first (and I don't find the documentation that great for someone trying to get started with it), but it's well worth the small initial investment.

    For example, I use log4net in my AMF.NET project (Flash .NET Remoting). If an exception occurs in any of the three main steps, I log the exception with log4net. Anyone who downloads AMF.NET can configure log4net to work in their environment. Maybe they want the log output to be sent to MS SQL, or to an XML file, or sent by email, or just ignored. Whatever they want, they can simply configure it in their web.config and voila. You can even set it up to log info and warning level messages to MS SQL, but have error and fatal level messages emailed.

    There are only a handful of things I wish they'd add (some of these are probably already there, and I just haven't figured them out).  First, I wish there was some type of RSS appender. Secondly it'd be nice if I could point to other configuration sections  for some of the data (ie, I hate having to store the same connectionString in multiple places of my web.config). Although I got it up and running quickly enough, I still think a more straightforward guide would be useful - maybe a future project for me :)
  • Eschewing Design Patterns

    I'm a pretty big fan of Paul Vick's blogging.  You don't need to be a VB.NET programmer to benefit from subscribing to his feed. His latest gem is a perfect example of an insightful blog entry.

    A while ago, Paul posted, what I thought was, a very funny and accurate post about "refactoring". Long story short, "refactoring" is really just "cleaning up your code".

    Along those lines, today I've officially stopped using "Design Patterns" in favor of "tricks".

    That's all.
  • Judging a book by it's cover - or - Are Java Developers Bad Developers?

    Building on Peter's entry about RADRace, I wanted to throw out my own experience with those "serious" guys (aka, Java Developers)

    First, I want to preface this post with an honest statement. I'm asking a genuine question. I want to know if I was just dealing with a few bad apples, or if the hole barrel sticks of rot. I have no doubt whatsoever that you could easily round up a bunch of bad .NET programmers.

    Over a period of time, I had the opportunity to work with an outside consulting agency that provided a number of ".NET experts" to our development effort. These .NET Experts had strong Java background but very little .NET experience (.NET was relatively new then).  Truth be told, they did most of the work and by the time I was brought in, everything was already set in stone (and sinking very quickly) - so maybe I'm just armchair quarterbacking. I've labeled the project a failure many times and have heard that the existing management team is throwing it all out (this isn't where I'm currently working obviously).

    Now, there's no doubt that it was a very challenging project, with very difficult clients, users and timelines. Nonetheless, I was appalled at the type of code I saw. We'll set aside the SQL injection vulnerabilities, the lack of viewstate optimization and the fact that all the html was generated dynamically in codebehind (new HtmlTable(), table.Add(new Cell()...).

    The developers treated the Database like a dumb filling cabinet - never coming close to taking advantage of what it had to offer (and I'm not just talking about indexes, udfs and stored procedures, but if you're curious, they didn't exist either). Much of the data was stored in a meta-like repository (at an extreme, think of having a single table with two columns "name" and "value").  Calculations were never cached (either in memory or in the database), but always done on the fly, in the business layer.  Want to display the top level total of the 10 root items? Load thousands of child items into memory and add them up. Instead of caching the sum, those thousands of items were stored in the session (yes, we got a lot of OutOfMemoryExceptions), and if you wanted to recalculate you'd wait another 2 minutes. What took minutes and 20+ megs of memory (per user), could have been achieved in microseconds with a more explicit data model and the powerful SQL SUM function.  

    Most ASP.NET applications have far too thick a presentation layer in my opinion. For the first time in my life, I was seeing too heavy a business layer - and it wasn't any better. Sure, storing a cached value in the database is a pain in the ass, because you need to worry about keeping it up to date. But when the system is getting rebooted every 15 minutes 'cuz you've taken up all the memory, you're arguments don't have much of a leg to stand on, right? In essence, the best way to describe it was as programming purism. I'm sure the application would have made a great school paper, but when reality can't handle more than 5 users, you're in trouble.

    Is this typical Java development? Is .NET development too presentation-layer focused, Oracle development too data-layer focused and Java development too business-layer focused?

    On a side note, the architecture was based on analysis patterns (not to be mixed with design patterns). Pinging architects inside and outside Microsoft, I learnt that analysis patterns aren't overwhelmingly used. Further research indicated that those specific patterns (accountability and observation) are very implicit and come with a lot of drawbacks (they have advantages as well, don't get me wrong!). It's just that you really have to do some deep analysis to figure out if it's right (of course, that wasn't done). If anyone has any experience with this, I'd love to hear it, even though I've thankfully moved on.

  • Disabling output caching when developing

    We all agree output caching is a powerful feature - especially when applied to a user control. The downside is that it can be a pain to develop with - more often than not you want fresh data and waiting 6 hours (or even 5 minutes) for the cache to empty out sucks!

    Well, thanks to the new output caching API, disabling output caching while developing is real easy. Here's a base user control I use for any control that'll have some output caching. When the DEBUG symbol is defined (ie, when you're in DEBUG mode), any @OutputCache directive will be overwritten by the code below, effectively disabling any caching.

    public abstract class
    DevelopmentUserControl : UserControl
    {
    #if DEBUG
     protected override void OnInit(System.EventArgs e)
     {         
      CachePolicy.Duration = TimeSpan.FromSeconds(0);   
      base.OnInit(e);
     }
    #endif

    }
  • Expecting More From Development Companies

    There are few things I hate more than poorly written code examples that masquerade as useful tutorials/lessons/guides. Every day, readers of these "helpful" guides have no choice but to turn to the ASP.NET forums and Newsgroups seeking help. With a new blog sprouting up every second, I'd be a fool to launch a jihad against the mass-ignorance people seem intent on spewing; but damnit, why can't large development companies get it right?

    Of late I've had my sights set on Macromedia and their craptastically written .NET material. most of the .NET code you'll find on Macromedia's site is hugely insecure, impossible to maintain and likely to run slow as hell. Some of the material I'll reference hereafter is written by independent authors that submit their work to Macromedia, but since they all show up on macromedia.com (some of them even featured), it's squarely Macromedia's responsibility.

    Let's look at this example on how to modify the CommandText of a DataSet:

    CommandText='<%# ((Request.QueryString["sortOn"] == null || Request.QueryString["sortOn"] == "" || Request.QueryString["sortDir"] == null || Request.QueryString["sortDir"] == "") ? "SELECT EmployeeID, LastName, FirstName, HireDate, Address, City, Region, PostalCode, Country, HomePhone FROM dbo.Employees ORDER BY LastName ASC" : "SELECT EmployeeID, LastName, FirstName, HireDate, Address, City, Region, PostalCode, Country, HomePhone FROM dbo.Employees ORDER BY " + Request.QueryString["sortOn"] + " " + Request.QueryString["sortDir"]) %>

    There's actually a note below the code that says "Note that the above code must be on a single line; it cannot be broken into shorter segments over multiple lines." This "single line" is (a) impossible to maintain (b) open to huge SQL injections (c) a slap in the face of N-Tier and OO design.

    There are some examples that aren't as bad, but still grate me. For example, this general tutorial on how to connect flash to .NET has this little gem in it:

    void Page_Load( Object sender, EventArgs e)
    {
     string queryString ;
     OleDbConnection connection;
     connection = new OleDbConnection( @"Provider=Microsoft.Jet.OleDb.4.0; Data Source=Server.MapPath( "Northwind.mdb" );   
     connection.Open();
       
     OleDbDataAdapter adapter = new OleDbDataAdapter( queryString, connection );
     DataSet dbData = new DataSet();
       
     adapter.Fill( dbData, "Results" );
     connection.Close();
    }


    To credit the author, he at least points out that "it's a good idea to place the database in a private directory that is inaccessible from the web" and makes a small reference to Server.MapPath, but does any one actually think a database path should be coming in from the query string, un-validated?! What irritates me more is the lack of try/finally or using - simply because too many examples exhibit the same lazy oversight. Don't give me any of that editorial crap for online resources either - 99% of the authors that write tutorials like this write code the same way. if (adapter is IDisposable) Console.WriteLine("DISPOSE ME!");

    My disgust with Macromedia's lack of groking .NET all began when I tried to familiarize myself with Flash Remoting (the binary protocol used for Flash to communicate with the server-side code). Page 6 of the PDF is a pretty big offender. Although the two examples above are pretty bad, the code written by Macromedia itself is even worse. Here's an example of what I mean:

    protected System.Data.OleDb.OleDbConnection sqlConnection;

    public DataTable getProductsByCategory(int catId)
    {
       string sql = "SELECT productId, name, description,
       categoryId, image, price FROM Product WHERE categoryId =
    " + catId;
       GetConnection();
       OleDbDataAdapter da = new OleDbDataAdapter(sql, sqlConnection);
       DataSet ds = new DataSet();
       da.Fill(ds, "Products");
       return ds.Tables["Products"];
    }
    private void GetConnection()
    {
       String source1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Inetpub\\wwwroot\\flashremoting\\samples\\db\\sports2000.mdb;";
       // get a connection using the connect info that works on this SDK platform
       sqlConnection = new OleDbConnection(source1);
       try
       {
          sqlConnection = new OleDbConnection(source1);
       }
       catch(Exception)
       {
       }
    }

    To be efficient, I'll use a list:
    •  Import a namespace but don't use it (System.Data.OleDb is imported)
    •  Protected fields
    •  Hard coded connection string
    •  Less than meaningful variable names ("source1", "sqlConnection" for OleDbConnection object)
    •  Perfect example of how to never swallow exceptions
    •  Not using command parameters
    •  Creating a dataset just to return a datatable
    •  Resources never released

    Maybe it's just me, but to add insult to injury, the comment "get a connection using the connect info that works on this SDK platform" doesn't even seem to be written in English!

    After seeing that code, it didn't surprise me to see Macromedia's actual .NET products lacking as well. They use an HttpModule where an HttpHandler would be far better suited. To get Flash remoting working, you need a physical page called FlashGateway.aspx. This page is empty and has no associated codebehind. Rather, the HttpModule checks to see if that page was hit to do it's thing. It's inefficient and screams of not understanding modules and handlers.

    If a company writes documentation that features highly insecure code, what expectations should we have from the products it delivers? If their documentation results in hard-to-maintain code, how stable do we think their offerings will be? Macromedia's development center obviously needs to step it up a notch and bring in some technical editors who know what they are doing.
More Posts

Our Sponsors