Thursday, June 18, 2015

AngularJS Protractor Error In Tutorial


AngularJS Protractor Error In Tutorial

 

In the tutorials if you attempt to execute npm run protractor to do end to end testing you may get an error on windows that states that that it cannot find the chromedriver.exe file. 

 

Two issues are likely to present itself

1.       Chromedriver.exe cannot be found

2.       Selenium server timeout

The issue I ran into that the chromedriver_2.16.zip file was downloaded but the chromedriver.exe was missing from the node_modules/protractor/selenium folder.

To correct this issue the do the following:

1.       Set chromeonly setting in package.json that is located in the node_modules/protractor folder.

2.       Execute the following commands

a.      NPM install webdriver-manager

b.      NPM uninstall protractor

c.       NPM install protractor

d.      NPM install

3.       The selenium folder is now in the webdriver-manager folder so copy this folder to the node_modules/protractor folder. It should have three files chromedriver.exe, chromedriver_2.16.zip, and selenium-server-standalone-2.46.0.jar

 

After doing this attempt to execute the end to end test by first starting the web server via npm start command in one command window.  In another command window run npm run protractor if it produces and error stating “there’s no selenium server jar at the specified location. Do you have the correct version?” perform the following steps.

1.       Open the package.json file located in node_modules/protractor/ folder.

2.       Change all entries in the file for selenium-webdriver and selenium to the correct version number which should be 2.46.0 (in my file it was code line 19 and 61)

3.       Then start the web server via npm start

4.       Run the end to end tests via npm run protractor


*** All Content is provided As Is ***

Thursday, April 10, 2014

Auto Generate Meta Data Classes for Data Annotations via MVCScaffolding.MetaDataPlugin

If you are like me, you like to separate the data annotations into separate meta data classes not only for Entity Framework but for my view models and other model classes.

The only pain of this is amount of tedious and repetitive code that has to be done to get it all wired up.  A fellow developer and myself were discussing this pain point and decided to utilized the power of MVC Scaffolding to create a T4 template that will stub out the very basics of the meta data class for a given model.

A day later and here we sit with a working NuGet package that does just this for any project.

http://www.nuget.org/packages/MVCScaffolding.MetaDataPlugin/

Instructions on how to use this package are in the readme.txt that will open upon install of the package.

For Example for the below class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ScaffoldingExample.Models
{
 
public partial class TestVM
  {
 
      public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Email { get; set; }
       public string Address1 { get; set; }
       public string Address2 { get; set; }
       public string City { get; set; }
       public string State { get; set; }
       public string Zip { get; set; }
  }

}
 


I would run the following command in the Package Management Console
PM> Scaffold MetadataClass TestVM

This will add TestVM.cs to the MetaDataClasses folder under the Models folder. (If these folders do not exist it will create them)

The following is the example file it generated:
//------------------------------------------------------------------------------
//
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// Date generated: 4/10/2014 4:44 PM
//
//------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace ScaffoldingExample.Models
{
      [MetadataType(typeof(TestVMMetadata))]
      public partial class TestVM
      {
      }
 
     
     
      public class TestVMMetadata
      {           
            public object FirstName { get; set; }
            public object LastName { get; set; }
            public object Email { get; set; }
            public object Address1 { get; set; }
            public object Address2 { get; set; }
            public object City { get; set; }
            public object State { get; set; }
            public object Zip { get; set; }
      }
}
 


There are a few important things to note
  1. Because this uses T4 Scaffolding you must successfully build the project so that the proper dll is referenced.
  2. If you work on the same project on multiple machines you will need to un-install and re-install the package so that they proper assembly and project paths are used in the T4 Template.  (you could manually modify the full path to the assemblies in the t4 template)
  3. It will only work on models that existing in the Project.Models namespace
Support for Areas (v1.0.6+)

To use this with areas simply specify the option -Area parameter.  If the above class was in the models folder of an area named "TestArea" the following would be the command to run in the Package Management Console:

PM> Scaffold MetadataClass TestVM -Area TestArea

Support for Custom Namespaces and Destination Folders and enhanced EF support (v1.1.0+)

If your project does not follow MVC conventions you can now specify the custom namespace via the Namespace parameter.  If you prefer to specify a custom output directory for the MetaDataClasses you can implement this via the Destination parameter.  The following is an example commmand to run in Package Management Console:

PM> Scaffold MetadataClass TestVM -Area TestArea -Namespace ScaffoldingExample.Models.TestVM -Destination MyMetaDataClasses

The Entity Framework enhancements in this version added filtering of the output to prevent the EntityState, EntityKey, EntityReference, EntityObject types from being output as generic object properties in the MetaDataClass.  This was not a breaking issue just a matter of keeping things nice and tidy.

Support of Required and Display Name Attributes (v2.0.0+)

Now adds the Required and friendly Display Name data annotation attributes for properties based upon camel casing and underscores for spacing between words.
I hope this helps save you some time!

Known Issues and Work Arounds:

  1. Null Reference Exception:
    1. Issue
      1. When using Entity Framework 5 or 6 the necessary entity framework reference is not added to the T4 template so a null reference exception is produced
    2. Work Around
      1. Add the following line as line 3 of the T4 Template making sure to have the correct path to the dll
      2. <#@ assembly name="c:\Projects\MyProject\bin\EntityFramework.dll" #>
      3. Make sure that any usuage of Entity.EntityState is strongly typed to System.Data.Entity.EntityState (should be line 55 after above line is added)
  2. The letters ID are being removed regardless of location in text.  For example: OverrideID becomes Overre
    1. Correction is coming soon but you can adjust the logic manually in the FormatPropertyName function in the t4 template. 
    2. The corrected logic is as follows and will included in the next version
if(str.Substring(str.Length -2,2).ToUpper() == "ID" && str.Length > 2)
{
str = str.Substring(0, str.Length -2).Replace("_"," " );
}

Next version will include corrections for all of these issues.  If you discover other issues please contact us and let us know so we can get them fixed.


*** All Content is provided As Is ***

Tuesday, January 14, 2014

RazorJS: The solution to using Razor in external JavaScript Files

If you are like me, I prefer to separate all JavaScript from the Views or Webpages. The difficulty in doing this is the lack of a method to use Razor Syntax to inject more fault tolerant urls, data and other Razor goodies. Yes, it can be achieved with out Razor by declaring the variables in a small JavaScript but I want complete separation not partial.

I did a little digging and found that there is a project called RazorJS. This project does exactly what I am looking to do with a few limitations. This project allows you to use the full Razor syntax with in the JavaScript and allows data models to be passed in so it can be references as part of the Razor. The limitations that I have found at the current moment is the lack of support for the ViewBag, ViewData, and TempData to be referenced in the Model. The solution is to add these to the strongly typed view model or as a dictionary.

For example of how to implement RazorJS and documentation refer to http://john.katsiotis.com/blog/razorjs---write-razor-inside-your-javascript-files

To install RazorJS via Nuget use Install-Package RazorJS. Details on the Nuget package can be found at http://www.nuget.org/packages/RazorJS/

*** All Content is provided As Is ***

Tuesday, September 24, 2013

Using jQuery to Post Data to an ASP.Net Web Forms Web Method via Model Binding

Scenario

I recently ran into a situation where I needed to use AJAX to call back to a traditional ASP.Net Webform's web method in the code behind for a quick lookup. There was a large number of values that were directly related to a model I was using. So, I decided to do this via model binding similarly to how ASP.Net MVC utilizes this same binding techniques for the post data, to keep from having to do the parameter to model translation and save myself some typing.

As a personal preference, I like to use JavaScript Object Notation (JSON) to populate the data being submitted to the server. This is just a personal preference because I feel the code is more readable and I have never been a big fan of string concatenations. I mention this because there is a needed work around for IE 8 or old due to the lack of native support for the JSON object. For more information please see http://blogs.msdn.com/b/ie/archive/2008/09/10/native-json-in-ie8.aspx

The Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Model
{
public partial class MyFormClass
{
public string Field1 { get; set; }
public string Field2 { get; set; }

}
}
The Form

In the code below you can see I have simplified the form to contain only a couple fields but this is just to condense the code posted. Also notice that that there are three JavaScript files used. jQuery, json2 to accommodate IE8 and older, and the page specific JavaScript file.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="WebApplication1.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Test</title>
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script src="Scripts/MyFormClassJavaScript.js" type="text/javascript"></script>

</head>

<body>

<form id="form1" runat="server">
<div>

Field 1 <asp:TextBox ID="txtField1" runat="server"></asp:TextBox>
<br />
Field 2 <input type="text" id="txtField2" /> <br />
<input type="button" onclick="DoWork()" title="Go" value="Go" />
</div>

</form>

</body>

</html>
The Web Method

In the code behind I have the following web method, as you can see I have a parameter named myFormClass of the same type as the model MyFormClass. This method doesn't have any major logic, just simply takes the submitted value throws it into a list and returns the list as a JSON string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using WebApplication1.Model;
using System.Web.Script.Serialization;

namespace WebApplication1
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public static string GetList(MyFormClass myFormClass)
{
//Using a list to show how lists can be returned instead of single objects
List myList = new List();

//just as the submitted value to the list, obviously this is where your business logic will be submitted.
myList.Add(myFormClass);

//used JavaScriptSerializer just for down and dirty method, there are better method of doing this.
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(myList);
}
}
}
The JavaScript

As you can see the javascript is just a simple function that uses the jQuery Ajax object to post to the web method. Something that you may not recognize is the data filter that is handling the d object that .Net is adding to the JSON object that I serialized. For more information about this data filter see http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/.

All I am doing with the return data object is looking through the array using the jQuery .each function and displaying in an alert window.

The key piece to notice is the JSON.Stringify function I used to create an object with the same name as the parameter of the web method, in this case myFormClass. The value of this object is another object that has two values named Field1 and Field2 which are set to the corresponding text boxes. These are name are extremely import and must match exactly, it is case sensitive, as the property in my model class.

function DoWork()
{
alert('I fired!');
$.ajax({
type: "POST",
url: "Test.aspx/GetList",
data: JSON.stringify({ myFormClass:
{
Field1: $('#txtField1').val(),
Field2: $('#txtField2').val()
}
}),
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
// This boils the response string down
// into a proper JavaScript Object().
var msg = eval('(' + data + ')');

// If the response has a ".d" top-level property,
// return what's below that instead.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
success: function (msg) {
// This will now output the same thing
// across any current version of .NET.
$.each(msg, function (key, data) {
alert('Field1: ' + data.Field1 + ' Field2: ' + data.Field2);
});
},
error:function( jqXHR, textStatus, errorThrown ){
alert(textStatus + " : " + errorThrown);
}
});

}
Conclusion

As you can see this is a really simple example but clearly outlines a quick and easy method to utilize model binding when submitting to a web method from a traditional ASP.Net web form.


*** All Content is provided As Is ***

Wednesday, June 5, 2013

How to properly submit an html form to MVC Action with model binding

Just like a view can submit data to an MVC action so can any external HTML forms and model binding can even be used allow for greater code re-usability of existing actions. This is helpful, for example, when you have a couple other sites that you would like to link back to your MVC site to take advantage existing functionality.

If you are familiar with MVC, you are probably already thinking this makes sense because views are just html. Even the helpers that are used in Razor or other syntax implementation, ultimately render as plain old html. So what are the gotchas and things to watch out for?

There are only a couple things that are extremely important and most of it has to do with the HTML form itself, and not so much on the controller action side of things.

First and most importantly the form must be configured to submit to the proper place and the correct method is being used.  When using the default routing configuration in MVC this would be the url/controller/action so something like http://www.mysite.com/mycontroller/myaction. Also make sure that if the action is decorated with the HttpPost attribute then set the method to "post" and likewise HttpGet attribute would be a form method of "get"

Now that the form will successfully submit to the proper action it is time to look at the input or select tags and make sure they have the proper id and name attributes.  I put the word "and" in bold because the model does not bind correctly if you do not have these both properly defined.  To define these properly make sure both the id and name attributes match the name of the parameter of the action or one of the property names of the model being used as the action parameter. For example if myAction had a parameter name "testParam" and "testParam2" then I would need two inputs with the id and name matching the "testParam" for one and "testParam2" for the other.

Example Form:
<form action="http://mycorrecturl/mycontroller/myaction" method="post">
<input id="testParam" name="testParam" type="text" />
<input id="testParam2" name="textParam2" type="hidden" value="junk" />
<input type="submit" title="Submit" />
</form>


Example Action
[HttpPost]
public ActionResult myAction(string testParam, string testParam2)
{
     //do something here
     return View();
}


There are other concerns that require time invested into understanding with MVC in general, like proper request filtering, authentication and other security concerns to ensure that your site and users are safeguarded. For more information about these topics I recommend reviewing Microsoft's MVC tutorial library at http://www.asp.net/mvc/tutorials as a good starting point.    

Tuesday, May 14, 2013

Why to switch from Android to Windows Phone

Switch to Windows Phone, Why?

I have been debating this myself for many weeks, as I have patiently waiting for my carrier, Verizon Wireless to offer the new phone models.  My main debate has been between the Samsung Galaxy S4 and the Nokia Lumia 928.
 
I am not going to go into the specifics about the hardware or vendor specific software, there are plenty of source for this type of information.  I am going to cover fundamental reasons why now is the time to switch to windows phone. 
 

Less carrier and manufacturer modifications

Windows Phone OS's core functionality is by design protected from manufacturer modifications.   This means while device manufactures and even wireless carriers like to add bloat ware and make other core system modifications to the Android's Open Source OS which can cause instability, battery drain, privacy concerns and additional security wholes.
 

Frequent updates, improved security

 
Unlike Android devices updates are not controlled by the cellular carrier, which from my experience are either up to a year past the current Android version, even then the devices only get one maybe two system updates to the operating system.  This is a major concern from my perspective because it means that any security flaws that are fixed in the newer releases are never going to make it my device unless I root it and void any warranty/support for the devices.
 
With Windows Phone the updates come from Microsoft, not the carrier or device manufacturer. No rooting require, no voiding the warranty or support agreements with the manufacturer or carrier.  These updates have been through the proper testing and Microsoft already has a great focus on security, case in point from the windows OS side is a little thing we like to refer to as "Patch Tuesday's".
 
Now Samsung recently was awarded a government contract for their knox software which is a vendor specific piece of software and again subject to carrier changes. But still good news for newer Samsung devices.
 

App market growing

If you expect to find every title that you had in Android, that is not going to happen.  This is a downside but as windows phone is gaining market share and the non-Microsoft ecosystem developers are discovering the easy of app development and fact that all web developer and windows 8 developer skill set cross all platforms there is a strong army of developers that are bringing new apps to the market every day.  I personally, have a couple apps that I am planning to write. 
 
Microsoft is aware of this as being one of the biggest hurdles to making the switch and they are addressing it as discuss in this Computer World article http://www.computerworld.com/s/article/9237836/Windows_8_app_store_growth_slows. 
 

#TimeToSwitch Android Application

Microsoft in an effort to make the transition easier has published an app to the Android market its called TimeToSwitch.  This app is designed gather what apps you have installed on your phone, save it and when you switch to windows phone it will help you find the same or similar apps in the windows store.  While the key phase in the last statement is same or similar I think there is room for improvement in this application to display the list of which will be same and which are similar a head of time, but hey this is a great start and much easier than the transition from one android device to another.
 

Easy contact migration

Since this uses the SkyDrive and your windows live account, guess what you want your contacts no biggie, log into http://www.outlook.com and important any contacts that you synced with Google or the other social media sites. 
 

Companion Applications for both Windows Phone and Windows 8

 One of the best features is that many of the applications your purchase (paid or free) for windows phone also have a windows 8 compatible version.  Who doesn't like a buy one get one? 
 

SkyDrive and Office Applications

Everyone windows phone comes with free space on SkyDrive, the Nokia Lumia series is stated as coming with 7gigs free.  This makes it really easy to access files from both your PC and on the via your phone or surface tablet.  Having used similar services like Drop Box for similar functionality in Android this was even simpler to setup and even easier to use.
 

Developer Perspective:


Modern UI (Metro) consistencies

The consistency of live tiles between windows phone, windows 8 is a nice change.  Also makes development and design easier which is great for me as a develop who lacks the skills to create amazing looking UI designs.


Its all just HTML5 (faster development) and JavaScript

That's right!  Web Developers and Windows Developers unite, we can draw on the same skill sets for developing for Web apps, Windows Phone, and Windows 8.  What I really like is that I can leverage any and all of the Web API's that I have built for my MVC sites for consumption in my windows phone apps and Windows 8, allowing me to greater code reusability.
 

You are going to pay me to publish apps, sign me up?

If you read the computer world article you will notice that they talk about pay developers to publish application to spur app market growth, well guess what that was just the extra motivation to get me started several app ideas I have been wanting to write. 
 

*** All Content is provided As Is ***

jQuery.noConflict() you smell like a stinky cheese!

So a little background

I was working on a project implementing a design into a project which included the html, graphics and a few javascript libraries and files. Upon initial investigation everything seem on par with what you would expect from a UI using jQuery and jQuery UI. I ran the provided files in the browser and everything seemed okay, no console errors in the browser debugger. It was using a few jQuery plugins that I have never used before but everything seemed to be displaying correctly except for the adGallery plugin, but I wrote that off to a minor error somewhere in the css or markup, knowing that if all else fails, I could easily implement a different plugin like PikaChoose to maintain the functionality.

Now to fix the adGallery

While integrating the design into the functional site I notice on of the javascript files it used jQuery.noConflict(). I didn't recognize this tag as I had never used it, but the jQuery library is pretty expansive and given no browser debugger error I wrote it off to my own lack of knowledge and moved on to trying to fix the adGallery. In Visual Studio, I reviewed the markup and css and both seemed inline with what the documentation was showing but when I ran it Visual Studio I would get an error stating adGallery is not a supported method or property. I did a little searching and nothing turned up about compatibility issues, so I chalked it up to conflict causing the jQuery library to not compile properly at run time. So I switched the markup, css and library out with PikaChoose and attempted to run in debug again.

Here is the smelly part

Unfortunately the error remained only stating that PikaChoose() is not a supported method or property. Having used this before I knew that it worked. This is when I noticed the jQuery.noConflict() a few lines above it, so on a whim I moved my instantiation code above this line and everything ran okay in debug. So I removed this line of code and a new error came light stating that Method of Property 'msie' was not found or null. Turns out that this error was related an incompatibility between jQuery 1.9.1 and jQuery UI 1.8.11.

So what is jQuery.noConflict() used for?

jQuery.noConflict() relinquished the control of the $ object. This would mean that any errors would not show in the debugger because the $ object would be empty or null. For more information on the proper usuage of jQuery.noConflict() check out the API Documentation at http://api.jquery.com/jQuery.noConflict/

In summary if you ever see jQuery.noConflict() make it is truly being used for its intended purpose.

*** All Content is provided As Is ***

Monday, May 6, 2013

CoAuthoring a new NuGet Package csharp.Extensions

A fellow developer and I have decided to coauthor a NuGet package to help us from having to constantly added the same extension methods to our projects.  This project is called csharp.Extensions.  Available at https://nuget.org/packages/csharp.Extensions/

These extension methods allow for quick expansion of the base csharp types including common functions such as converting a comma separated string into a list, or converting a nullable datetime to a non nullable datetime.  We have not compiled the code based because we encourage you to use them and extend them as necessary.

If there is an extension method missing and you would like to added please let us know.  To use in NuGet Package Manager Console type install-package csharp.Extensions.

I hope this helps save you some time and if you have any questions don't hesitate to ask.

*** All Content is provided As Is ***

Wednesday, July 20, 2011

Glimpse from NuGet

Some of you by already know the wonders of Glimpse for ASP.net and the newer released Glimpse for MVC.  If you are not familar with this product I recommend that you check out the products website for more details.  (http://getglimpse.com/)

I have recently been exposed to the wonders of Glimpse for MVC which the route detections, strongly typed entity inspections client side, and other various tools is hugely helpful in diagnosing what is happening within the views which you typcially do not have a lot of inspection options related to entities.

But I will give you a tip about this product and beware of a few issues.

I am a big fan of Lazy Loading for Entity Framework 4 really enjoy the simplistic nature of the syntax that allows for faster development with greater emphases on business logic versus lines of code.  So the biggest issue I have ran into is when children entities of children entities are lazy loaded and you have glimpse turned on for the site, a referenced entity has been disposed run time error will be generated.  Simply turn off Glimpse and issue will disappear. 

Given that Glimpse is currently in beta, I look forward to the polished product that will take these issues into account.  But for being in Beta, it is truely a great utility even with the few bugs that are in the product.

*** All Content is provided As Is ***

Using Extension Methods in MVC

As many .Net developers have learned extension methods provide a mechanism to quickly add on capabilities to existing data types and methods.  If you are unfamilar with Extension Methods, Microsoft provides a great tutorial and documentation via MSDN (http://msdn.microsoft.com/en-us/library/bb383977.aspx). 

This particular post is related to utilizing these methods within MVC and the necessary work around for them to work with in your code.

Setup:

  1. Create your extension method as normal, and put your Class in a folder you created to house your extensions (typically done in the App_Code folder in ASP.Net web apps - this is not a folder that is an available system folder for MVC)
  2. Perform a build via the build menu or CTRL+SHIFT+ B
  3. Attempt to add the Using statement to the top of controller, data model, or class.
Why is my namespace not showing up?

Well, this is because in MVC by default the class is added with a build action of "Content".  This means that when you build the application it did not compile your extension method class.

So how do you fix this?

This actually extremely easy via the following:
  1. Right click on the extensions class file you created
  2. Select Properties
  3. The first option in properties window is Build Action
  4. Select Compile from the drop down
  5. Build the application
Your extension methods namespace should now be available to reference in any of the other classes, controllers, data models via the Using statement. From then on within that particular class you can use your extension method as normal.

*** All Content is provided As Is ***

The Conversion of a datetime2 Data Type to a datetime Data Type Resulted In an Out of Range Value

This particular error was produced when using Entity Framework where the edmx is generated from a SQL Server 2008 database.  This particular issue was rather nerve racking giving that I was providing the property of the Entity that a DateTime.Now value.  Which works perfectly in other areas of the application, as expected.

Background:

There was two tables in question, TableOne has a non-nullable foreign key constraint to the primary key field of TableTwo.  This is highly common and not something that is an issue, obviously the record in TableTwo had already been created and the ID was being supplied to the TableOnes entity.  So when attempting to perform db.TableOnes.AddObject(tableone) and calling the db.SaveChanges() produced the following error "The Conversion of a datetime2 data type to a datetime datetype resulted in an out of range value." 

Diagnosis:

I verified through stepping through the code and inspecting the entity that the value being supplied for the only datetime property of the tableone entity was a valid datetime.  I attempted dropping the TableOne entity from the edmx and re-adding it.  Only to still produce the same error.  Given that the inner exception message was being provided from SQL Server, I decided to inspect the sql statement that entity framework was passing to the database since, the emdx has no datetime2 mappings for any of the tables to entities. 

Side Note:
To inspect the sql statements use SQL Profiler - a good tutorial and information is provided at http://blog.sqlauthority.com/2009/08/03/sql-server-introduction-to-sql-server-2008-profiler-2/

Upon executing the same action that produced the errors, I found that it was actually attempting to execute an insert statement for TableTwo instead of insert for TableOne.  Obviously, this means that there was an issue with the edmx file, and something is mapping correctly.

I inspected the mappings for both TableOne and TableTwo and did not see any incorrect mappings either in the designer view or via opening the edmx as an xml file.

Resolution/Workaround:

As a last ditch effort since the deletion and re-addition of the TableOne to the edmx did not resolve the issue and the sql statement was trying to execute against TableTwo, I decided to try deleting and re-adding TableTwo.  This caused any mappings to get regenerated which solved the issue and everything saved properly with no conversion errors of datetime2 to datetime.

*** All Content is provided As Is ***

Monday, July 11, 2011

Mini Profiler for MVC

So a collegue of mine, sent me this little gem my way so I want to share it with everyone.

Given that slow downs in MVC can be hard to diagnose if its an issue with a route, database connection, or even a little JQuery script the team at Stack Overflow create this highly useful utility for all to use called MVC-Mini_Profiler. 

The Pros:
  1. Collects stats for MVC Routes, Database connections, and JQuery posts
  2. Has a strong group backing the utility in terms of future enhancements/compatibilities
  3. Simple and easy to understand statics
  4. Can be implemented at most levels of the application including even down to the individual lines of code.
The Cons:
  1. Can be a little tricky to get working
  2. Displays statics only on the page that you have setup profiling
  3. On or off situation configured in application_beginrequest and application_endrequest

For best implementations I can clearly see the benefit for using this as part of the UAT and performance monitoring. But not necessarly something that would I leave in the application for production unless only certain accounts are given this feature as it over shadows the underlying application.

For more information and detailed usage instructions check it out at http://code.google.com/p/mvc-mini-profiler/.

*** All Content is provided As Is ***

Thursday, July 7, 2011

An Item with the same key already exists

So you are probably thinking what I was thinking.  Thanks, that error is amazingly descriptive.

We all know that this is typically what you would expect to see this if you were using a dictionary and tried to add an already existing item with the same key.  But wait this is MVC3 and all I am trying to do is add a controller.  I have no control over the dictionary that MVCScaffolding (T4) MVC Tooling is using behind the scenes, what do I do now?

Well let me give you some tips on how to diagnose what the issue is and how it came about.  First let me say I have only ran into this when I used Entity Framework that is generated from a database.  The particular database was a newly created database with a couple hundred tables.  The build was at all times successful even though the root cause was related to foreign key constraints in the database.  But let me describe what steps I took to diagnose the issue and determine the resolution.

Background Info:
The controller and associated views I was trying to create were specific to entities located in my edmx file.  I had no business requirements for the particular entities that required a view model so I was building directly from the entity framework generated data context. The MVC3 application would build correctly with no warnings or errors, and I was able to update the entity framework model from the database with no warnings or errors as well.

So what exactly was the problem?
  1. One of the entities had a duplicate foreign key, which I confirmed was defined this way in the database as well.  
  2. Another entity seemed normal and there was no duplication of any key constraints.  But one of the foreign keys was created backwards, meaning that the primary key table was actually the foreign key table and vice versa.
  3. Another entity that caused the issue was due to the fact that the primary key in the one of the constraints was correct but the foreign key was actually pointed to the identity column of the foreign key table.
So how did I discover these were the actual issues?
  1. I removed the entities from the edmx with out deleting them out of the context.store 
    1. This is done by right clicking on the entity
    2. Selecting delete
    3. But when the pop up comes up saying do you with to delete them choosing no.
  2. I then attempted a build knowing that it would throw errors.
  3. When I reviewed the errors I found the duplicate key entry issue, but for the other two issues I was not so lucky to find such an easy to fix mistake as the errors simply stated missing table reference.
After I found the issue I made the correction in the database and updated the model from the database.

Awesome, it will work now ... NOPE!

I wish it were that simple.  Instead, I had to remove the entities from the context.store and then re-add them to the edmx.  For issues 2 and 3, I actually had to fully delete both the affected entity and the related entity that was part of the foreign key constraint from the edmx and add them again.  Fortunately this does not really affect any controllers, views or view models that you have already built unless you ended up renaming a field in the entities.  But you would run into this issue any time you rename a field in an entity.

I hope this help with the dreaded "An item with the same key has already been added" error from MVC3 when attempting to add a controller.

***** UPDATE Mon, Jul 11, 2011 at 9:48 AM *****


Steve Sanderson, Program Manager for .Net Stack at Microsoft has informed me that this issue is related to the MVC Tooling in VS 2010 and has been added to the bug list to be fixed.

*** All Content is provided As Is ***

Tuesday, September 1, 2009

Welcome

Since this is the first post, I feel that it is important to explain the purpose of this blog and several of the topics that I plan to have in the upcoming weeks. 

Firstly,  I plan to discuss the various .Net development situations that I have caused me either some time to research or write custom controls to meet the needs of the applications that I have developed.  Topics will range from Ajax, CSS, MySQL, MSSQL, VB.net, RDLC, IIS configuration issues, and features and pratices that have helped to make my code more efficient and easier to debug when the need has arrised.

Some of the up coming articles that I am planning of posting are as follows:
  • Custom Tree View Control with buttons using images for better look and feel.
  • Multiple file upload with drag and drop capabilities using Open Source Java Applets.
  • How to inject custom variables into MySQL queries used in RDLC's and the  Report View control for windows and web.
  • Centralized function for database queries using MS SQL data client and parameterized queries.
  • Usage of System.net.mail to provide better emails with embedded images for HTML and Plain Text views
  • Explination of my preference for usage of DataSets over DataReaders
Of course since I will provide my code as a resource for other developers that are facing the same obsticles as I have, but I request that any comments posted please be respectful and I will response to anyone that needs clarification.

Thanks for taking the time to read my blog and I hope that it will continue to provide resources to you that will be of help and increase your knowledge along the way.

*** All Content Is Provided As Is ***