Ironing code, geek t-shirts and even presentations!


Using Inline Templates for Directives

When writing angular directives you usually use two kinds of templates - a string that goes into the template property, or a path to a file containing the template which goes into the templateUrl property. The less known brother of these is the inline template option, which is what this blog post is about.

What are Inline Templates?

Inline templates are templates that you define inside your HTML pages within <script> tags. This is an "in-between" approach between the string template and the file template - on the one hand, you don't have to define the template as a string (who loves doing that?? it's such a horrible experience) and on the other hand, angular doesn't need to request the template from the server because it already loads with the page.

What Is It Good For?

A lot!
Well, a few use cases that this approach will make sense for:
  • Instead of using the template property which forces you to write the template as a string.
    If you're a fan of concatenating strings, then this might not appeal to you. But if you are, hmmm, well, you probably have other problems :)
  • When you create a DSL for your application which involves a bunch of directives which will, for sure, be loaded - put all the templates on the main page. This will eliminate the calls to the server for fetching the templates.
  • The last bullet works for every directive that will certainly be loaded at some point.
In my applications I usually create a single partial page which gets loaded with the master layout page and put there all the directive templates I need.

How do You Define Inline Templates?

It's very simple!
To define the template, just add a <script> tag with type="text/ng-template" and a unique id, for example, id="/templates/my-head.html":

On the directive side, use the templateUrl property and set its value to the script tag id. In our case, that would be "/templates/my-head.html":
m.directive("myHead", function() {
  return {
    templateUrl: "/templates/my-head.html"

Why Not, Then?

There a few disadvantages for using inline templates that you should be aware of:
  • Some IDEs will not provide autocompletion inside <script> tags. 
  • People usually prefer to have the template file on its own because it's easier to find on the file tree.
    This is pretty true. However, you can continue working with separate file and then write a simple build script that will take all the template files and bundle them into a single file before going to production.


Inline directive templates is a super simple and powerful solution that makes a lot of sense for various use cases. For some reason the documentation on this feature is pretty much not existing so I hope now it will get the acknowledgment it deserves :)

Write Angular and prosper!

Code Samples from IDNDUG – August 2013

Last night I took the stage at the Israeli .NET User Group and introduced how web development is done today in a session named “How The Cool Kids Create Chats Today?”. Images (courtesy of Dror Helper and Ariel Ben Horesh):

Israeli .NET User Group AUG 2013 - How The Cool Kids Create Chats Today - Shay FriedmanIsraeli .NET User Group AUG 2013 - How The Cool Kids Create Chats Today - Shay Friedman

I had a blast. Thanks to all the attendees who came and listened!

I promised to upload the code from the presentation and I’m a man of my word so…
the solution can be downloaded from: 
The code here has a bit more features than what I showed yesterday and includes custom styles with LESS (look for less files in the Content/less folder) and the general UI design is done via Twitter Bootstrap.

Last but not least – a hidden Easter egg - open the chat in two browsers and make sure one of them is Chrome. Sign in to the chat from both browsers and send a message from the other browser that says *trees* (including the asterisks). Enjoy! Smile

If you have questions or anything else, let me know.
All the best,

Local IIS Not Working and the horrifying “The Server Committed a Protocol Violation” Error

The Problem

I was working on a web site on my local computer. When I wanted to run the web site on my local IIS, I suddenly received a 404 Not Found error for everything hosted on my local IIS.
I tried to run iisreset (even twice, of course!) and it didn’t help. I then tried to start debugging from within Visual Studio, just to see what happens – then I received the OMFG error: “The Server Committed a Protocol Violation. Section=ResponseStatusLine”.


I turned to my old friend, Google. He (or she?) helped me find Martin Kulov’s post -, which suggested that some application had already been using port 80 (the one IIS is using). This results in IIS not being able to load and eventually throwing all of these doomsday errors.

The Solution

I downloaded TCPView to figure out which application is responsible for all the mess. I was surprised (or not) to find out which application it was:

Local IIS Not Working and the horrifying “The Server Committed a Protocol Violation” Error

It was SKYPE!!!! WTF???

Killing Skype and restarting IIS solved the problem and I was able to go back to work.

Note: I’m using Skype

All the best,

My Interview on Herding Code is Published!

At this year’s NDC I had the honor to chat with Jon Galloway and Scott Allen, who are half of the Herding Code crew. We chatted about subjects related to my NDC talks – Roslyn, C#’s dynamic capabilities, and the DLR. 

Last week our chat was published as an Herding Code episode, and it is available to hear and download at

Enjoy the episode and thanks Herding Code for having me!

All the best,

Video, Slides and Code from my Session at aspConf 2012 – ASP.NET MVC Tips, Tricks and Hidden Gems

Last week I had the honor of taking part in the community-driven, ASP.NET-related, virtual event – aspConf 2012. My session was named ASP.NET MVC Tips, Tricks and Hidden Gems and it was generally about things I found to be important from my ASP.NET MVC experience – some were more basic and some were more hidden, too hidden some would say :)

I had lots of fun doing the session, and hopefully the attendees has fun too :)

A big big thanks to the aspConf crew – Javier Lozano, Jon Galloway, Eric Hexter, and friends – you guys did an AMAZING job! thanks!

Anyway, everything from my session is now on the interwebs – video, slides and code samples:


Can be watched and downloaded on channel9:


The slides are available on SlideShare:


Code Samples

All code samples from the session are available on my github page:

That’s it. If you have any questions, let me know!
All the best,

Sample Code from my “What?!? C# Could Do That?!?” Session

In the last few months I had the honor of presenting my session “What?!? C# Could Do That?!?” at different conferences and user groups around the world. The session is mainly about different things you can do with C#’s dynamic capabilities, IronRuby and also a bit about the upcoming Roslyn “Compiler as a Service” project.

I’ve received several requests to upload my sample code. Therefore, I’ve just made it available on my github page -
If you have any questions about the code, don’t hesitate to contact me through twitter or the contact page.

Additionally, if you want me to come and do this session (or others) at your user group/conference, let me know!
All the best,

MVP for the 3rd Time!

A few weeks ago I’ve received an email from Microsoft telling me my MVP had been renewed for another year – 3rd time for me!

IronShay - MVP for the 3rd Time!

I would like to thank my colleagues at CodeValue, you guys ROCK!
Also big thanks to Guy Burstein for everything. If you ever get to meet him, give him a big hug – he’s doing a lot for the developers here.

Last but definitely not least, thank you – readers, attendees, twitter/g+ followers, beer buddies. This all worth nothing without you.


Mass Assignment Vulnerability in ASP.NET MVC

A couple of days ago the Ruby on Rails world got shocked by an old bug (or feature?) that could cause massive security issues sometimes. You can read about it here.

While reading about this vulnerability, I figured out that ASP.NET MVC worked in a very similar way… would it reproduce in an ASP.NET MVC environment? well, of course!

The Problematic Feature

ASP.NET MVC has this very convenient way of getting parameters from the request named Model Binding. The very simple example of Model Binding is controller actions with parameters. For instance:

public ActionResult Create(string name, string email)
  // ... do stuff ...

In this sample, the Model Binding feature will automatically fill in the name and email parameters with data from the request. Very similar to doing something like that:

public ActionResult Create()
  string name = Request["name"];
  string email = Request["Email"];

  /// ... do stuff ...			

This is already very helpful and it’s getting even better – you can set the parameter to a type of your own, and ASP.NET MVC will create an instance and fill it up for you. For instance, if you have a class named Person like this one:

public class Person
  public string Name { get; set; }
  public string Email { get; set; }

You can change the Create method to:

public ActionResult Create(Person person)
  /// ... do stuff ...

By doing this, the Person.Name and Person.Email properties will automatically be filled in by ASP.NET MVC Model Binding.

OK, now that we understand what the essence of model binding is, let’s move on to the problem it represents…

Reproducing the Vulnerability

  1. Create a new ASP.NET MVC Application (I tried it with ASP.NET MVC 3 and 4).
  2. Add a new model class named User, as follows:
    public class User
      public int Id { get; set; }
      public string Name { get; set; }
      public string Email { get; set; }
      public bool IsAdmin { get; set; }
  3. Use the Add Controller dialog box to create a database context and a controller. Call it UsersController. Set the dialog properties as follows:
    Add Controller UsersController
  4. We don’t want the users to change the IsAdmin boolean value. It will be set somehow by the logics of the application later on. Therefore, open the Create.cshtml and Edit.cshtml views (they’re located under the Views/Users folder), and remove the IsAdmin part from them. The part to remove should look something like that:
    <div class="editor-label">
        @Html.LabelFor(model => model.IsAdmin)
    <div class="editor-field">
        @Html.EditorFor(model => model.IsAdmin)
        @Html.ValidationMessageFor(model => model.IsAdmin)


Now to the interesting part:

  1. Run the application and browse to /Users/Create
  2. Fill up the form and send. You’ve got a new user. IsAdmin is false.
  3. Go to the Edit page for this user. The URL will be something like /Users/Edit/1.
  4. Change the URL to /Users/Edit/1?IsAdmin=true and click enter to browse to it.
  5. Now click Save
  6. IsAdmin is now saved as True to the database. Oops.

This example is very very simple, but think about real world scenarios… this might get ugly. Very ugly. The biggest site that suffered the consequences of this vulnerability(based on Rails, but it’s the same thing) is GitHub – you can read their announcement here.

How to Defend

ASP.NET MVC offers a very simple solution to that problem – the Bind(Exclude=””) Attribute.  However, most people never use this feature. So… make a new habit from today – start using it. ALL THE TIME. And when I say ALL THE TIME, I mean that from now on you use it ALL THE F***ING TIME.

For my small sample, add [Bind(Exclude = "IsAdmin")] to the top of the model class (User.cs). After this change the model class should look like that:

[Bind(Exclude = "IsAdmin")]
public class User
  public int Id { get; set; }
  public string Name { get; set; }
  public string Email { get; set; }
  public bool IsAdmin { get; set; }

Rebuild and try our little hack again. It won’t work this time. Phew.

Stay safe,

C# One Liners

I love programming languages. I think they are beautiful. One of the best things about learning different programming languages is finding the different approaches and techniques of each language. This also allows you to incorporate them into other programming languages. One of my favorite languages is Ruby, and Rubyists have this habit of writing meaningful code in one line, AKA “one liner”. C#-ers don’t do one-liners very much, probably because they couldn’t write cool one-liners till not so long ago.

BUT! this has all changed with the arrival of LINQ. The first time you see it you go “WHAT THE ****!?!?!?##@@!??!??”, then you go “hmmmmm” and eventually you have a silly happy look on your face and it seems like everything you can pronounce is “wow” and “cool!”. That’s why my nickname for LINQ is “CDD” – Coolness Driven Development.
So for this post I’ve gathered some cool C# one-liners that I’ve put together with the help of LINQ and features of the C# language. Have more? add a comment!

Filter lists

var list = new List<string>() {"Asia", "Africa", "North America", "South America", "Antartica", "Europe", "Australia"};

// Get all the items from the list that start with
// an 'A' and have 'r' as the 3rd character
var filteredList = list.Where(item => item.StartsWith("A")).Where(item => item[2] == 'u').ToList();


Create a new list from the first items of another list

// Take the first 3 items from list 'list' and create a new list with them
var shortList = list.Take(3).ToList();


Remove duplicate items from a list

var listWithoutDuplicates = list.Distinct().ToList();


Print all items in a list



Cool string counting stuff

var str = "H1e2l3l4l5o6";
// Count all digits in a string
var numOfDigits = str.Count(char.IsDigit);
// Count all lowercase characters in a string
var numOfLowerCase = str.Count(char.IsLower);
// Count all uppercase characters within a string
var numOfUpperCase = str.Count(char.IsUpper);


Comparing two lists

var list = new List<string>() { "Asia", "Africa", "North America", "South America", "Antartica", "Europe", "Australia" };
var list2 = new List<string> {"Africa", "South America", "Antartica", "Foo"};

// Get all items in the list that do NOT have matching items on a different list
var list3 = list.Except(list2).ToList();

// Get all items in the list that have matching items on a different list
list3 = list.Intersect(list2).ToList();

Convert all items in a list

string[] numbersAsText = new[] {"1", "2", "3"};
int[] numbers = numbersAsText.Select(n => Convert.ToInt32(n)).ToArray();


Do heavy processing of parts of groups in threads

var nums = Enumerable.Range(1, 100);
Parallel.ForEach(nums.GroupBy(num => num%2), numGroup => DoHeavyStuff(numGroup.ToList()));


Well, that’s what I have… I bet there are tons more. Go ahead C#-ers, it’s your time to shine!

Slides and Code Samples from my Talk at LIDNUG - What?!? C# Could Do That???

On Thursday I had the honor to do a virtual talk at LIDNUG – the LinkedIn .NET User Group. A stage where lots of .NET celebs like Scott Gu, Jeffery Richter, Jeff Prosise and others have talked in the past.

I’d like to thank all the attendees and the LIDNUG crew who made this possible – Inbar, Peter and Brian – you guys rock!

About the talk – I focused on the dynamic capabilities of C#. Started with some black magic done using the dynamic keyword, then moved on to practice witchcraft with the combination of IronRuby and C#, and ended with the new and shiny .NET spell-book also known as project “Roslyn”.

The talk was recorded and it can be found on YouTube:

The code samples from the talk are also available – click here to download them [2.47Mb].

I had a blast, hope you did as a well.
All the best,