Allow Me To Share My Toolset Choices for Developing On .NET

There was a question in a tech facebook group I co-manage about what tools you’d use if starting a new project today.

tools

I don’t know for sure. It depends -of course- is the expected answer. For example, there’s some idea I had I mind I considered using MongoDB or CouchDB for, while still using .NET, and then I wasn’t sure if I go extra mile in DB I’d go for Node or Rails as well or would prefer .NET for my personal productivity. I also often use Node/Bower when checking libraries with many dependencies.

So, for this question, I thought what tools I might use in a company project. Thinking back, I found that most tools I use now are good enough for what they do. So, I thought I’d list these.

These tools are my personal experience though. While some of them are widely adopted in Readify, some others may have been specific to some clients or Readify teams I worked with. Every team is free to choose the tools that work best for them and make it easier to deliver high quality deliverables in sensible time, so, even if you are at Readify, your mileage may vary…

The Tools

Server Side Web

Database

  • SQL Server (or SQL Azure, although I don’t like SQL Azure, because it’s not compatible with some scripts generated from SSMS, which I sometimes use to generate migration scripts)

  • DbUp for DB migrations (there are some other nice options now)

  • Special SQL views + Web API OData + MS Excel for reporting

Client Side Web

  • Angular.JS on the client when I have the choice, Knockout.JS and jQuery UI (being deprecated now) at some big client I keep going back to every few gigs

  • LESS for CSS, or SASS (SCSS) when the CSS is handled by one of our favourite design agencies

  • Chrome devtools for web debugging (obviously), unless it’s IE issue of course.

Mobile

  • Phonegap (most just the open source part of it, Cordova) and Ratchet CSS framework (considering alternatives, like TopCoat) for mobile development, with Angular.JS

  • Considering Xamarin as their work seems to be VERY cool, and I recently get access to their stuff via my company (OT: Also considering Neo4j DB for similar reasons).

IDEs and Text Editors

Testing

CI / ALM

Internal Communication

  • Several kinds of wikis used by different clients, often with OneNote

  • HipChat for team communication, sometimes Skype and/or Lync as well

  • AnswerHub (Stackoverflow clone) for internal questions forum where I can safely quote client sensitive information in my question

  • Yammer for internal company social network

How about you?

What tools do you you use when developing?

Let me know in the comments, via email, or on twitter!

Enforcing ASP.NET MVC Conventions With Unit Tests, Or Solving The AJAX HTML Redirect To Login Page Problem

This blog post is about an ASP.NET MVC workaround we implemented in a previous project. We solved the problem by enforcing using a class that extends one of ASP.NET MVC classes, which in itself created another problem, as new developers joining the project may always use the old class. The solution to this problem was not something that I invented, but it’s also not a very common practice.

So, if you are interested, here’s the entire story…

Detecting Session Timeout In AJAX Requests

We wanted to solve a problem where in an AJAX heavy ASP.NET MVC application, if the user triggers an AJAX action after staying inactive for longer than our application timeout, the call to the controller action, which normally gets a JSON response, would instead get the HTML of the login page.

This is a known issue in ASP.NET (particularly System.Web). A feature that’s on by default is returning a redirect to the login page instead of a HTTP Unauthorized Status code (401). After the redirect the response returned is a successful (HTTP Status Code 200) load of the login page. That means even our Angular.JS error interceptors (or jQuery handlers, etc.) don’t notice there was an error.

A fix for this was turning this feature off. We inherited the Authorize attribute as below:

<code>
 /// <summary>
 /// Suppresses Forms Authentication Redirects for Ajax requests 
 ///     so the client side interceptors can handle it.
 /// </summary>
 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, 
     Inherited = true, AllowMultiple = true)]
 public class AuthorizeRedirectAttribute : AuthorizeAttribute
 {
     protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
     {
         var context = filterContext.HttpContext;
         if (context.Request.IsAjaxRequest())
         {
             context.Response.SuppressFormsAuthenticationRedirect = true;
         }

         base.HandleUnauthorizedRequest(filterContext);
     }
 }</code>

SuppressFormsAuthenticationRedirect is the property that disables the login redirect. Microsoft set it to false by default so that it’s backwards compatible.

ASP.NET MVC doesn’t recognize AJAX requests through Request.IsAjaxRequest() via Accept header or so. It does via checking X-Requested-With header. Most AJAX-capable frameworks like jQuery and others offer a way to intercept all requests and add extra headers, for example, in that app, we configure Angular.JS to include the header with some code similar to this:


 app.config(['$httpProvider', function ($httpProvider) {
   $httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
 }]);

Enforcing The Convention

The obvious problem with the previous solution is that we are ignoring The Power Of Defaults. Any other developer who may join the project needs to know that using Authorize is a no-no, and even for old devs (myself included),
it’s very easy to just forget and use Authorize not AuthorizeRedirect just out of habit.

Solving this problem was quite easy though, we added the following test to our Unit Tests project:


 [TestClass]
 public class AuthorizeRedirectTests
 {
     [TestMethod]
     public void All_Controllers_And_Actions_Do_Not_Inherit_Authorize_Directly()
     {
         var controllerType = typeof(IController);
         var invalidAuthorizeFilter = typeof(AuthorizeAttribute);
         var correctAuthorizeFilter = typeof (AuthorizeRedirectAttribute);

         var webProjectAssembly = correctAuthorizeFilter.Assembly;
         var controllers = webProjectAssembly
             .GetTypes()
             .Where(controllerType.IsAssignableFrom);

         Func<MemberInfo, IEnumerable<object>>
             invalidAttributes = member =>
                 member
                     .GetCustomAttributes(invalidAuthorizeFilter)
                     // Note that AuthorizeRedirectAttribute inherits from AuthorizeAttribute
                     .SkipWhile(correctAuthorizeFilter.IsInstanceOfType);

         foreach (var controller in controllers)
         {
             Assert.IsTrue(invalidAttributes(controller).IsNullOrEmpty(),
                 "Controller {0} should not use {1} directly, " +
                 "use {2} instead",
                 controller.Name, 
                 invalidAuthorizeFilter.Name, correctAuthorizeFilter.Name);

             var actions = controller
                 // Simple check, might get some false positives but they won't hurt
                 .GetMethods(BindingFlags.Instance | BindingFlags.Public);

             foreach (var action in actions)
             {
                 Assert.IsTrue(invalidAttributes(action).IsNullOrEmpty(),
                     "Controller Action {0}.{1} should not use {2} directly, " +
                     "use {3} instead",
                     controller.Name, action.Name,
                     invalidAuthorizeFilter.Name, correctAuthorizeFilter.Name);
             }
         }
     }
 }

I hope the code is self explanatory. We check the web project assembly for all ASP.NET MVC Controllers, then we check the Controllers and all their Action methods for existence of the AuthorizeAttribute. We filter those that use the correct attribute (AuthorizeRedirectAttribute), and we Assert that there are no the no Controllers or action remaining, otherwise, we tell the developer which Controller or Action needs to be fixed, and how to fix it as well.

Room For Improvement

The drawback of this is that our Unit Test project had to reference the ASP.NET MVC assemblies and gets more stuff than most tests should need. We can overcome this by moving our “convention” tests into another project completely, but for this project the conventions were very few and it seemed fine.

Of course the same method can be applied to any other convention you enforce in your project. One obvious example is ensuring all Controllers inherit from a custom base Controller class instead of the ASP.NET MVC class directly. I know people who already do this, as I mentioned in the opening the technique is not new by any means, but it’s worth even more popularity.

Speaking of improvement, the code for this test class was optimized a bit while writing this blog post, there is always room for improvement :)

IsNullOrEmpty()

In case you were reading the code carefully, the IsNullOrEmpty() method I used in assertions is a custom extension method we had in the project, a very simple one as you may expect:


 public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
 {
     return source == null || !source.Any();
 }

And That’s it!

I hope you found the technique useful if you haven’t used it before, or found the post a good place to reference it to those who didn’t.

Using OneNote As Wiki Inside Readify

onenote In recent projects I have been on with Readify, I have seen the rise of using OneNote to share most of the artifacts related to project. We still had requirement documents and proposals and all, and also tracking systems for ongoing and future work (backlog), but we used OneNote to record all sorts of information you’d store in a Wiki and/or in email and floating documents everywhere like:

  • Induction information (why does the project exist? how to setup dev environment? etc.)
  • Demo notes (what items are ready to demo? what are the steps? which users/links are needed?)
  • Meeting notes (demo meetings, sprint retrospectives)
  • Essential communication (Copies of release notes after sending, special notes coming in email / chat)

The availability of OneNote pretty much everywhere (including mobile devices, and web, as it’s hosted in out Office 365) and automatic synchronization made it a perfect alternative to a wiki for internal communication.

And yes, although I haven’t noticed this earlier, but OneNote also keeps track of all revisions and modifications, just like a proper wiki does.

If you want to learn more about how this approach worked for us in Readify, Tatham Oddie, one of our Readify Principal Consultants had an extensive writing of this model and other related communication strategies that help us excel at Readify.

Check it out: BEING AN OPEN RECIPIENT

Of course this is more applicable in situations where we do have more control over the way of communication. Not all projects follow this yet, and many projects work according to the established ways of our clients as long as they get the job done.

How to set the initial value of a select element using AngularJS ng-options & track by

I have been doing Angular.JS in production projects for months, that it did surprise me recently how I haven’t used drop-downs in it. Well, I mean how I haven’t used them enough to get into several problems I had in my current project, and other friends at the same office had in their project as well.

To save you the pain I went through, I’ll list some problems and solutions here, and then give you a video that shows going through all of them ans the thought process that led to the solutions.

Initial selection

<code><select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in objectList ">
</select>
</code>

Assuming someObject in the model has the same properties and values as someObject in the objectList, it will still not be selected.

It’ll only be selected if someObject was actually one of the objects in objectList, like objectList[0] or whatever. Otherwise, Angular.JS will insert an empty option tag with no value or text and select that.

Root Cause

Angular.JS uses native JavaScript comparison for comparing the objects. In JavaScript, unrelated to Angular.JS or anything, comparing objects (object literals) is “by reference”, so it doesn’t factor the similarity of the objects. Only checks if the two references compared point to the same object in memory or not.

Solution

An un-documented (AFAIK) feature in ng-options is that you can use some bits from the ng-repeat directive with it, like track by. This allows us to choose some property as the comparison key.

<code><select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in objectList track by someObject.key">
</select>
</code>

If the key property is a simple type, like Number or string, JavaScript will consider it equal to any other object that has the same value, so we don’t have to use the same objects.

Invalid Value Sent On Server-Side Submit

When Angular.JS writes the <option> tags from an ng-options directive pointing to an array, the value of the option is always the index of the element it maps to in the array. This is not important if you process the selection on client side because you only deal with the result of ng-model anyway, you can use this later to create an AJAX request or whatever.

However, if you intend to submit the form using a normal server submission, and only use Angular.JS for say validation or managing complex form interaction (client-side tables containing sub-items with add/remove/sort for example), this may be a road blocker to using Angular.

Root Cause

By default Angular.JS uses the index of the array to track which object maps to which <option> element.

Solution

Similar to the previous problem, use the track by syntax. Angular.JS will use the track by property value as the <option>‘s value. Most of the time your tracked property is the key property you want to send to the server anyway, so, this should be good enough.

Simple Properties Scenario When Combined With Server-Side Submit

Let’s say you want something as simple as this:

<code><select 
    ng-model="person.genderId"
    ng-options="gender.id as gender.text for gender in genders">
</select>
</code>

This syntax will work very well, if you only use this value from JavaScript, you are all set. But if you plan to send it directly to the server (a normal non-AJAX form submit), you’ll want to consider using the track by syntax, like track by gender.id.

However, if you do this, you’ll notice that the select is no longer usable. No initial selection, and changing selection although updates the model, it does not show the new selected value.

Root Cause

The track by syntax expects an object, with the property you use to track. It does not honor the key part used in the key as text syntax (which in our example is g.id as g.text), so, it wants the ng-model to point to an object with the tracked property, it cannot be the key itself directly.

Workaround

I didn’t call this a solution, because it’s pretty much a hack.

<code><select
    ng-init="person._gender = {id: person.genderId}"
    ng-change="person.genderId = person._gender.id"
    ng-model="person._gender"
    ng-options="gender.id as gender.text 
        for gender in genders track by gender.id">
</select>
</code>

We created a new property (which I liked to prefix with _ to show it doesn’t normally belong to the model object), initialized it to a new object that contains only our key property id set to the original simple value genderId, and then used that as the model (as in ng-model).

We created and assigned the property in ng-init, then synchronized the changes to the simple property via ng-change. This allows the code everywhere else in the application (like the controller, or other parts of the markup) to only interact with the property we want (genderId in this example), without knowing about our hack. This makes things a bit cleaner, although it still remains a hack rather than a solution.

You can view an example of using this hack here.

Adding extra selection items to the dropdown

One thing you notice if you are affected by the “initial selection” problem, is that the empty <option> tag that Angular.JS adds when it can’t match the ng-model to the array from ng-options disappears when the use changes their selection. We have gone through how to avoid showing the empty option by mistake already.

But if you do want to have that option, it’s easy, just, um, add it!

<code><select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in 
        objectList track by someObject.key">
    <option value="">-- Select an option--</option>
</select>
</code>

Update:

If you are using Angular 1.4+, check the much smaller 2nd part of this article, about how to use track by correctly.
Using track by correctly with Angular 1.4 select ng-options – Why can’t I select this option?

The Video

If you want to dig these problems really deep and see what they look like in action, and what was the thought process for solving them like and in some cases other possible solutions, I have put all this in a (rather long) video here:

My Answer To The Question: Is having an online reputation on sites such as Quora important for young people?

Social SitesToday I’ll be sharing with you another answer I’ve added to Quora. The question I answered was:

Is having an online reputation on sites such as Quora important for young people?

And here’s my answer:


In a direct way, only specialised sites count. For programmers for example, a high rank in StackOverflow might be valuable to some employers.

Apart from that, for a site like Quora or so, a high rank will possibly be just like contributing to charity or playing a team sport. A little nice thing for the HR person or cultural interview.

However, there’s more…

Answering questions will likely require you to research topics that you thought you know, when you start explaining them, you get the areas you miss and you figure them out to complete the answer. As the old saying goes, best way to really learn something is to teach it.

Even if a normal answer like this one I’m providing  Just writing your thoughts does help organize them, which is a very good both mental and writing exercise.

So, in short, it’s nice, very nice to have, although not necessarily that important.

Authoring Introductory Articles: The Pitfalls I See As A Reviewer

Authoring Introductory Articles

Just finished replying to an author who asked me to review his introductory article.

The lesson learned from reading and reviewing is that there are some quite common pitfalls to these kinds of articles, which are essentially the same thing:

Thinking That One Size Can Fit All

You are writing an introductory article, so, you target beginners, but even for beginners, you have to assume some level of common ground as a foundation to build on, but how much of a common ground is that? IS the author targeting those who have experience with similar tools/concepts? Students? Professionals with other (unrelated) programming experience?

Sometimes it feels like the author keeps changing his imaginary idea of the intended audience as they keep writing. Eventually the author finds himself inserting some hints and references that if the reader understands then they probably don’t need to read your article (except to review it).

Which leads to:

Unlearning is hard

Just simulating not knowing what you know already. Yes, it’s not that easy!

If you are an author

When you work on any kind of introductory material (which is different from these posts you write just because you want to “take the thought off your chest to the wild”), always be very strict about:

  • Who you audience are
  • Who your audience are not

Identify them by what they do, and what experience they had doing what they do. Be honest with yourself about this identification means they’ll actually benefit from your material or they’ll just congratulate you on it (if you know some people who fit into the audience) without real benefit.

Think of what they are “not” more often as you keep writing. Check every assumption about the audience that you make in the material against the “not” bit.

You may find it hard. Depending on why you are working on the educational material, it may simple be worse changing the intended audience. If this happens without lots of modifications to the work you already did still, it means neither of your images about the intended audience were correct, not the original one, and not the new one too.

As A Reviewer

A reviewer also has their own challenge…

What are some time-saving tips every AngularJS user should know?

Today I’ll be quoting my answer to this question on Quora: What are some time-saving tips every AngularJS user should know?

The Answer

I have read so many advices, most of them are the same, some of them come from the time angular was new and everyone was just worried about reverting to jQuery. Now, these are what I learned:

  • Use routing from the very beginning, go ahead and include ui-route and architect your pages around the idea of routing, don’t be afraid of using child routes / child states

  • Include jQuery, for a “large app” you’re likely to need it anyway, and sometimes the behavior changes when its included (for example, a bad one in fact, historically at least ng-touch for mobile doesn’t stop the 300ms click delay when jQuery is included). If you are building a mobile app maybe this’d be different, but read the next one if you read this

  • Write directives (and filters). Don’t be afraid of writing them. You know all the advice about not doing DOM and stuff? Don’t worry about these much, just make sure whenever you do it, you are doing it in a directive. And yeah, don’t worry about having “too many directives”, most people have the opposite problem; also don’t worry about remembering the syntax, I almost always copy it from another one or docs, don’t let that make you write less directives.
    Same thing applies to filters BTW, write as many of these as you feel you need, sometimes you’ll want to keep them next to the controller they are used in, that’s fine, really.

  • Use services, whenever the controller feels too long (what’s so long? up to you, compare to a regular server MVC controller action, or a class in Java/C# and apply whatever rules you use there), or seems to have so many dependencies (too many function parameters) consider encapsulating most of the logic in a service or more. Think of services as a way to breakup up code more than a way to make it reusable, meaning, don’t fear building one or more services to serve one controller.

  • Write a different CSS file per route view, and use clear classes or so to make sure the CSS doesn’t have conflicts when all combined/minified together (because of course you use some sort of combining/bundling and minification, right?). Of course you’ll also have some shared files (per site and per application module / feature / route) for reusable stuff.

  • Create folders by feature, not by file type. this is called vertical slicing sometimes. The idea instead of having folders named like “Controllers”, “Views”, “Services”, etc., have the folders named after the feature instead (that’s the route most often, but not necessarily, feel free to have some matching route names and some not, it’s OK), and let it have the relevant controller (or controllers, if having child ones), view, and any supporting files, like services, directives, etc.

Disclaimer: Note this is not about being new to Angular or doing JS in general. This is what will help most for “big” applications, although you can use some of it in smaller apps as well of course.

A Video of Aaron Powell Presenting IE 11 At Sydney JavaScript UG

I haven’t been able to attend ALT.NET Sydney or SydJS last month,
as I had to follow up some family issues in Egypt on daily basis.
However, Aaron Powell ( @slace) presented at SydJS last month, and was kind enough to
record his talk on his laptop as a screencast and put it online.

The talk is about dev tools in Internet Explorer 11.
Well, yeah, I know, IE! No matter what I or you think about this browser,
we all often have to test against IE and even worse, against older versions of it too.

With compatibility modes and all, I think it’s great if newer IE versions can make
this must-have experience easier, and can prevent IE from being a source of headache.

Watch Aaron showing us how this applies to IE 11

(Solution) Windows 8.1 hangs on sleep/standby, can’t wake up

The Problem

When you send your physical computer running Windows 8.1 to sleep (stand-by), the computer screen goes black but all other power lights remain on, and you cannot wake it up by pressing any key or whatever, you have to hard reset it by pressing the power button till it stops.

Root Cause

The main problem in my case at least was a conflict between a VirtualBox network driver that it installed on Windows 8.1 (the host) to support “Bridge” networks in virtual machines (clients). Windows hangs at trying to turn this off.

Note that it’s not the same device you see in front of other network adapters in device managers. The one you see is the “host only network”.

The Solution

I managed to solve the problem by uninstalling VirtualBox, and then installing it again without Bridge network support. In the install wizzard “Custom Setup” step, under “VirtualBox Application” -> “VirtualBox Networking”, I disabled “VirtualBox Bridged Networking”, and continued the setup with everything else set (the default).

virtualbox

Note that I tried removing bridged networking from the virtual machines that used it and it didn’t solve it. I had to remove the feature as explained above.

But I need bridged networking!

Ideally, most of the use cases for bridged networking will be solvable using NAT networking instead, use this for your virtual machines unless you really really need the bridging, and then you need to choose between it and the ability to set the computer to sleep, at least until BirtualBox solves the problem.

Applies To: (Version information)

I experienced this problem with VirtualBox 4.2.18. Most likely the problem itself will be solved in some future version.

Update

If you want to watch for progress on this issue, check out the issue report in VirtualBox issue tracker:
https://www.virtualbox.org/ticket/12063

Maintaining your personal brand online with @TathamOddie – New Video

My new video featuring @TathamOddie on maintaining your personal brand both online and offline is now up…

Tatham Oddie is a well known public figure in Microsoft world as he speaks in so many .NET conferences around the world and is an active contributor to several high profile open source projects like WebFormsMVP.

In this video Mohamed Meligy interviews Tatham on online personal branding and ow you can makes the best out of people you meet in social media and offline groups. Tatham shares his experience on how to make it easy for people to recognize you and communicate with you for both social and business benefits.

http://youtu.be/6UBIRiEglsM