Dot Net Tricks

Articles about .NET, ASP.NET, C#, Object Oriented Programming and Agile Methodologies
Welcome to Dot Net Tricks Sign in | Join | Help
in Search

Software Theosophy

  • Deleting all records in all tables in the entire database using NHibernate


    This is a great little code snippet I thought I'd share.

    Before each one of my NUnit or NBehave tests, I clear out all the records from the database using NHibernate.  Unfortunately, NHibernate's HQL doesn't seem to do cascade deletes, so you have to delete your tables in the right order.  Otherwise you'll get referential integrity errors such as "The DELETE statement conflicted with the FOREIGN KEY constraint" and the query will fail.  I didn't want to have to explicitly delete each table in order either--I just wanted to loop through all my NHibernate mapped domain objects and wipe them out.

    Fortunately there is a system stored procedure built in to sql server 2008 (and presumably 2005) as well that will disable all constraints in the whole database.  Then you can loop through all the tables and wipe out all the records, then re-enable all the constraints.

    Below is the final code:

    protected virtual void DeleteAllObjects()
    {
        var types =
            typeof(DomainObject).Assembly.GetTypes().Where(
                type => type.BaseType == typeof(DomainObject) &&
                !type.IsAbstract)
                .ToArray();

        GetSession().Clear();
       
        using (ISession session = GetSession())
        {
           

            this.RunSqlNonQuery("EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' ");
            foreach (Type type in types)
            {
                session.Delete("from " + type.Name + " o");
            }
            session.Flush();
            this.RunSqlNonQuery("EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'");
        }
    }

    protected void RunSqlNonQuery(string sql)
    {
        var session = GetSession();
        var cmd = session.Connection.CreateCommand();
        cmd.CommandText = sql;
        cmd.CommandTimeout = 120;
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();

        session.Flush();
    }

    The first method uses reflection and linq to find all classes that inherit from "DomainBase" which is my base class for all NHibernate persisted domain objects.  If you have an interface or attribute something that should work as well, although I like having a base class to put in "global" domain logic. 

    The second method is a utility method I use to run straight sql commands against NHibernate.  I"m not sure if it could be refactored to use NHibernate's built in ISession.CreateSqlQuery() method because this doesn't return any results.

    So that should be all you need.  Just turn off constraints, loop through and delete all the types using HQL and turn the constraints on again.

    I know its cliche' but happy coding. 

     

  • ASP.NET MVC - Multiple buttons on a single form.

    I haven't posted in a while do to being busy with my new job, but I thought I'd just share this code snippet. 

    In the new asp.net mvc framework, you often have the need for a single form, but multiple buttons that each post to a different controller action.  In webforms you didn't have to worry about this as all forms did a postback and asp.net created event wiring magic to wire up each button to an event handling method.  But with MVC, we're forced to go a little old school.  So I created a little helper method that I'll probably submit to MvcContrib or something if they don't have one like this already.  It lets you wire up controller methods to each submit button in a strongly typed fashion using lambda expresssions. 

    Here's an example:

       <% using (Html.BeginForm())
          { %>
      
        <h2>About</h2>
        <p>
            Put content here.       
            <%= Html.SubmitButton<HomeController>(x => x.DoSomething(), "Do something now")%>
            <%= Html.SubmitButton<HomeController>(x => x.DoSomethingElse(), "Do something else")%>
        </p>
        <% } %>

    Obviously the generic parameter above called "HomeController" is the controller class and the DoSomething() is the method in that class.  I also let you specify the button label and optionally the name of the button and other html attributes.

    Here's the source code:

        public static class SubmitHelper
        {
            public static string SubmitButton<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string buttonText) where TController : Controller
            {           
                var name = buttonText.Replace(" ", ":");
                name = "SUBMIT_BUTTON:" + name;
                return SubmitButton<TController>(helper, action, name, buttonText);
            }

            public static string SubmitButton<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string name, string buttonText, IDictionary<string,object> dictionary) where TController : Controller
            {           
                return helper.SubmitButton(name, buttonText, dictionary  );
            }

            public static string SubmitButton<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string name, string buttonText) where TController : Controller
            {
                var link =  LinkBuilder.BuildUrlFromExpression<TController>(helper.ViewContext.RequestContext, helper.RouteCollection, action);
                  var dictionary = new Dictionary<string,object>();
                  dictionary.Add("OnClick", "this.form.action = '" + link + "';");
                return helper.SubmitButton(name, buttonText, dictionary);
                           
            }

        }

    For this to build, you must reference the Microsoft.Web.Mvc dll and namespace, which can be found here:
    http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471

    or click below to download directly:
    http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471#DownloadId=61773

    Enjoy!
  • Giving up on the community


    I know nobody reads my blog anyway, but I still feel the need to comment (rant) to the blogosphere. 

    The back story goes like this.  Joel Spoelsky said some pretty irresponsible things in an interview, calling SOLID principles bureaucratic and saying "(code) quality doesn't matter."  Jeff Atwood more or less agreed with him and posted the Ferengi Programmer.  There has been a lot of outrage and debate and even Jeffrey Palermo has commented on his blog as well as various codebetter people.

    Here's some context I borrowed from  Jeffrey's site.
    Original published audio programFirst response by Robert MartinAttempt at clarification by Jeff AtwoodFurther backing of SOLID principles by Robert Martin.

    So there's all this discussion flowing about, about whether or not SOLID principles are useful to programmers or not and finally we have Jeff Atwood's latest response:
    Read Ulimate Programming Power

    I feel the need to respond, because in the second paragraph of this post, he quotes my comment:

    The majority of developers do not suffer from too much design patterns, or too much SOLID, or agile, or waterfall for that matter. They suffer from whipping out cowboy code in a pure chaos environment, using simplistic drag & drop, data driven, vb-like techniques.  

    And Jeff responds:

    Absolutely.

    But here's the paradox: the types of programmers who would most benefit from these guidelines, rules, principles, and checklists are the least likely to read and follow them. Throwing a book of rules at a terrible programmer just creates a terrible programmer with a bruise on their head where the book bounced off

    He's basically that we can't help the people that aren't interested in learning.  And I think thats true to some extent.  The problem is, he wants to throw up his hands and not help everyone else.  They'll just "figure it out" on their own somehow.

    My first career programming was done in Coldfusion.  After working on a few web projects, I became dismayed out how quickly things deteriorated into what would now be considered "spaghetti code".  Of course, at the time I didn't know that the code was the problem.  I thought maybe the vendors would eventually come out with better tools or a better IDE to manage all this complexity. 

    Instead, my friend and co-worker Ashe, came across a methodology for Coldfusion, called "Fusebox."  Fusebox was a set of rules and conventions for structuring your web application.  I wasn't even Layered or MVC or Object-Oriented or anything like that, although there were some shared principles, such as separating your data access code into separate files.  Mostly it was bringing structured programming to a procedural environment and some naming conventions.   After I started using Fusebox for a while, the light bulb (ha ha) went off in my head.  "The real problem," I thought, "is not the tools or the IDE or the Coldfusion language.  The real problem...is ME!"

    After that I was hooked.  Hooked on not just learning new tools or syntax or libraries from vendors, but on improving myself as a programmer, on improving my craft.  When I migrated my skills to .NET, I kept trying to not only absorb syntax, but also OOP, layered design, patterns anything that would help me tame the chaos that is always at our heels when writing code.

    Yes there are those that will never learn and don't want to learn.  I'd like to think that they are in the minority, but probably not.  But there are also some who just need some guidance, some little push in the right direction, and aren't there yet.  And there's a lot of us that really want to improve that are hungry to become better at their craft.

    I can tell that i'm not nearly done yet.  I have been coding professionally for almost 10 years now, and I can tell that I still have a lot to learn.  Frankly, I can tell I'm not near where a lot of the Codebetter guys are, in overall knowledge and skill.  I'm certainly no uncle Bob or Martin Fowler.  I wish i could learn faster, but its hard with a family and bills to pay.  But I'm always trying.

    For those of that want to be learning, we really need Design Patterns, SOLID, TDD, DDD, Agile, OOP and the rest.   OOP has helped me so much with complex business logic.  I'll probably never do another work flow application without some strategy or state pattern.  MVC has helped me make sense of how to better structure web applications.  Domain Driven Design has really helped me figure out how to structure large enterprise development with databases.  How did I learn about all this stuff?  I read books.  I read blogs.  I asked questions.  In essence, I took from the knowledge of those that came before me.  Yes its a lot to learn and I still don't have it all down.  But each piece I absorb is another notch in my belt that makes me a better programmer. 

    Jeff also talks about marketing and relgion, and I agree there's a lot of that in the programming community and also a lot of the agile and alt.net world.  But there's also marketing that's been coming out of Microsoft and other vendors, as well as hundreds of "24 hours to learning Foo Programming" books that seem to suggest that if you learn a few drag and drop techniques and some basic syntax, you can be a professional programmer.  Just recently, a friend of mine who was learning .NET for the first time was asking me some questions about data access and code behind and I started talking about OOP and ORMs and layered applications.  He said "None of the books on .NET teach you any of that!"  He's right of course.  Part of this is natural.  If you are reading beginners book you're unlikely to hear about something like Repository Pattern or Separation of Concerns.  But some of this is because this is how the vendors market programming. 

    There's no paradox Jeff.  All these "Rules and Regulations" are here for those of us that want to find them.  Certainly we all need them.  Yes there will be some that remain oblivious.  There will be some that have it sink in only a little.  There will also be some who really start absorbing it to become professional programmers.

    So I feel we need other voices standing up as professionals to balance out the natural apathy as well as the bad marketing that comes from vendors.  As others have already mentioned, our industry is so young.  Every other industry has a deep set of rules, guidelines and principles to work off, even if they break them once in a while.   Right now, we need people shouting out principles and better ways of doing things in the hopes that some people who get hit the with the book will turn and look around and see whats up.   Stop coding for a second, and start learning how to be a coder!

More Posts Next page »

This Blog

Post Calendar

<March 2010>
SuMoTuWeThFrSa
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

Syndication

Powered by Community Server, by Telligent Systems