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 ***