MVC – Dealing with the Identity Column

I am following a MVC  introduction tutorial found here.  I have gone though it a couple of times and I am coming up to speed with the basics of MVC.  I found an interesting error though.  I created a controller called movie and then coded up the functions for the insertion of a movie record like this:

        public ActionResult Create()

        {

            return View();

        }

 

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Create(Movie movieToCreate)

        {

            if (ModelState.IsValid)

            {

                context.AddToMovieSet(movieToCreate);

                context.SaveChanges();

                return View(movieToCreate);

            }

            else

            {

                return View();

            }

        }

I then created a Unit Test to check my work like this (note the exclusion of the primary key):

        public void CreateTest()

        {

            MovieController target = new MovieController();

            Movie movieToCreate = new Movie();

            movieToCreate.Title = "AAA";

            movieToCreate.Director = "BBB";

            movieToCreate.DateReleased = DateTime.Now;

 

            ActionResult actual = target.Create(movieToCreate);

            Assert.IsNotNull(actual);

        }

 

Things worked great so I then created a View using the code generator (Right Click -> AddView) to create a data entry page.  I then deleted the ID field because it is an identity key in the database:

Unfortunately, when I ran it, I got a validation error:

So I added back the ID Field and placed in a dummy value:

And the data took!  Note the new ID number:

 

This illustrates my biggest problem with MVC so far – you need to rely almost exclusively on the Code Gen (and know the conventions) to get anything done and when things don’t work as expected, it is really hard to pinpoint the problem.

In this case, I found the error was that I didn’t tell the controller that the ID should not be bound.  I changed the signature of the Create Function to this

public ActionResult Create([Bind(Exclude="Id")]Movie movie)

and it worked like a charm

 

MVC

I started researching MVC this last week.  My 1st stop was the series of webcasts that are on the ASP.NET/MVC site.  For me, the best one so far has been the nerddiner.  I was surprised on how much of a convention curve there is for even a basic crud site: each controller having their own View folder, the index, Details, Edit, and Create for Gets and Posts.  Also, spending so much time in the HTML marketup seems to be a step backward. 

 

On the flip side, I love the prompt to add a test project when you create a new MVC project.  That is progress and shows how serious Microsoft has become about TDD techniques.  I have to believe there will be a mocking framework in the in the next release of VS (2013?).

 

 

Microsoft SDK

I went to install the most recent SDK on my development machine when I ran into this nugget on the install page.  Microsoft has 6 Billion in cash sitting around and they can cough up enough to make sure their SDKs don’t force a reinstall of VS2008?  The alternative does not include any of the speech SDK iteams.
<sigh>
 

MCPD 3.5 Enterprise

I passed the last of the 3.5 Upgrade exams today so I am officially a MCPD 3.5 Enterprise. 

 

Interestingly, the solution architecture part was fairly straight forward but the WCF piece was a real pain – they went into much more detail than I expected based on the study materials – they really want you to know exceptions (versus the rule).  Most of the scenarios they present I have not run across in the 5-6 WCF projects I have worked on in the last year or so.   Good luck to anyone else who takes it.

Up next?  I have the Swim Team Website (Dean is doing a great job with the MVC on it) so I can test a mocking framework and MVC & WCF/JSON.  Also, I have the RTOOT site I need to get back to.  Finally, there is this speech API with the phigits I have can’t wait to start.

Tune in next week for some code…

WCF Editor

I am wrapping up studying for my WCF Upgrade exam – I completed all of the labs in Microsoft learning and I am now building some Hello World projects to focus on specific areas for the exam.  I ran into an interesting problem.  I created a new solution with some class libaries in it and 1 console project to be my hosting application.  I did not used the WCF templates.  When I added an App.config to the Console applciation and right clicked on it, the WCF editor did not show up.  The project already had a System.ServiceModel reference.  I wonder what you need to do to have this editor show up in a project?  A quick glance through my solution and a parallel WCF-template generated solution did not reveal anything.
 
In related news to the labs – lab 6654 does not work because of SQL Server security permissions, 6659 does not work because of SQL Server security permissions (which is ok because that is the exception you are supposed to raise anyway), and 6658 does not work out of the box because they did not define the binding as duplex.  This can be fixed by changing the binding.
 
 

WCF Callback Functions

I am working though Lab 6658 for my 70-569 exam (due in January).  I am having a problem getting the Callback functions to work.  Granted there are more moving parts using a callback function that a request/response pattern, but I think I have isolated the problem.  The start kit that Microsoft provides does not use a Duplex Chanel – which I thought was necessary for callback functions.  I will investigate on my local machine.

Pragmatic Unit Tests

I am preparing a Slide Deck on Unit Testing for my employer’s .NET User Group.  The deck is pretty vanilla but it does help me crystallize my thoughts around dogmatic versus pragmatic unit tests.  The purist argues that the unit test should be in complete isolation – it has no dependencies across layers and, therefore, needs a mocking framework to be used correctly.  I take a more pragmatic approach – I am less worried about writing correct unit tests as much as writing effective unit tests.

I recently added some unit testing to a project for which I am tech lead.  We implemented some unit tests that call an API that, in turn, calls a lower layer.  The tests are clean and they are very effective at identifying problems when the code changes.  Interesting, even though the unit test depends on some data in a database – they have yet to fail because of that dependency.  It has failed for some failed logic introduced when refactoring though – proving the usefulness of the tests. If the tests do fail, the developers know that the error might be in the dependency and can investigate appropriately.

 I think this example points to the heart of the unit testing – you either take ownership and use them effectively as part of the way you code, or you don’t.  If you are in the former category, you can get away with dependencies in your unit tests.  If you are in the latter category, you shouldn’t even bother with unit tests at all – correctly formed or otherwise.

It All Comes Down To Infrastructure Redux

I was pulled into an IRT over the weekend.  A development team was moving their application from DEV to QA and experiencing an unexpected error.  They could not connect to the database from their web application.  Turns out they had two databases on the same server and they could connect to one using a connection string like this:

connectionString="Data Source=DIXON08;Initial Catalog=VideoGames;Integrated Security=True"

but not the other one.  After going through the typical algorithm  of ports open, impersonation set correctly, etc…, it was found that the connection string needed to fully qualify the server name and the port like this (I didn’t come up with the right answer, Rob Seder did):

connectionString="Data Source=Com.Tff.DIXON08:8001;Initial Catalog=VideoGames;Integrated Security=True"

Why it worked on one database without fully qualifying versus another that did need it, I don’t know.

Microsoft Labs – Some QA would help

I am getting ready  for Microsoft exam 70-569 by going through their on-line learning courses found here.  Last night, I did the lab for 6654.  Things were going great until the last step – where you actually call there WCF Service, which then makes a database call.  I received the following error:

Could not open database “Appointments” requested by login.  The login failed.  Login failed for user ‘LON-DEV/Student’

The problem is that the connection string is hard-coded into the supporting class that Microsoft provides and there is no other way to login.  I am surprised Microsoft didn’t QA their applications better.  I am also surprised that no one else hasn’t found this for Microsoft to fix…

Partial Page Post-Back and The Property Proxy Validator – CTD

As a quick follow-up to this post, I disabled the PropertyProxyValidator on the RowUpdating Event Handler of the other control and it worked fine

 

        protected void GridViewFamily_RowUpdating(object sender, GridViewUpdateEventArgs e)

        {

            PropertyProxyValidator propertyProxyValidator =

                GenericUtilities.FindAChildControl(this.DetailsViewInsertFamily, "PropertyProxyValidatorInsertPersonName") as PropertyProxyValidator;

            propertyProxyValidator.Enabled = false;

 

        }

 

FindaChildControl is a just a recursive method to find a control on a web page:

        public static Control FindAChildControl(Control control, string controlId)

        {

            Control targetControl = null;

            foreach (Control childControl in control.Controls)

            {

                if (childControl.ID == controlId)

                {

                    targetControl = childControl;

                }

                if (targetControl == null && childControl.Controls.Count > 0)

                {

                    targetControl = FindAChildControl(childControl, controlId);

                }

            }

            return targetControl;

        }

 

The fact that I have to do this is very annoying – it adds more code to the project, therefore increasing the cost to develop and maintain it.  I noticed that the out of the box ASP.NET validators do not have this problem – they only fire when the control that they are associated is updating/inserting…   I would argue that the Ent Lib validators need to add this feature.