Posts tagged ‘.NET’

As far as web developer’s go, I’ll freely admit that my Javascript is not one of my strong points.  I don’t have a real good reason for this, it’s just that over the past few years I haven’t had much call/need to polish and hone my Javascript skills.  Recently I discovered jQuery, and I must say that I wish I had know about this library earlier.  The more I use jQuery, the more I like it.  The simple things are simple, and the hard things are possible.  Take calling a simple webservice when the user clicks a button on a form.

Client side, the user would click on a button in their browser, in order to "check out" or "check in" – pretty simple stuff.  Click a button, update a record in the database.  I wanted this done via AJAX, as the page itself is pretty heavy with data, and I didn’t want to go through the whole page lifecycle.  I spent some time Googling how to do this on the web, but I didn’t find anything that seemed to be suitable for something as simple as this.

So, enough boring stuff, on with the issue.  In my current application the ASP.NET web service that the client should call looks something like:

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class CampaignProductCheckoutService : WebService, ICampaignProductCheckoutService
{
  [WebMethod]
  public void CheckIn(int campaignProductId, int loginId)
  {
    // Do something...
  }

  [WebMethod]
  public void CheckOut(int campaignProductId, int loginId)
  {
    // Do something...
  }
}

Pretty simple webservice, nothing fancy.  Here is the corresponding Javascript on the browser:

$.ajax({
  type: "POST",
  url: "CampaignProductCheckoutService.asmx/CheckOut",
  data: "campaignProductId=3&loginId=4",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Content-Length", "campaignProductId=3&loginId=4".length);
    $("#progressBarContainer").show();
  },
  dataType: "xml",
  complete: function (xhr, msg) {
    $("#progressBarContainer").hide();
    if (xhr.status == 200) {
      alert("Happy Times!");
    }
    else {
      alert("Wailing and gnashing of teeth!");
    }
  }
});

This looks busy, but in reality, it isn’t. Now, for a detailed explanation of what is going on here, I’d suggest reading the book jQuery in Action.  It is a most helpful book for learning jQuery.

Anyway, here is a quick rundown of what is going on:  the $.ajax is a jQuery method that will perform the AJAX call, using the parameters that we provide it.  jQuery will perform an HTTP post to web service specified in url.  As part of the POST request, you can see that we’re passing in the parameters for the webservice call.  So far, pretty straightforward.

The next line, beforeSend, is a javascript method that jQuery will call before it does the POST.  In this case, we make sure that the request header has the length of the data being sent, and we show a progress bar to the user.  The funny syntax you see there is how we select the DIV element holding our animated gif and display it to the user.

Your standard ASP.NET web service will return XML to the client, and we inform jQuery of that with the dataType parameter.

By default, jQuery will perform the AJAX call asynchronously, so in the final line we provide another Javascript callback.  jQuery will call this function once the request is finished.  In this case, we hide the DIV element holding the progress bar, and we check the XMLHttpRequest object that is returned from jQuery. If the status is 200, then all okay and we display a happy message.  Otherwise we assume the request failed, and display a sad message to the user.

There you have it, a quick and dirty explanation of using jQuery to call an ASP.NET Web Service.

Two topics merged into one.  Rod Paddock wants to talk about stored procs, and others want to learn how to explain NHibernate to other people who aren’t familiar with it (and minimize the jargon).

Rod uses a custom code-gen solution based heavily on sprocs – a data driven approach.  Sounds like it works well for him.  Oren concurs that this technique could be very effective in certain circumstances.  It will have problems with complex situations that deal with convoluted/difficult data scenarios.  He’s giving an example, but I just can’t keep up with him.  The point of Oren’s story is that a domain driven approach will would better when you’re not dealing with data but with data and behavior.

Brad Abrams brings up the point of noun centric vs. verb centric  designs.  Noun centric == data driven.  Verb centric == domain driven.

Oren talks about one of the big advantages of DDD.  We can very easily change the model, as it is all in code.  Tools like R# allow us to make changes quickly, and then NHibernate will allow us to update the database just  as quickly.  Databases are an implementation detail, part of the application, a mere persistence store.  A good domain design will generally lend itself to a  decent database design.

Apparently it is possible to suffer from an SQL injection attack with NHibernate.  According to Oren, you have to be pretty stupid for this to happen, but it can happen.  I did not know this.

Topic changes:  what do you do when you come to a client who has 1.5TB of established data and database.  How do you deal with that?  Ideally, you claim ownership of the data, and carry on.  This isn’t very realistic.

Oren starts explaining that NHibernate can allow you to partition the data in existing databases to match your model.  He suggests that it might be better to speak with the DBA to make a new model, as this approach might take a lot of effort.  Might be smarter/better to change the persistence.

Oren’s preference is to generate the HBM’s by hand.  He wants the pain to be real.  The logic is that the pain will force you to thing about your model, and helps you focus on what is important to your model.  By generating the code, you end up with, for example, a domain model that has 200 classes/tables and classes with 700 fields.

Another advantage of using NHibernate:  you get a nice way to set up a unit of work, and can specify boundaries for your application.  For example, you can, via an HttpModule with your unit of work, limit the number of queries (trips to the database).  Oren:  Going to the database is the best place to optimize, not the query itself.  Minimize the trips to the database.  You can enforce this limit right away.  It is not a problem that will hit you out of the blue in production.

NHibernate is very complex, and the learning curve very steep.  Oren argues it is not overly complex, and this complexity allows you to very advanced things.  For the simple stuff, NHibernate is very easy.  It is very irresponsible to just parachute in, introduce NHibernate, and then disappear.

Oren quotes:

  • "I tend to be nice to people that pay me"
  • "Use a set, that is all"
  • "Don’t worry about performance until you see you have a hotspot and are using a profiler"
  • "Whoever designed Linq bordered between genius and madman"

Ben Scheirman refers us to Chapter 6 in NHibernate.  Important for collections.

It seems that this session is not so much stored procs, but a Q&A session from the community about what exactly NHibernate can do.  Oren’s knowledge and experience

The CLR is very fast, asserts Oren Eini.  Rod Paddock disagrees.  With WebForms, it isn’t the CLR that is slower, it is all the stuff that goes on behind the scenes with the page lifecycle.

The question is asked:  Are datasets more efficient that NHibernate.  Apparently some people get hung up on these types of things, and claim that tools like ORM’s aren’t good because they add overhead.  Sounds like premature overhead to me.

Unrelated trivia:  This is the latest in the year it has snowed in Seattle since 1968.

For those getting into .NET 3.5, you might find Mono.Rocks of interest.  I first saw this on Jean-Baptiste Evain blog.  Basically, this is a collection of extension methods for the class libraries.  They are covered under the MIT licence, so you can pretty much use it anywhere.

As most Resharpies know, when you’re using Resharper you can reformat your code. A nice feature is that you can use this reformat code to also organize and layout your code files the way you like it.

For example, Kyle Baley did post on how to how to use the format code to get rid of regions. His techique is a bit unrefined – his revolutionary, dogmatic zeal he will clobber all regions and do nothing else – but still handy.   Myself, I’m a bit more compulsive / fussy when it comes to the layout of my code. Not only do I want regions gone, but I want the code to appear in a certain order. Lucky for me that Reformat Code does this for me. Here is the Type Member Layout pattern I use. If you want to use it, just paste it into the type member layout window in Resharper.

What this will do, when you ask Resharper to Reformat Your Code, is the following: Remove all regions Sort your code, with the following order:

  • any COM Interop interfaces
  • public delegates
  • public enums
  • constants (sorted alphabetically)
  • fields (sorted with readonly first, and alphabetically)
  • static constructors
  • constructors
  • properties (sorted alphabetically)
  • methods (sorted alphabetically)
  • anything else (sorted alphabetically)

For the sake of brevity, I’m not giving a detailed breakdown of the Type Member Layout Pattern syntax. Well, brevity and the fact that I’m not 100% certain on a lot of it and don’t want to unintentionally say something wrong. I do believe that the format is pretty straight forward, so you look at it and make your own adjustments.

However, to give you an example. Imagine for a moment that you wanted to surround any interface methods in a #region. First off, don’t tell Kyle. Might be a good idea not to mention it to David Laribee while you’re at it. Secondly, add the following snippet:

<Entry>
  <Match>
    <And Weight="100">
      <Kind Is="member"/>
        <ImplementsInterface/>
    </And>
  </Match>
  <Sort>
    <ImplementsInterface Immediate="true"/>
      <Kind Order="property method"/>
      <Readonly/>
      <Name/>
  </Sort>
  <Group>
    <ImplementsInterface Immediate="true" Region="${ImplementsInterface} Members"/>
  </Group>
</Entry>

What this will do is, for each member of your class that is part of an interface implementation (the whole part), sort it by it’s name (the part), and surround them with a #region (). If you look at my Resharper Patterns with Interfaces sample, you can see by the position with in the element that the interface #region will appear at almost the end of your *.CS file. I hope now that this will appease your inner obsessive compulsive self.

The past week I’ve been dabbling with an open source program called Open Dental – mostly trying to see if can get it to compile under Mono, and running under Linux.  I figure that this would be a good opportunity to and work with a cross platform application.

According to their website, Open Dental has been supported under Linux since v4.7.  Here are some notes of my efforts so far.

You will need Mono v1.2.5.  It seems that there is a problem with the Linux binary installer ( a known bug that will be corrected in 1.2.6).  I used the OpenSUSE 10.2 VMWare image which had a 1.2.5 install all set up.  That solved my problem of getting a current Linux distro with the most recent version of Mono.

There is a website for getting Open Dental to run under Ubuntu, and instructions on how to compile on Linux.  I couldn’t get the application to compile under Linux using those instructions.  I suspect that they are a bit out of date.  What I ended up doing was compiling the application in VS2005, setting the build to LinuxRelease.  I then copied the binaries over to my OpenSUSE VM, and ran Open Dental.

Now, Open Dental uses MySQL 5 for a database backend.  The problem that I ran into next is that the database script that is provided to setup the database is for a very old version of Open Dental (like v3.x).  Open Dental is supposed to be smart enough to update the database to the correct version.  However the DB upgrading process seemed to keep crashing.

What I ended up doing was installing the trial version of Open Dental.  This created a database for me.  Once I had a database, the application seemed to run.

A curious thing is that when I would try to run Open Dental on Windows, using Mono 1.2.5.2, the application crashes.  No such problems running under Linux though.

One thing I noticed since I started doing ASP.NET programming back in 2002: I started using Javascript a lot less, and my copy of JavaScript: The Definitive Guide sits on the shelf gathering dust.  I’ve noticed a lot of developers I’ve worked with are the same way. In fact, I’d say that most of the ASP.NET programmers I’ve worked with these days really don’t know much about Javascript.

I don’t blame Javascript itself for this – I blame ASP.NET. Developers just get used to dropping the server side controls on their WebForms, and then doing everything server side. I’ve also worked at clients which had a "no client-side javascript" rule. All of this combines to cause our (my) Javascript skills to atrophy and wither. Kind of shame, really. (note: to a degree, I think the same can be said about CSS).

Now, I think that when MS-MVC is released, this will change. As places being to use MVC more, I can see Javascript becoming more important in my day to day work – perhaps even to the point of becoming a first-class language again.
Javascript didn’t rape my dog – that’s because ASP.NET has pummelled my Javascript skills into a coma. But, I suspect that in the near future, a healthy dose of MS-MVC will revive my Javascript. I’d better start thinking about how to protect my dog.

Recently, on one of the mailing lists I subscribe to, a member starting bashing .NET. A bit curious as to why there was this strong hatred of .NET, I posed a simple question:

What is wrong with .NET?

The answer I got back somewhat suprised me:

I guess the standard reply is, what is right about .NET?  .NET was invented so that M$ could provide software as a service. You would end up with a minimal OS on the disk, and no applications. When you turned your computer on, it would download whatever applications you needed, or did so on demand; if your subscription was paid up.

That was the PR on .NET when it first came out, to my best recollection.

Your PC was useless, unless your subscription was up to date. Again, as far as I remember, this was the original intention of .NET. It doesn’t look like things progressed quite the way they were supposed to.

I felt, that given the opinion was largely based on an erroneous perception, that I should respond:

Yes, the original PR campaign around .NET was a bit of a disaster, if you ask me. It did more to confuse people than anything. You’d mention .NET, and some people would think you were talking about the programming/software development environment, some people thought you were talking about the next version of Windows, and yet others still thought that you were the service concept that was mentioned. And lets just quietly agree to push Passport into a dark pit along with Microsoft "Bob".

These days, when people speak of .NET, they are speaking of the software development platform – i.e. the tools to write software. The concept of .NET as a Microsoft service faded away a while ago.

Now, I will admit that I might have a bit of a bias. My OO programming started with Clipper (using ClassY), then C++, then Java. And when .NET came out in beta, I switched to that.  I’ve also dabbled a bit using OO in Perl.

In the 5+ years I have been using .NET, the only "subscription" I have paid is for my MSDN subscription, and that I have only paid for since I started consulting. I have written .NET applications without having an MSDN subscription. I know of people that write .NET applications using nothing fancier than emacs. In fact, I know of people that write .NET applications without Windows or using anything from Microsoft. I have never had, nor heard of, anyone having their custom applications "expire" because their "subscription" was unpaid. .NET doesn’t force any downloads on you – that is Windows Update.

Using .NET is no different that using Java, IMO. The basic concepts behind each are almost the same. There are pros and cons to each, but in the end it comes down to your preferences (or that of your client). I’ve worked at places that use both. The .NET camp does borrow a lot from Java, many Open Source Java tools have been ported to .NET. Many of the software engineering principles that the Java camp adopted years ago are finally start penetrate into the .NET world.

So, if you ask me what is right about .NET, I’d say that for many software applications, it’s a good choice. I can write web application, Windows applications, Windows services, daemons, and web services. I have have a good set of libraries that allow me to concentration on what I need to get my job done, and not spend so much time on "plumbing" – unless I want to.

I can use the same language for each every application, or I can use one of the many languages that are supported by .NET (C#, VB.NET, Java, C++, Python, Ruby, Perl, PHP, FORTRAN, COBOL, and a large, large, list of others). I can share my .NET components with each other, regardless of the language I use. I can (and have) also share my newer .NET components with my older Delphi/VB/C++ applications. Thanks to Mono, you can now run your .NET applications on platforms other than Wintel. 

So, for developing software applications, pick your poison. .NET is definitely a viable choice.

Why I love NHibernate:

I am rather please by the fact that a database schema change involving the creation of six new tables, three one-to-many relationships, and a many-to-many relationship (which includes a sort order on the join table) can be taken care of inside of seven easy hours.  It probably would/could have been less, but I crafted the HBM and class files by hand and had a few typos which hide themselves well.  This also included the time it took to create some quick integration tests to ensure that CRUD is working.

Now, of course, there are other changes to the domain that need to be done to deal with these new tables, but NHibernate frees me from paying a significant "database tax".

This Saturday past we had the Edmonton Code Camp.  I’d say things went pretty well.  It’s my understanding that some 80 people showed up to hear a variety of topics.  I kicked off the day in "Track #2" with a Introduction to Test Driven Development.  For those who are interested in my presentation / code, you can download it here.

On a project that I’m currently involved with, I’m using NHibernate and a persistance-ignorant domain. Today NHibernate threw me a "You may not dereference an collection with cascade="all-delete-orphan"" error. This kind of had me confused for a bit. What this error means is this: When you have a parent-child relation in your domain, say something like this:

public class Parent
{
     ISet<Child> _children;
}

You can’t do something like this in the parent class:

_children = new Set<Child>();

NHibernate gets angry with this and throws the aforementioned error.  It does this because the collection object that NHibernate was tracking is now gone.

What you need to do is something like:

_children.Clear();

The collection object that NHibernate is tracking is still around, so NHibernate can figure out how to persist the collection of child objects.