Friday, October 11, 2013

Moving from TFS(vss) workflow to Git Part II

In my previous post, I outlined our current VSS-inspired workflow.  Here, I will outline a Git workflow that I believe will provide the isolation that we need without the danger or overhead of cherry picking commits to merge up.

To start with, I believe we should use the fairly well established “git workflow” pattern with a few minor modifications. Most of this is outlined there, but I will address a few issues here.

At the outset, with we will have a Dev branch. This branch will represent finished features that have not yet been to QA. From this branch, each feature will branch ( as a verb ) down into a feature branch ( noun ). The feature branch will be maintained until the feature or fix is considered complete and ready to go to QA. During the developer’s daily process, the Dev branch will be merged down to his feature branch at least once a day, and possibly more often, depending on the amount of work going on elsewhere that needs to be integrated.  Once the developer’s feature is completed, he will merge it up to development, making it available for deployment to QA and merging to other feature branches.

Two points to make about the above: (1) the Dev branch will always be in a state that is ready to push to QA, and (2) the reason that the feature branches merge down from Dev often is twofold. First, new completed features may be committed by other developers at any time, QA fixes and hotfixes will be being merged down into Dev, also at any time. The features will want to have an accurate picture of the Dev branch. Furthermore, frequent down merges will make the final up merge considerably easier, ( albeit at the cost of many small conflicts in the down merges. Nevertheless, this is much preferred over having a bunch of conflicts to resolve all at once ).

While I believe “git workflow” covers the QA and Prod workflow, a quick synopsis follows. At some point, someone says “Hey! I just finished my feature and would like to have it QA’d”. After he merges into Dev, he can then merge Dev into QA knowing that all features in Dev are in an initial completed state and are ready to merge up to QA. QA may find errors with the new features. The feature owner, at this point, branches off of QA, fixes the problem, merges up to QA and down to Dev, and QA tests again. A similar process is used for doing hot fixes on production. branch –> fix –> up merge –> down merge to both QA and  Dev.

So, now our developers can commit all day long, as they well should, without worrying that their commits will inadvertently make it to production. Perhaps an even nicer step would be to make available an environment in which a feature branch can be QA’d. This way, the back and forth of bug fixes could take place off-line, and when a feature is merged with Dev, it will be in a much more complete state. However, I’m not sure what would be involved with getting multiple, disposable testing environments up.

One caveat is that all the features that are merged with Dev must be cleared to go into production in the same push.  Once they are in the main line there is no easy way to tease them back out.  There is a workflow that would facilitate this practice but (a) it is pretty much an incremental (albeit large) change to the proposed workflow so we can evaluate it later, and (b) it is somewhat complex and unless we are very sure that we need this flexibility I feel simpler is better.

In a future post I will look at some of the actual steps and commands that developers would be using given the proposed workflow.

Moving from TFS(vss) workflow to Git Part I

Here at work we currently use TFS for, well, everything.  We have made the wonderful -some would say only responsible- decision to move to Git.  This decision will require all manner of stuff to happen.  In this post, I will explore the developer experience.

We currently have certain workflows for check-ins, merges, etc. that are based on the insane way that TFS encourages you to do these things and these workflows will not work with a respectable source control system.  So, first I will lay out the way we currently do things.

We have a relatively small team: three backend developers and a frontend developer.  None-the-less all of us tend to be working on different things at any given time.  We all check in to our Dev branch whenever we feel like it.  We do not employ CI so the state of our Dev branch is never really known until you get latest and build.  Fortunately, it tends to be in pretty good shape despite the absence of procedure or control.

The fun begins when we want to move our code into a QA branch.  The technique we use is to merge specific change sets.  As I mentioned, everyone checks in their changes ad hoc, meaning that everyone is in a different state of readiness.  So, when we want to merge up to QA one person’s changes and not the rest, we look at all the change sets and try to distinguish,  either by reading the commit message or by actually looking at the code in the change set, which are the appropriate change sets to merge.  This process is repeated when we move from QA to Prod.

On the one hand, this seems like an insane proposition that veritably begs for disaster.  On the other hand, due to the hard work and diligence of the team members, we make it work which facilitates our siloed development of different features and bug fixes.  As this is a rather ingrained workflow that has been in place since long before I joined the team, our switch to Git will have to permit some facsimile of this process without polluting or perverting our new source control system.

In the next post I will outline some of the practices that I believe will allow us to be successful with Git.

Wednesday, September 4, 2013

Embrace the frontend

In my last post I wrote about getting out of the “forms” business and into the “AJAX” business, which I view as a pivotal step in the development of Web applications that are both better managed and more responsive.

The problem is that once you are liberated from the tyranny of <forms> you find that you can no longer be just a “backend developer” that surfaces web pages. You must learn the language of the frontend. I know you love your strongly typed, server side, cozy blanket, and you can certainly go work for some monolithic death corp and write the same code for the rest of your life. But if you want to develop interesting applications and stay current in the flow of software technology, get over it and start learning javascript.

One’s first steps into javascript invariably go as follows:

1) Write a bunch of crap in a <script> tag in the HTML file it’s self

2) Discover what a mess that is and how hard it is to debug and move same crap into a separate file.

At that point you think you are being responsible and call it done. A year goes by and you find that you have a lot of those files, with lots of duplicated code and/or duplicated functionality with different implementations. You consolidate that into some horrible library that contains every “helper function” in the world and include the whole file on every page. Probably minify it so when it breaks it’s a pain to figure out what’s going on and now you think you’re done.

Well you’re not. You wouldn’t write your C# application like that. In fact you’d probably go on some career-ending rant if you saw it being done (much as I am doing here with js). You must treat you’re javascript application with respect if you want it to respect you. Sure it lives for, perhaps 10 seconds, but those are pivotal seconds and that time can and will grow as you feel the joy of building an app on the client side.

So how do you treat it with respect? Well, the KEY to success is to employ a pattern, a nice pattern, and stick with it for every page. JS doesn’t have a very appealing, object oriented story out of the box, but there are a few patterns for creating objects or classes that are easier and more familiar to work with. Some are better than others. And there are several frameworks that provide implementations of these patterns and generally wrap them up with some other functionality.

As I mentioned in my previous post (not smart enough to know how to point to previous post here), I like very much the Knockout.js . However, Knockout endorses a rather repugnant pattern of dispersing your javascript between your HTML and a simple javascript object. You essentially (within Knockout’s attribute) put onclick -> fire this event in my ViewModel. Their ViewModel is just a plain old javascript object with properties and functions on it. The idea of putting a bunch of behavior inside of HTML is most unpleasant. However, I am willing to concede the need for a two-way binding attribute. The payoff is so great and the offense rather minor. But when you start putting all manner of logic in the HTML attributes, it’s my loud opinion that, you have crossed the line, Jack. Furthermore, the anemic Knockout ViewModel is not very helpful, when it comes to organizing your code. Thus, I say that KO.js has an excellent two-way binding story but you should leave it at that. Don’t let it take you down the dark road of HTML decoration.

I can see how KO would be compelled to provide other functionality so as to seem more like a “framework” than a “library”, and I can see how they would try to extend what is already working so well for them (e.g. the HTML decoration). I can see this but you can’t make me use it. Other “frameworks” Angular.js for one have taken a similar direction. Angular is very popular, but their HTML wrangling makes KO look like a minor offender. I won’t go any further into my objections. If you want to debate, hit the comments.

In my next post I will write about how I use a combination of backbone.js and ko.js to create a best-of-both-worlds cocktail.

Furthermore, I am cross posting this to my personal blog if you like it so much you want to read it twice. http://cannibalcode.blogspot.com/

Tuesday, September 3, 2013

Shredding your forms

Shredding your Forms

Using the <form> tag to wrap elements and then submit the data contained within worked in the 90’s. Hell it worked in the early 2000’s. But with the advent of AJAX techniques, the <form> element is now really more of a liability than a help. The problems are as follows:

1) Through some method, unbeknownst to me, when a <button type=”submit”> is clicked the <form> makes a post to the url found in one of it’s attributes. There is no hook into this process not before it goes out and not after it comes back.

2) Add to this that if you have something you need to submit outside of the <form>, you’re pretty much out of luck.

3) Thus you get what’s in your form and nothing else and you must redirect to a whole new page on return. No nice success or error message showing up smoothly, just a whole new page of HTML (which could include your messages of course).

4) This leads to the highly unappealing practice of packing hidden elements within the form, and/or - even worse - updating element names when you dynamically create a new element. Shudddr.

While there are work_arounds for these problems that allow you to use AJAX to catch a form submit, you can take it from me it can be a byzantine nightmare to try to customize.

So when you throw out your horrible <form> tags and start using AJAX to post and get data from the server, you will find that, while it did a rather crap job of it, the <form> tag did at least harvest your values from the elements contained. Without it, you must now query each element that contains data you want to post back. While this is exactly where you get the benefit, it is also a pain. Add to this the fact that, if you are using C# MVC, MVC expects that data to come back in a very precise and unintuitive manner, and you are now faced with a rather boring if not daunting task. In fact, it can be so daunting I may do a blog post explaining how to do it.

Luckily, the solution is not only beautiful it is wonderful and awesome, all wrapped into one. By employing a model binding framework like Knockout.js or one of it’s lesser cousins you can create two way binding between your DOM elements and a JSON object (heretofore referred to as the ViewModel). This means that when you change the value in, say, a text box, the corresponding property on the ViewModel changes as well, and vise versa. So now, when you want to submit your data via AJAX you don’t talk to the DOM at all. Insteadm, you just submit the ViewModel object. Again, the versa of this vise is that when you want to update the DOM you must merely speak, in it’s native tongue, to the ViewModel.

Creating this two-way binding, emancipates you to some degree from the business of mucking around in the DOM. I say to some degree because you most likely will still have to interact with the DOM to perform other actions: clicks, show/hide, fade out with pixels, etc. Still if you can find a way to abstract that noise, you could quite possibly, write tests for your javascript logic without the incredible hassle of spinning up a browser and mocking your HTML.

I have glossed over A LOT of the implementation details in favor of a much higher lever ( and much shorter post). I would be happy to write a post on the details should anyone ask.

In my next post I will discuss the strategy that I have found to be quite fruitful for employing two way binding without horribly polluting your HTML or creating a deep and vast plate of javascript spaghetti.

Monday, April 22, 2013

ClipX Still the best

ClipX is a great clipboard extender.  It remembers your last x number of ctr c(s) and has them available from a hotkey.  It saves images as well as text and does lots of other cool stuff I never bothered to mess with.  What’s more, it was developed in 2005!  the url is http://bluemars.org/clipx/

Here’s the caveat though, it will set a couple of hotkeys for you and one of them is Ctrl Shift N which of course is “Navigate to File by File Name” in resharper.  You will be plugging away happy as pie then ctrl shift n and it will open a browser for you rather then the resharper command and MAN will you be pissed.  Then you’ll waste copious amounts of time trying to figure out how the hell to get that shit back.  Well, I just done that step for you so go to clipx settings and change that bastard and live happily ever after.

Thursday, November 1, 2012

Thoughts on being an Asshole

Last night I read a post by Nicholas C. Zakas on being nice, which in turn lead me to a post by Tom McNichol on being and asshole which it’s self caused me to start to muse on the nature of being an asshole.

The Tom McNichol’s article was largely on Steve Jobs and how he was successful despite being an asshole, rather then because he was an asshole.  One quote in particular caught my attention

“Even people who worked with Jobs told me that they'd seen him make people cry many times, but that 80 percent of the time he was right” – actually that was McNichol quoting someone else.  I don’t know how to show that.

So this is concerning because I am right 95% of the time.  And while I’ve only made someone cry once in recent history, I do get the sense that I am perceived to be an asshole.  So my musings are as follows.

I believe there is room here for a discussion on intent, however, I don’t have time and this is long and boring enough already.  But I will say this, regardless of how I am perceived, I am always surprised and saddened when I find I have hurt someone’s feelings.  Well, almost always.  I guess I see myself as eminently diplomatic. And other's? They may see me as an asshole.

If one, in a certain situation, is correct, should that person accept an inferior solution, poor reasoning or miss-understanding of facts?  I find that very difficult to do.  In fact, at times, I feel that tacitly accepting poor thinking is a disservice to the thinker, and perhaps to the world.  So does the fact that you are right, in effect, make you an asshole?  ( I know what you’re thinking, ‘It’s the fact that you think you are right that makes you an asshole’, but let’s just assume for the sake of argument that you are in fact right. ).

I understand that it’s also an issue of presentation.  How do you go about correcting a situation.  If you have the ultimate say it’s easy to be easy going, but if you do not have the ultimate say and there is a very real possibility that a bad outcome may come to pass, then you really need to be more assertive.  You must make sure you’re points are taken into consideration and clean up the mess later. 

I guess this internal rambling comes down to two points. 

Point 1) A) do you follow the Christian ethic and turn the other cheek, hope to inherit the earth, and make an unpleasant situation pleasant at all costs, or B) do you follow a more Nietzschean track which says that pity is  a disservice to the person you are pitying. That one must seek the higher road of intellectual authenticity before pandering to the feelings of those that may be offended.

Point 2) How important is the issue at hand.  I often find that appalling grammar, and sentences which do not actually convey the meaning that the speaker believes they do, is in-fucking-tolerable. ( bad spelling is ok Smile ).  I believe this may fall into the he’s an asshole category.  But hell it’s sooooo annoying.   Other issues such as should we purchase this car, or vote for this politician, may have much greater ramifications.

I guess I could go on here about how in effect nothing really matters as one can not reasonably predict what might happen next week much less predict the course of human events and so one should always opt for making people feel good about themselves.  But the fact is I’m a freakin optimist, a romantic if you will.  I have to believe that doing what is ‘right’ has some effect somehow.  Of course what is ‘right’ conveniently lines up with my belief system perfectly.  Which causes, perhaps an endless recursive loop.

Whatever

Thursday, December 15, 2011

A Better Ajax throbber

I’ve been messing with setting up an ajax throbber ( the little waiting icon or animated gif.  That’s what they call it.  It ain’t me. ).

Most examples show that you should put the show() logic right before you make your ajax call and then the hide() in the $.ajax.complete() event.  This has a number of problems. 

1) Unless you have just one single repository through which all ajax calls go ( and I do ) you end up putting the start throbber logic all over the place, wherever you make a call

2) unless you use a setTimeout function the throbber will always show even if just for a flash.  It’s much better to have a pause and if the ajax call is quick enough then you don’t see the throbber at all.

Number two has a major problem though.  And this is the meat of the post.  If you set your time out for 1000 ( one second ) and the ajax call comes back in 500 then the ajax complete will fire before your setTimeout has fired.  Then the setTImeout will fire and the throbber will never disappear.

Two ways to deal with this are to put the hide() logic in the repository call back method which unless you have a single repository as mentioned above with a single OnComplete callback that then calls your real callback you end up with code everywhere again.

So what I decided to do is to have global ( or scoped to your module global ) variable called showThrobber, and set it to false.  Then in the $.ajaxSetup.before send I put my timeout with a check for showThrobber. in the $.ajaxSetup.complete is set showThorb to false and hide the throbber.  so it looks like this

$.ajaxSetup({
            complete:function(){dci.showThrob = false;  $("#ajaxLoading").hide();},
            beforeSend:function(){setTimeout(function() {if(dci.showThrob) $("#ajaxLoading").show(); }, 500)}

});

In my ajax get ( or post ) I turn on the showThrob

ajaxGet:function(url, data, callback){
             dci.showThrob=true;
           // showLoader = setTimeout(function() {if(dci.showThrob) $("#ajaxLoading").show(); }, 1000);
            $.get(url,data,function(result){repositoryCallback(result,callback);
            });
        }

sorry about the formatting.

This is I believe called a latch mechanism.

Monday, November 21, 2011

How I use Backbone.js Views as modules

In my previous post I explained how I use views as a basic class structure. Here I will go a bit deeper into how I use them.

At the base there is the traditional Backbone.js view.  Used as one would normally use it, to set up the container, hook up the events, and structure your code.  This is a nice way of compartmentalizing functionality.  But let’s say that you have two views, or pieces of functionality, say a popup functionality and an ajax form functionality.  You  could initialize the two views separately and then hook them together using a controller ( more on that later ) but if you do this a lot, and this is the sort of thing one would do a lot if they are using popups, then this get’s terribly tedious. 

So I employ what I call a module.  It’s an extended view that has a views collection ( object ) a modules collection and a destroy function();  Then I inherit this module, and in it I instantiate the ajax form view, the the popup view put the form in the popup and render. I put both views in the modules view collection.  The destroy method loops through the modules and the views that belong to the module and calls destroy and remove on them respectively.  Now I can call new AjaxPopupModule() pass in an el ( a root element ) and a url and possibly other stuff and I’m all set.

Using Backbone.js views as a class structure

So what I’ve ended up doing is using Backbone.js Views basically as a class structure.  I used to use immediate functions or static objects or whatever you want to call them, basically

var x= (function(){

return {

}

}())

for everything.  And I always had an init function to set it up.  The limitation was that I could not inherit from those classes so I eneded up duplicating code a lot.

So, as I was saying, I’ve adopted backbone.js views as my class structure.  I can inherit these classes, they are constructor functions so I can put set up code in the function and they offer a few bonus features as well, such as if I have straight up events I can use the views event declaration infrastructure.  But overall what I like the most about it is that I can create base classes that have the functionality that I use a lot on them.  Now I know I could write my own class structure and implement all these features as well as a couple I’m about to mention that I don’t like, myself, but a) I’m kind of scared of constructer functions with prototypal inheritance and b) I believe ( hope ) that the structure will be familiar to people who use backbone.js ( such as my team ) and they will understand what is going on more easily.

The one thing I don’t like about using backbone.js views as my base class structure, is that it doesn’t implement any override functionality.  You can overwrite but not override and call base().  This would be great for such things as having a function on a base class called registerSubscriptions() that lays out the common subscription.  Then in my inhertied classes I could override it add page specific subscriptions then call base().

The way I get around that now ( and there are I guess a couple of similarly distateful ways ) is that I have my base registerSubscriptions() call registerAdditionalSubscriptions() as it’s last step.  in the base class I stub out the method so it won’t crash and in my sub classes I overwrite the method if necessary.

Friday, October 14, 2011

My javascript stack

Ok so here’s how I’m building my single page business app.

Backend is asp.mvc using fubu html helpers. 

front end.  Here are the plug ins I’m using. jquery ( of course ), backbone.js, a little pub sub class, $.address, knockout.js and my own system of controllers.

A lot of people talk about not using any controller, just straight backbone.js or knockout.js.  I can’t seem to figure this out.  My shit has lots of stuff going on that has no place in a view or a model but I don’t want it just hanging around willy nilly.  I need a freakin controller to manage all the different parts. 

For instance, when you click on a row in the grid, it must hide the grid and show a form.  When the form submitted or canceled it should remove the form and show the grid again.

First I hide the grid so that I don’t have to re load that section.  If the form is updated rather then canceled I update the grid but I don’t have to get the whole def and re render everything.  The form however, I retrieve via ajax.  This is because there could be different forms based on what exactly is clicked on the page/grid and loading a form for every possible outcome is crazy.

Even so that might not seem like it’s that crazy that I just absolutely need a controller, but here’s a real example of the basic page in out app.  We a) load a grid. click on the grid and you get b) ajax call for form. On the form there is the ability to associate a document with this particular instance of the entity.  If you haven’t any you can upload a new one.  But you can’t just upload a document you much attach some meta data to the document so we need a c) new ajax form and a d) new popup to house it.  then you save the doc and meta data and you see it in a list of selected documents for this item.  If you want to edit/view one of these docs you can click on the name and up comes the popup with the form and data.  This is the basic page and shit just gets more complex from there. 

So in my next post I’ll explain my controller and how it keeps me sane.  But it’s friday 6:00 and I still got shit to do so I’m out.

Catch up and more Javascript

well it’s been forever since I’ve posted but don’t worry I haven’t learned a thing.  I will dispense with the backlog and jump straight into what I’m doing now.

Javascript

I am working on a single page app with basic business app functionality eg lists ( grid ( jqgrid )) forms, menus, popups etc.  I of course quickly found my javascript btfu ( getting ugly and out of control ).  So I started writing my own collection of classes to organize and componentize the functionality.  After a few iterations I had something pretty workable but I’m using Douglas Crockford’s objects with private variables.  These are nice and clean and organized but they don’t allow for much extension or inheritance.

I’m still using these but I have integrated backbone.js and am about to integrated knockout.js in there to.  I will write an other post explaining this stuff so people don’t have to read this bullshit if they don’t' want

Tuesday, March 23, 2010

Using FubuMVC.UI in asp.net MVC : Getting started

If you are not fortunate enough to be able to use FubuMVC but are fortunate enough to be using asp.net MVC, you may find yourself unendingly vexed by the suckyness of the ui helpers in asp.net mvc ( heretofor referred to as mvc ).  mvccontrib has some good stuff with the uibuilders, but I find the FubuMVC.UI more to my taste.  In this post or series of posts I will show how I am using the FubuMVC.UI in my MVC app.  I am using Structuremap as my DI container so there may be a few differences if you are not.  And to that not, I got a big leg up from RyanOhs post Using FubuMVC’s Html Conventions in Microsoft MVC which seems to be dead now but may someday return so I linked to it anyway.  He’s using Windsor as his DI container.  Now on to the meat.

One of the central ideas in the FubuMVC.UI is that there are three kinds of elements were interested in.  Inputs, Labels, and Displays.  Inputs being any kind of element that allows you submit information, Labels being, well, labes and Displays being elements that display information.  Readonly information.  Labels are the easiest.  Once you know how you like to display your labels you can specify that concvention and largely be done with it.  Displays too can be pretty easy too but can get more complicated depending on what you want to display.  Inputs are the proverbial money shot.  That is where most of the cool stuff happens.

One of the first things you’ll need to do is create a set of conventions.  The idea is that you say ok whenever I specify a label ( e.g. Html.LabelFor(x=>x.FirstName) ) render it like this.  So for my convention I have

Labels.Always.BuildBy(req => new HtmlTag("label").Attr("for", req.Accessor.Name).Text(req.Accessor.FieldName.ToSeperateWordsFromPascalCase()));

So for labels always build using a “label” tag, set an attribute “for” equal to the name of the property and set the text of the label to the Property name and ( using a little extension method I build ) separate the words of the Property.  So my property was FIrstName.  it will render <label for=”FirstName” >First Name</label> . 

Similarly I do something for the display.

The fun happens with the InputFor.  To keep this simple I will show the very least that you will need for Input. 

Editors.IfPropertyIs<bool>().BuildBy(TagActionExpression.BuildCheckbox);

Editors.Always.BuildBy(TagActionExpression.BuildTextbox);

Here if you do something like this Html.InputFor(x=>x.IsReallyCool) you will get a checkbox since IsReallyCool is a bool.  and if you do basically anything else you will get a textbox.

So the final very bare minimum HtmlConvention file would like this

public class FlywheelHtmlConventions : HtmlConventionRegistry
    {
        public FlywheelHtmlConventions()
        {
            Editors.IfPropertyIs<bool>().BuildBy(TagActionExpression.BuildCheckbox);
                      Editors.Always.BuildBy(TagActionExpression.BuildTextbox);
            Displays.Always.BuildBy(req => new HtmlTag("span").Text(req.StringValue()));
            Labels.Always.BuildBy(req => new HtmlTag("label").Attr("for", req.Accessor.Name).Text(req.Accessor.FieldName.ToSeperateWordsFromPascalCase()));
        }

This is won’t take you very far but we can go over some more interesting conventions later.

Next

You will also need some extension methods that you will access the FubuMVC.UI with from the view.  Now here I chose to write the extension methods off the HtmlHelper despite the fact that it’s a big bloated pos.  I did this for a very important reason.  If you use partials you will need to be able to get information off the model from the view that called the partial from with in the partial.  So inside the partial your calling InputFor(blah).  You will know that blah is on the BlahViewModel, but you wont know that the BlahBlahBlahViewModel called that partial unless you dig around in the HtmlHelper.  More on this later. probably.

So here are the three extension methods you will need and a little helper method.

public static class FubuUIHtmlExtensions
   {
       private static ITagGenerator<T> GetGenerator<T>(HtmlHelper<T> helper, Expression<Func<T, object>> expression) where T : class
       {
           TagGenerator<T> generator = ServiceLocator.Current.GetInstance<ITagGenerator<T>>() as TagGenerator<T>;
           generator.Model = helper.ViewData.Model;
                     return generator;
       }

       public static HtmlTag InputFor<T>(this HtmlHelper<T> helper, Expression<Func<T, object>> expression) where T : class
       {
           ITagGenerator<T> generator = GetGenerator<T>(helper, expression);
           return generator.InputFor(expression);
       }
       public static HtmlTag LabelFor<T>(this HtmlHelper<T> helper, Expression<Func<T, object>> expression) where T : class
       {
           ITagGenerator<T> generator = GetGenerator<T>(helper, expression);
           HtmlTag tag = generator.LabelFor(expression);
           return tag;
       }

       public static HtmlTag DisplayFor<T>(this HtmlHelper<T> helper, Expression<Func<T, object>> expression) where T : class
       {
           ITagGenerator<T> generator = GetGenerator<T>(helper, expression);
           return generator.DisplayFor(expression);
       }

}

basically each of these is getting a TagGenerator and calling either input,label, or display on it.

The Generator method gets a TagGenator from the servicelocator( container ).  You then pass the instance of the viewmodel into the TagGenerator. Essentially the TagGenerator will read you conventions decide what to render and do so using the data in the Model.

The last step is to register some stuff with your container. 

First in your ContainerRegistry you should do as follows ( for structure map.  of windsor check out ryanohs post )

For<HtmlConventionRegistry>().Add<MYHtmlConventions>();
            For<IServiceLocator>().Singleton().Use(new StructureMapServiceLocator());
            For(typeof(ITagGenerator<>)).Use(typeof(TagGenerator<>));
            For<TagProfileLibrary>().Singleton();

Then after you call bootstrapper for Structuremap in the application.start you should call

            ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator());

            var library = ObjectFactory.Container.GetInstance<TagProfileLibrary>();
            var conventions = ObjectFactory.Container.GetAllInstances<HtmlConventionRegistry>();
            conventions.Each(library.ImportRegistry);

Here we set up the ServiceLocatorProvider. then we get an instance of the TagProfilerLiberary and an instance of our HtmlConventions and call Library.ImportRegistry on each of the conventions.

Now in our view we can do <%= Html.LabelFor(x=>x.FirstName) %>  <%= Html.InputFor(x=>x.FirstName) %> and get

<label for=”FirstName”>First Name</label><input type=”text” name=”FirstName” value=”Cannibal” ></input>

There.  I made it through.  This looks like total ass in my editor and I may need to figure out how to display code better and redo this post.  But in any case in future posts I will go over more useful conventions and some advanced stuff.

Friday, January 29, 2010

Post Classifications

Congealed Thoughts

I enjoy a  sort of steam of consciousness style post as it helps me gel my thoughts.  However, I can only imagine that it’s pretty annoying to read.  So I am going to start sub heading my posts with a classification.  So Stream of Consciousness for that type.  Perhaps Congealed Thoughts for my opinions and thoughts that have are more ready for the masses :).  and a third for explanatory posts, explaining certain technologies and such. I’ll have to come up with the heading for that when I actually write one.

Wednesday, January 27, 2010

My venture into OOP Javascript pt3: us an M? I think so.

The next issue that I’m struggling with is the idea of a model.  Do I want to break away from the dom completely.  An event is issued from the dom to the controller.  the controller could then query the dom for all the data it might need to process the call put it in a little viewmodel and pass that around to all the services that will eventually need to deal with this data to validate and persist etc.

Yes I do like this idea.  A clean break from dom for some clean javascript programming.  Fuck another massive re write.  I’m never gonna finish this shit.   Anyway,  there’s a certain voice in the back of my head wondering if there will be inefficiencies the further I get from what I’ve always though of as javascript programming and the more I impose my server side code patterns onto my client side programming.  But I guess I’ll blow that up later.

My venture into OOP Javascript pt2: MVC?

At this point I’ve tried to break out the code into classes that loosely mimic my MVC classes.  A view that deals with setting up the calendar onload with the proper dropdowns and so on, a controller that deals with the events or “actions” that come from the calendar, and various services. 

One immediate issue that comes up is that  while the calendar is the starting point, once you click on it you get a dialog box which is not unlike an entire new and mostly unrelated module that has all manner of view setup, events or “actions”, data, rules and services.  It’s almost like whenever an event or a time is clicked it the calendar controller should call a calendarEventController with it’s seperate view and data.  But then I wonder if every dialog box should have it’s own controller.  There could be several stages to creating an Event.  If the event is in the past you have to justify it.  That’s one dialogbox, then you get the regulare add/edit dialog, if it’s edit and recurring you have a new dialog asking if you want to change all future events or just this one. and so on. 

Ok so upon writing this it’s starting to make me think about fubumvc’s “controller-less actions”.  basically it does away with the idea of a proper controller and makes each action it’s own class.  This class references the view it wants to write to and the model it’ll use.  However, I’m not sure I want to use this pattern in Fubu, much less in my javascript code.  I mean views generally have several calls that are all related and if each call requires it’s own class/controller then things can get kind of dispersed.  Hmmm.

My venture into OOP Javascript pt1

So I’m trying to wrap my head around javascript programming.  Not so much jquery this or modify that, so much as full on client side functionality. 

I’m building a scheduling calendar using jquery.jqweek or something like that.  Basically looks like a google calendar.  But there is a great deal of functionality that I have to add in order for it to display correctly ( with the information I want displayed that is ) and for the adding and editing appointments.  A LOT of functionality.  So I’ve been struggling with the best way to organized my code and as it gets more organized I start seeing patterns that are familiar to my C# code, as well as patterns that are completely different.

My venture into OOP Javascript pt4 : Linear vs cyclical

Yet another issue that comes up is that ultimately you end up wanting to persist data and or retrieve data.  In server side code this is done synchronously.  You query the db and wait for the return.  In client side code, this is generally done via ajax.  which is, as per the a, asynchronously.

This completely disrupts the flow of the app.  Instead of a method calling for some data, receiving it, and then processing it, you have to create a method for processing the data, then pass that method into the call for the data ( to be used as the call back from the ajax call ).  This is kind of topsy turvy and makes things more linear.  Less circular.  Instead of having method calls nested in other method calls walking down a chain then back up the chain and ultimately returning home to the original caller, I do a little of that but ultimately do off on a branch never to return. 

I would very much like to find a way around that since it is completely counter to what I am used to, but more likely then not I will just have to create/find some patterns for understanding it and using it more efficiently.

See if I could bring it all home to the controller then I could have the controller be the only point of contact with the dom.   However if there are end points all over hell then the will each have to have contact with the dom . Or perhaps I could have a “dom touching service” where I keep all my end point code.  Hmmmm. again.

Thursday, January 21, 2010

RubyMine Rocks

RubyMine is the shit.  I don’t develop in ruby.  But I do do a lot of javascript.

As we all know Visual Studio is completely untenable for javascript. I know that you can down load this and install that and eventually it wont be a piece of shit, it’ll merely suck but I’ve tried and failed and couldn’t give a shit to try to man handler That app into doing it’s job.

In comes Jet Brains RubyMine.  Or at least into my life, It’s been around for a while.  Anyway, this app just further proves the point that Visual Studio is merely a shell for running Resharper.  I use RubyMine for my javascript and I get most if not all the wonderfulness that is Resharper.  I can click on function calls and be taken to the definition and vise versa, rename, refactor the whole nine yards.  It’s just awesome.  It even has great intellisense.  No longer do I feel like I’m developing in the dark.  Or worse that I have to use my brain to keep track of everything.   I don’t know about you but after the ‘70’s I need all that’s left of my brain for the important stuff. Logic and porn. 

One caveat is that RubyMine takes a little tweaking.  However, I have used several other javascript editors all of which required a ton of tweaking just to be usable and all in all seemed like big heavy unweildy messes.  RubyMine feels a lot cleaner, lighter and easier to manange, and once you get all your settings tweaked it’s just like writing C#. … Except for all the differences, but you know what I mean.

I am currently refining my settings daily and will post them here if anyone is interested. 

Also it costs $100.  So that kinda sucks but so does resharper and would you even consider developing with out that?

Tuesday, November 24, 2009

Find next specific day of week

It’s not cutting edge but it’s something I forget about every 6 months and have to look up or figure out again.  So here it is.  Also I’m not convinced that it is the best way so if anyone knows a better one feel free to let me know.

ok I have written a battery of tests changing both days around and this is the real deal.

public DateTime getNextSpecificDay(DateTime d1, DayOfWeek day)
        {
            var diff = day - d1.DayOfWeek;
            if(diff <= 0)
            {
                diff = diff + 7;
            }
            return d1.AddDays(diff);
        }

 

this will find the next sunday.  if you pass in a sunday it will find the next one not the current one.

Wednesday, September 9, 2009

FluentNHibernate 'urn:nhibernate-mapping-2.2' has invalid child element

Just a quick post for anyone who may be suffering with this error.  If you get an error that looks like this,

NHibernate.MappingException: (XmlDocument)(3,6): XML validation error: The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'property' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'urn:nhibernate-mapping-2.2'. --->

then there could be two causes for this depending on how you are configuring FNH.

If you are using FluentMapping which is to say you are explicitly mapping each class then you must map the ID Column differently then the rest of them.  I just upgraded from NH 1. something and it’s concurrent version of FNH and I had the following in my origional mapping  UseIdentityForKey(x=>x.Id, “id”). After upgrading I saw that the UseIdentityForKey no longer existed and having read that there is a convention for discovering the Id column I figured that I’d just map it the same as the other Map(x=>x.Id).  Well that was kind of silly and produced the above error.  So I changed it Id(x=>x.Id) and all was good.

The second case may be a bit more insidious.  If you are using Automapping, FNH will indeed discover your id columns for you.  Yay!  However, only if you have named then Id.  That’s capital I lower case d. If you have it all caps ( or for some reason all lower ) like ID then you will get the above error.

I posted this cuz I didn’t find any other posts on this error.  Which could mean that I’m sooo brilliant that no one has even thought of making the mistakes that I make.  There’s another interpretation which I’m sure you’ve already come up will so I will leave it un uttered.