Docker - A New Way To Think Virtual But Not Be Virtual
I've had success setting this up on Windows and a Mac, both of which use a tool called boot2docker. Since Docker only runs on Linux systems, both Windows and Mac need to use Virtual Box to spin up a Linux machine that can host Docker. For Windows check out https://docs.docker.com/installation/windows/ and for Mac see https://docs.docker.com/installation/mac/. I had a little trouble at first on Windows, which required deleting the VM on disk then re-initializing docker. After they are up and running, it's a breeze getting a container started, just type "docker run container name". It's that simple. Of course, if you want your container to expose ports and do other things there's a little more to it, but if you want to test out Linux based products, this is a very slick way to do it. To see a list of docker supported containers go to https://registry.hub.docker.com/. Pluralsight also has some good modules on how to use docker.
Sass CSS with Compass using Grunt Not Working on Windows
My team is using AngularJS, Node.js, Grunt, Sass CSS via Compass, Yoeman, and a few other web toolsets. The other day when running the serve process to generate the css output from Sass CSS, the css wasn’t able to generate. It turned out that Compass was setting the permissions on the .tmp folder where it puts the CSS to a state that didn’t all the process to write the file, hence a Permission Denied error. To fix this issue I followed the StackOverflow thread http://stackoverflow.com/questions/22596760/yeoman-error-errnoeacces-on-line-897-of-c-permission-denied which did these steps.
Open a command prompt and run the following.
- gem uninstall sass (if you have multiple version, select all)
- gem uninstall compass
- gem install compass --pre
- gem install sass --pre
Setting Up PhoneGap/Cordova for Visual Studio
It’s always a struggle to find time to invest in side projects when you work and play an active role in your kids lives. I appreciate when installing tools is just simple and you don’t have to google “why doesn’t …. do …” or “where is…” because the instructions aren’t straight forward or are missing steps/pieces. I found this the case with the latest phonegap instructions as of 2014-3-9.
- Install Windows SDK. I’m using Windows 7.1 because I have a Win7 machine, I found SDK here. This installed Visual Studio 2010 Express for Windows Phone (VS2010).
- Download PhoneGap SDK and unzip in C:\Tools. PhoneGap SDK is on github here.
- In the C:\Tools\phonegap-master (you might have to drill down a bit) there will be a lib folder, and in it there are folders for the different target frameworks one of which is “windows-phone”. As of recent the Visual Studio template .zip is not there. I had to run a batch filed called “createTemplates.bat” which created templates for WP8 and WP7.
- Once you have the Visual Studio .zip file template(s), copy those to your \Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C#.
- Open VS2010 and create a new project. You will now see a project template as shown below. The template name may change at some point.
The project structure will look like the following.
- cordova – build tools
- cordovalib – code for browser engine interaction
- www – folder for html/js/css of your app
- plugins – plugins for interfaces on your phone (i.e. camera, contacts)
Installing Node.js and Other Packages
Keeping up with technology can be a job in itself. Learning is fun, but is quickly forgotten so writing things down can always save you time later. This thread goes over various was of installing Node.js and other packages.
Installing Node.js
There are 2 ways in which you can install Node.js. Node.js comes with node package manager now so it will not need to be installed independently.
Installer (recommended): Go to node.js.org and use the installer for your OS. Run the installer.
Homebrew (Mac only): Run the command “brew install node”. You will have to have homebrew installed.
Other Node packages t
Installation will use node package manager. You can list the node modules for your node application by listing the directory of “node_modules”.
Express – web application framework for node
npm install -g express --save
NOTE: once you create a application with express (i.e. express AppName) you will have to navigate to AppName folder and run the command “npm install” to install the components defined in node’s package.json.
Yeoman – front end tool focused on scaffolding (yo), building/testing (grunt), and dependency management (bower)
npm install -g yo --save
npm install -g generator-webapp --save
coffee-script – scripting language that builds down to javascript.
npm install coffe-script --save
node-dev – a tool for node that will monitory files and auto restart the node app when a file has changed.
npm install node-dev –save
NOTE: When using this you will want to separate development dependencies from production ones. In the package.json, you can create a “devDependencies” like so:
{
"name": "application-name",
...,
"dependencies": {
"express": "2.5.8",...
},
"devDependencies": {
"node-dev": "~0.2.2"
}
}
mocha – javascript test framework for node
npm install mocha –save
NOTE: put this in your dev dependencies
REQUIRES: request
request – modeule that simplifies the process of making http calls
npm install requets --save
Redis – open source advanced key-value store
npm install redis hiredis connect-redis --save
REQUIRES: Installation of Redis backend. On a Mac use homebew “brew install redis”, Windows see redis.io.
connect-assets – transparent file compilation and dependency management for Node’s connect framework
npm install connect-assets --save
socket-io – simplifies the use of IO on all browsers. See WebSockets for information on this topic.
npm install socket-io --save
AngularJS – front end web application framework dealing with models, views, collections, and events
npm install angular --save
Backbone – front end structured for web applications dealing with models, views, collections, and events
npm install backbone --save
RELATED: Marionettejs (npm install backbone.marionette --save)
Mocking ASP.NET MVC HttpConext and Sessions
Unit testing ASP.NET MVC controllers can be difficult when you start to use the HttpContext and Session state. The following snippet of code will allow you to mock, using the Moq framework, the HttpContext properties. Add this to your test project.
using System.Collections.Generic;
using System.Web;
using Moq;
using System.Collections.Specialized;
using System.Web.Routing;
using System.Web.Mvc;
namespace WebBackOffice.Tests
{
public class ContextMocks
{
public Mock<HttpContextBase> HttpContext { get; private set; }
public Mock<HttpRequestBase> Request { get; private set; }
public Mock<HttpResponseBase> Response { get; private set; }
public RouteData RouteData { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ContextMocks"/> class.
/// </summary>
/// <param name="controller">The controller to add mock context to.</param>
public ContextMocks(Controller controller)
{
// define all the common context objects, plus relationsips between them
HttpContext = new Mock<HttpContextBase>();
Request = new Mock<HttpRequestBase>();
Response = new Mock<HttpResponseBase>();
RouteData = new RouteData();
HttpContext.Setup(m => m.Request).Returns(Request.Object);
HttpContext.Setup(m => m.Response).Returns(Response.Object);
HttpContext.Setup(m => m.Session).Returns(new FakeSessionState());
Request.Setup(m => m.Cookies).Returns(new HttpCookieCollection());
Request.Setup(m => m.QueryString).Returns(new NameValueCollection());
Request.Setup(m => m.Form).Returns(new NameValueCollection());
Response.Setup(m => m.Cookies).Returns(new HttpCookieCollection());
// apply the mock context to the supplied controller instance
RequestContext rc = new RequestContext(HttpContext.Object, new RouteData());
controller.ControllerContext = new ControllerContext(rc, controller);
}
/// <summary>
/// Sets the ajax request header so that mocked HttpRequest shows as a ajax call.
/// </summary>
public void SetAjaxRequestHeader()
{
Request.Setup(f => f["X-Requested-With"])
.Returns("XMLHttpRequest");
}
private class FakeSessionState : HttpSessionStateBase
{
Dictionary<string, object> _items = new Dictionary<string, object>();
public override object this[string name]
{
get
{
return _items.ContainsKey(name) ? _items[name] : null;
}
set
{
_items[name] = value;
}
}
}
}
}
Below is an example of using this in a unit test, based on nunit test framework. During the setup, create the ContextMock and associated with the controller under test.
namespace MySite.Tests
{
public class AccountControllerTests
{
private MyAccountController myAccountController;
private ContextMocks contextMock;
private Mock<IAccountService> accountServiceMock;
[SetUp]
public void Setup()
{
// create new controller under test
myAccountController = new MyAccountController();
// create mock HttpContext
contextMock = new ContextMocks(myAccountController);
accountServiceMock = new Mock<IAccountService>();
myAccountController.AccountService = accountServiceMock.Object;
}
[TearDown]
public void Cleanup()
{
myAccountController = null;
contextMock = null;
accountServiceMock = null;
}
[Test]
public void SignUp_AjaxRequest_Returns_JsonResult()
{
// arrange
string email = "test@test.com";
string password = "Some#rei!23";
// configure ajax mock request
contextMock.SetAjaxRequestHeader();
accountServiceMock.Setup(f => f.CreateAccount(It.IsAny<string>(), It.IsAny<string>()))
.Returns(new SignUpResponse(SignUpResponse.ReturnCodeType.Success));
// act
ActionResult actual = myAccountController.SignUp(email, password);
// assert
Assert.IsInstanceOf<JsonResult>(actual);
}
}
}
Alter Visual Studio Template Files
Out of the box, I’ve found Visual Studio template files to be just fine. Recently I was doing some researching into using StyleCop so I installed in on my machine. Little did I know, it went behind the scenes and altered some if now all template files. In particular, I don’t care for their Interface and Class file templates, I tend to use ReSharper and GhostDoc to do cleanup and documentation. If you want to change or revert your templates, your in luck, Visual Studio has backups. Follow the steps below to restore whatever templates you need to. In the example I will be restoring the C# class file for Visual Studio 2010 (10.0).
1. Go to the template folder you desire. You will find the templates in the Program Files folder (Program Files (x86) on 64 bit system) and the particular version here C:\Program Files\Microsoft Visual Studio {Version of VS, 10.0, 9.0…}\Common7\IDE\ItemTemplates. In the case of the C# class you will have to drill down into \CSharp\Code\1033\ folder, and in there you will find a file called Class.zip.bak. Delete the existing Class.zip file, copy the Class.zip.bak and rename it to Class.zip. Do this process for any other templates you wish to revert.
2. Reset the IDE environment. Open a Visual Studio command prompt (I do it in administrator mode on Windows 7). It’s found in All Programs^Microsoft Visual Studio {Version 2010, 2008,…}^Visual Studio Tools. Once the command windows is open run “devenv /setup” and you’re all set!
Things I Keep In My Toolbox
This thread is my ongoing attempt to remind myself of the tools I keep somewhere in my toolbox.
IDE Tools
- Visual Studio
- Eclipse
- Xamarin Studio (Mono IDE)
- WebStorm (javascript IDE)
- NUnit
- Android SDK
- Expresso Regular Expression Tool
- MOQ .Net Mocking
- SQL Management Studio
- SQL Compact Edition
Web
Cryptography
Design Tools
Development Other
- Visual Studio Power Tools
- TFS Global Alerts
- Team Explorer Everywhere (Eclipse plugin)
- XCaptcha
- Google reCAPTCHA
- TortoiseSVN
- Fiddler
Windows General Tools
- Virtual Clone Drive
- 7-Zip
- PuTTY Telnet/SSH Tool
- Filezilla (client and server)
- xmarks
- LastPass
- Digsby IM Chat Client
- Notepadd++
- Windows Live
- Greenshot
Mac General Tools
Debugging in Visual Studio and Eclipse, Hotkey Consistency
Most developers become accustom to hotkeys and shortcut key strokes. I, for one, cannot live without them, but there is one thing that drives me crazy and that’s debugging with different key bindings between Visual Studio and Eclipse. I’ll have to admit, that I should probably keeps with the Eclipse key bindings when it comes to debugging, but I’ve grown custom to Visual Studios F5, F10, F11. To make my life a pleasant one, I like to modify Eclipse’s key binding when it comes to debugging. Follow the step below to achieve just this.
1. Open Eclipse and go to Window^Preferences. Select the section General->Keys. I like to sort the items by Binding so that the ones to modify are all clumped together.
2. Modify the following items show in the diagram below. Unbind the Refresh for “When=In Windows”, otherwise two operations will be bound to F5.
If you want to go the other way around and modify Visual Studio, then open Visual Studio and navigate to Tools^Options. Select section Environment->Keyboard.
Printing HTML Landscape Using Print CSS File
I think one of the hidden gems of web applications is that you can mold your page for printing using a specific CSS file or printing. I wrote post a while back Printable Web Page which covered using the CSS media attribute for your <link> reference. The other day I was working on some reports that had some table cut off issues. I discovered there are a couple approaches that you can take, including using fixed width (though you’d need to know your printer widths) or using landscape and percents for tables. I chose to do the later.
If you add the following to your CSS file used from printing, it will default the users printing to Landscape and remove the margins. I set by tables to use a width of 100% or less to fit on the screen.
@page {
size:landscape;
margin:0;
}
Printable Web Page
Ever wonder how to make your unnecessary page elements disappear only to leave a perfectly printable web page? Using the stylesheet link’s media attribute can do the trick. Below describes how to utilize this media stylesheet to hide specific elements within your page. One of the keys to remember is that when your presenting mostly readable text, you want to stick to black and white with possibly red or blue links to let the user know certain text represented hyperlinks.
1. First thing to do is to define a css file to hold or media printing specific css. Let’s call it pring.css.
2. Add the following reference to the head section of your html document.
<link href="/Styles/Print.css" type="text/css" media="print" rel="stylesheet" />
3. Define the core css classed that drive most of you page. Below shows the core css classes we will use. The class “nonprintable” will be applied to any element that should not be shown on the printed page. Sometimes you will need to force certain css styles so you can use a “printable” class for this purpose. Applying black and white to the body of the html document is the cleanest way to obtain a slick page. Notice that “a” links get a red color and a transparent background; this helps the user realize the text was a hyperlink and prevent any a link’s background images from showing up.
/* GENERAL */
.nonprintable
{
display:none;
}
/* apply to specific items that must be forced */
.printable
{
background:white !important;
color:Black !important;
}
body
{
background:white;
color:Black;
}
/* A links */
a:link, a:visited
{
color:Red;
background: transparent;
font-weight: bold;
text-decoration: underline;
}
/* END GENERAL */
/*
asp.net ajax tab control
*/
.ajax__tab_header, .ajax__tab_outer, .ajax__tab_inner
{
display:none;
visibility:hidden;
}
.ajax__tab_body
{
border-color:White;
visibility:hidden;
}
5. Now apply css to elements within your document. Menu’s, images, ads, and other content that you don’t want to print should get the “nonprintable” class. This class will be assigned to the element but will not take affect until the user goes to print the page. Try it by applying some css and doing a print preview. This is a clever way of verify that the page looks correct without actually printing.
ASP.NET MVC Html Helpers Not Using Updated Model Values
If you’re using the Html helpers with the naming convention TypeNameFor (Func<>…) or the TypeName (string name,…), like TextBoxFor or TextBox, you might find some odd behavior when you post back form data to the controller, update your model, and send the model back to the view. I was pulling teeth trying to figure out why certain input text boxes and drop down lists were not being set to the values I had in the model.
Problem: ASP.NET MVC uses the post back data to set any drop down lists, text boxes, hidden fields, etc. before it uses a particular model’s values. Let’s say you have the simple model below.
public class Car {
public Manufacturer Make {get;set;}
public string Color {get;set;}
}
In your view you are trying to use the “For” Html helper methods to display the car’s color input, your markup would be:
<% using (Html.BeginForm()) { %>
...
<%=Html.LabelFor(m => m.Color)%>
<%=Html.TextBoxFor(m => m.Color)%>
...
<% } %>
In the simplest cases, this works very well because it automatically binds the value to you model if you use automatic binding (i.e. you post method takes an instance of Car) or manually bind with TryUpdateModel<T>. A problem arises when you post back, modify the model value, in our case Color, and re-show the form. This sort of scenario can arise when you have an add form that once the user is done adding one record, you send them back to the add form with new defaults so they can add another record. Below shows the simple controller and UI flow that will do this.
public CarsController : Controller {
[HttpGet]
public ActionResult Add() {
// our default we want
Car car = new Car {
Color = "Hot Sexy Pink"
};
return View(car); // return the model we want displayed
}
[HttpPost]
public ActionResult Add(Car car) {
try {
carDao.MakePersistent(car);
return Add(); // once saved, return user to add another
} catch {...}
}
}
2. You change the value to the color you want.
3. You submit the form, car is saved and controller returns you back to the add form to enter another car, but this time the default is incorrect, well from what you want it to be! It still shows “Firey Red” for the color when the default should be “Hot Sexy Pink”, because the Add() controller method creates a new Car instance, set’s the Color value, and passes it back to the view.
The framework is setting the color input with the forms posted values (ModelState key’s values) and not the model value (car in our case) that you are passing to your view. I can understand this because it’s the sticky form concept which is very useful, but not in this kind of scenario. You want it to be set to your defaults.
Solution: Clear the ModelState before redisplaying the form. Since the helpers are using the ModelState key’s values, you can make a call to ModelState.Clear() to clear out the posted values. If clearing all the values is not an option, you will have to set the keys to the desired default values. Below shows a modification to our view and controller code that will fix our situation. In the controller I’ve left a bunch a code out for brevity, like validation and error handling, but the idea is if the save is successful, clear the ModelState, and return user to a new add form with correct defaults.
<% using (Html.BeginForm()) { %>
...
<%=Html.LabelFor(m => m.Color)%>
<%=Html.TextBoxFor(m => m.Color)%>
OR
<label>Car color:</label>
<%=Html.TextBox("Color", Model.Color)%>
...
<% } %>
public CarsController : Controller {
[HttpPost]
public ActionResult Add(Car car) {
try {
carDao.MakePersistent(car);
ModelState.Clear(); // clear model state so new add form will not have old posted data
return Add(); // once saved, return user to add another
} catch {...}
}
}
ASP.NET MVC Html.DropDownList Not Showing Selected Value
I’ll have to admit, this is one of the only unfortunate nuances that I’ve come across in the ASP.NET MVC framework.
Problem: You’re using the Html.DropDownList, it’s name property is the same as your model’s property name, you pass a SelectList with you selected value, but in the UI it’s not showing your expected selection. The reason behind this problem is that ASP.NET MVC first looks for a match between the name of the drop down and a property on the model. If there’s a match, the selected value of the SelectList is overridden and no value is selected. This can be annoying. Here is our example, which is as simple as I can get it without loosing the meaning.
// models
public class CarRegistration {
public string CountryCode {get;set;} // iso 2 char code
}
public class Car {
public CarRegistration Registration {get;set;}
public string Color {get;set;}
}
public CarsController : Controller {
[HttpGet]
public ActionResult Edit(string vin) {
Car car = carsDao.FindByVin(vin);
ViewData["countries"] = new SelectList(
contriesDao.List(), // list of countries for select list
"Code", // select value attribute
"CountryName", // select text display
car.Registration.CountryCode); // selected value
return View(car);
}
}
<%= Html.DropDownList("Registration.CountryCode", (IEnumerable<SelectListItem>)ViewData["countries"]) %>
Lets pretend our registration country for some car is DE, or Germany. Your SelectList will have a internal list of SeletListItem’s that should produce the following in the rendered view. Instead, of rendering what is show below, you get a select list of countries without any options that have the selected attribute set.
<select id="Registration_CountryCode" name="Registration.CountryCode">
...
<option value="GE">Georgia</option>
<option value="DE" selected="selected">Germany</option>
<option value="GH">Ghana</option>
...
</select>
Solution: The solution to this issue lies within the name of the drop down list. Changing the name to not match the model’s property name will correctly render the drop down with the selected value. So change our view to the following corrects the problem.
<%= Html.DropDownList("countryCode", (IEnumerable<SelectListItem>)ViewData["countries"]) %>
The downside to this is that you cannot rely on model binding and have to pick this value out manually.
...
public ActionResult Edit(Car car) {
// get registration country
car.Registration.CountryCode = Request.Form["countryCode"];
}
Alternate Solution: Ok, I had to amend this post because after looking at the source code for the MVC framework I noticed something that wasn’t quite intuitive. There actually is a way to keep the model binding and have the correct select list and selected value. The trick is you must add the selected list to the ViewData with the key name of you property and pass null to the Html.DropDownList helper (or use the DropDownListFor helper). According to the example above here is how it is done:
public CarsController : Controller {
[HttpGet] public ActionResult Edit(string vin) {
Car car = carsDao.FindByVin(vin);
ViewData["Registration.CountryCode"] = new SelectList( // notice the view data key name!
contriesDao.List(), // list of countries for select list
"Code", // select value attribute
"CountryName", // select text display
car.Registration.CountryCode); // selected value
return View(car);
}
}
Our view now will have this:
<%= Html.DropDownList("Registration.CountryCode") %>
OR
<%= Html.DroopDownListFor(m => m.Registration.CountryCode)%>
The reason this works is because the helper extension for the DropDownList checks the ViewData collection for a key named “Registration.CountryCode” and casts it to IEnumerable<SelectListItem>. Since you already stuffed this in the ViewData, it finds your existing list with the correctly selected value and inserts into the view. In addition, you model binding will work now!
Converting IP To Numeric
When looking up a Geo IP, you will need to convert the IP address to numeric value. Below shows the formula for the transformation in both directions.
Given IP address is: w.x.y.z
Numeric:
256^3(w) + 256^2(x) + 256(y) + z
or
16777216(w) + 65536(x) + 256(y) + z
IP:
w = (int)( IP Number / 16777216 ) % 256
x = (int)( IP Number / 65536 ) % 256
y = (int)( IP Number / 256 ) % 256
z = (int)( IP Number ) % 256
Doing this in .NET would yield the following code:
public static uint? IPToNumeric(string address)
{
string[] splits = address.Split('.');
if (splits.Length == 4)
{
try
{
return
16777216 * uint.Parse(splits[0]) +
65536 * uint.Parse(splits[1]) +
256 * uint.Parse(splits[2]) +
uint.Parse(splits[3]);
}
catch { }
}
return null;
}
public static string NumericToIP(uint numeric)
{
try
{
return string.Format("{0}.{1}.{2}.{3}",
(uint)(numeric / 16777216) % 256,
(uint)(numeric / 65536) % 256,
(uint)(numeric / 256) % 256,
numeric % 256);
}
catch { }
return null;
}