IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

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 - https://github.com/shayfriedman/WhatCSharpCouldDoThat-Sample.
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,
Shay.



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.

Thanks!
Shay.



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>
    <div class="editor-field">
        @Html.EditorFor(model => model.IsAdmin)
        @Html.ValidationMessageFor(model => model.IsAdmin)
    </div>

 

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,
Shay.



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

list.ForEach(Console.WriteLine);

 

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();
numbers.ToList().ForEach(Console.WriteLine);

 

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!
Shay.



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,
Shay.



My Sessions at NDC2011 and Upcoming Gigs at GOTO, SDC and LINDUG

It’s been a while since NDC2011 took place but I figured out I’ve never officially published the slides and videos from this incredible event. First and foremost, I’d like to thank Program Utvikling for having me as a speaker second year in a row – you guys ROCK! this year’s conference just strengthened my belief that NDC is the best .NET conference out there. So if you have one conference you wanna go to, this is, IMHO, your best pick.

image

Anyway, I had two sessions this year – IronRuby FTW and Ruby on Rails vs. ASP.NET MVC:

IronRuby FTW!!!

Thanks for the attendees that chose my session over Scott Guthrie’s – very much appreciated! :)

Abstract:
Ruby has been a home for some great innovative frameworks like Ruby on Rails, Cucumber and Rake. In this session you will get familiar with the IronRuby language and its amazing ecosystem and you will learn to take advantage of it in everyday tasks like testing, building, enhancing current code and more. Come and see how IronRuby makes your development life better and happier!

Slides:

Videos: Dowload MP4

Ruby on Rails vs. ASP.NET MVC

I had lots of fun preparing for this session and doing it as well. Apart from my comparison, I ran a little scoreboard during the session and asked the audience a few times to vote for their favorite framework – ASP.NET MVC won by 1 vote! this is not a huge surprise – even though Ruby on Rails is still ahead in terms of community and external packages, the fundamentals of both frameworks are pretty solid at the moment and quite similar…

I did this session a year ago (with MVC 2.0) at Epicenter2010 and Ruby on Rails won 8 to 2… So this result is a very good sign that ASP.NET MVC is in the right direction – Good work Microsoft!

Abstract:
Last year was the year when two great web development frameworks arrive at the .NET world – ASP.NET MVC 3.0 and Ruby on Rails (via IronRuby). It is the time to get to know these frameworks and learn their advantages and disadvantages. In this session, Shay Friedman will walk you through the good, the bad and the ugly of both frameworks providing you points to consider when coming to choose one of them.

Slides:

Videos: Download MP4

Upcoming Gigs

In the next month I’m going to present four sessions in three different conferences and locations. If you’re around, come say hello.

GOTO Amsterdam – October 13-14 (Amsterdam, The Netherlands)

GOTO Logo

I’m going to run a single session – “ASP.NET MVC 3 Hidden Tips, Tricks and Hidden Gems”. You’ll also be able to find me on the conference party, the Meet the Speakers event and generally where they serve beer :)

Time and place: October 13th, 13:20-14:10, Foyer room.

Abstract:
The ASP.NET MVC framework has been around for more than two year now and has been constantly gaining popularity since then. However, despite that fact a lot of MVC developers are not aware of various hidden gems that can make their development experience much easier and nicer. In this session we will go through some of those which were added in the latest version – ASP.NET MVC 3.

ScanDev on Tour – October 18th (Stockholm, Sweden)

Very excited to come back to Sweden (too bad it’s not gonna be snowy, though :) ). On ScanDev on Tour I’m going to present two sessions – “ASP.NET MVC Hidden Tips, Tricks and Hidden Gems” and “Introduction to Ruby on Rails”:

Session: Introduction to Ruby on Rails
Time and place: 10:30 – 11:20, Web Room
Abstract:
The most famous Ruby–driven framework is, by far, Ruby on Rails. In the last few years this framework has been gaining popularity and now is a great time to get to know it. In this session, Shay Friedman will build an entire Web 2.0 site from scratch while using and explaining the key features of Ruby on Rails. Come and see what Ruby on Rails is all about and what's made it the success it is today.

Session: ASP.NET MVC Hidden Tips, Tricks and Hidden Gems
Time and place: 13:30 – 14:20, .NET Room
Abstract:
The ASP.NET MVC framework has been around for more than two year now and has been constantly gaining popularity ever since. However, despite that fact, a lot of MVC developers are not aware of various hidden gems that can make their development experience much easier and nicer. In this session we will go through some of those which were added in the latest version – ASP.NET MVC 3.

LINDUG – November 17th (Virtual)

LINDUG is the .NET group on LinkedIn. I’m going to run a LiveMeeting 90-minute session – “What?!? C# Could Do That?”.

Time and place: 12PM – 1:30PM (PT)
Abstract:
.NET 4 has brought us the DLR and C# 4 has brought us the dynamic keyword. With their powers combined, C# suddenly gets super powers!
In this session Shay Friedman will show you surprising and practical things you can do today with C#, the dynamic keyword and the DLR.
Registration (free): http://lidnug-shayfriedman.eventbrite.com/


All the best,
Shay.


My Leading Candidate for Worst C# Feature – Method Hiding

I love C#, I really do. Of course is has its little annoying quirks here and there, but in general it is, IMHO, one of the best static programming languages out there. Having said that, one thing that makes me wonder “WHAT THE HELL WERE THEY THINKNING?!?$?!?” every single time is the feature known as “Method Hiding”.

What is Method Hiding?

Method hiding, in short, is the crippled, mentally-ill brother of method overriding. For example, look at the next code:

class A
{
  public string GetName()
  {
    return "A"; 
  }
}

class B : A
{
  public new string GetName()
  {
    return "B";
  }
}

Class A has a GetName method; class B inherits from class A and implements the GetName method as well. 
Look carefully at the GetName method signature in class B – do you see the new keyword there? this means that the method doesn’t override the implementation in class A, it just hides it. What does that mean? read on.

So What’s the Big Deal? Hide, Override… Who Cares?

There is a huge difference in the behavior of method hiding and overriding. Look at the next two samples:

Method hiding vs. Method overriding

The left part is a method hiding example, and the right part is a method overriding example. Now let’s go through the use cases.

First – using the father classes:

FatherHidden fh = new FatherHidden();
fh.GetName(); // = "A"

FatherVirtual fv = new FatherVirtual();
fv.GetName(); // = "A"

Both are available and return the same result. Good.

Second – using the son classes:

SonHiding sh = new SonHiding();
sh.GetName(); // = "B"

SonOverriding so = new SonOverriding();
so.GetName(); // = "B"

Again, both methods return the expected result. Swell!

Third – using polymorphism – storing an instance of the son classes in a father class variable and calling the GetName method:

FatherHidden fh = new SonHiding();
fh.GetName(); // = "A"

FatherVirtual fv = new SonOverriding();
fv.GetName(); // = "B"

See that? the hidden method (FatherHidden.GetName) had suddenly woken up, took over and returned “A” instead of the expected “B”! kicking polymorphism out the door while doing it!

Is It a Problem?

Yes, it is. I’ve never found any reason to use method hiding and I can’t think of a good reason start using it in the future. OOP is great and I can’t understand why we need ways to screw it up. In my opinion, if you get to a situation where you need to use method hiding, re-think your design and start over.

This is not just a cute code smell. It can lead to nasty bugs along the way. For instance, I came across something like the next piece of code when doing a code-review lately:

class Base
{
  public bool IsAuthenticated { get { return false; } }
}
class SomeAuthClass : Base
{
  public new bool IsAuthenticated { get { return CheckAuthentication(); } }
}

Now, as long as they use SomeAuthClass variable types on their system, everything will work fine. But once a developer comes and wants to use some OOP magic, all users will immediately become unauthenticated. And this is no fun. No fun at all.

One of my major problems with method hiding is that it is C#’s default behavior – you don’t even need to write the new keyword. And even if the method on the base class is marked as virtual, and you forget to mark the method on the inheriting class with override – you fall back to method hiding…

#sadpanda

What I Am Suggesting

I know this feature isn’t going to disappear. Ever. I’m sure some people have found a reason to use it like there’s no tomorrow and Microsoft is one of the best in keeping their products backwards-compatible.

However, I would like:

  • To get a compilation error if a method is going to hide another method and is not marked with the new keyword.
  • To make the method hiding feature obsolete (yes, obsolete!) and get a compilation warning when using this feature in future versions of the framework.
  • You to stop using method hiding.
  • Everyone to recycle more and save the planet!

All the best,
Shay.

kick it on DotNetKicks.com Shout it



Windows Azure Tip: The "DeleteCurrentDeployment" task failed unexpectedly

Recently I’ve been helping a client to migrate an existing web application to the Azure cloud. We’ve been facing several different obstacles along the way, but most of them were technical. However, today we got to our first “DUDE, I HAVE NO IDEA WHAT’S GOING ON” moment – we got the next error when trying to build the Azure project in Visual Studio:

“Error 1  The "DeleteCurrentDeployment" task failed unexpectedly.
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.VisualStudio.OLE.Interop.IServiceProvider'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{6D5140C1-7436-11CE-8034-00AA006009FA}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).”

*crying inside*

Searching the web resulted in a very few unrelated cases with crazy solutions - I even tried to run regsvr32 on all of the DLLs in the system32 folder… which didn’t help. At all.

*crying out*

Anyways! 2 hours later I had everything working again! How? read on…

The Solution

There is actually nothing fancy about the solution… The thing that worked for me was uninstalling Windows Azure SDK and Windows Azure Tools for Visual Studio and then reinstalling them. That’s it.

*tears of joy*

All the best,
Shay.



Please Use TryParse and Avoid Parse+Try/Catch

Recently I’ve run into a piece of class which was operating as the central place for type conversions in the system. While the idea of having such a class doesn’t sound like a problem, the way it’s been implemented definitely is.

Most of the conversion methods looked something like that:

public int ToInt(string value)
{
  try
  {
    return Int32.Parse(value);
  }
  catch
  {
    return DefaultValue;				
  }
}

I took this method for a test drive – I executed it within a loop and put a stopwatch before and after. The next chart demonstrates the results (X=number of loop iterations, Y = execution time in milliseconds):

Parse with try/catch execution time chart

100,000 calls to this ToInt method takes about 10 seconds!

This implementation would have been acceptable if there were no other solution for doing this stuff. But there is ALWAYS another way! and this time this way has a name – TryParse.

TryParse will achieve the same result like Parse but with one major difference – it will not raise an exception once the conversion is unsuccessful but instead it will return false. Changing the ToInt method implementation is quite easy:

public int ToInt2(string value)
{
  int result;
  if (!Int32.TryParse(value, out result))
  {
    return DefaultValue;
  }
  return result;
}

And now, when I re-run the test drive code I got blown away by the results – look at that chart:

TryParse execution time chart

The time for 100,000 conversions dropped from ~10 seconds to ~20 milliseconds! that is about 500% faster!!!

This is the joined chart, which makes the results crystal clear:

Joined results: TryParse vs Parse+try/catch

Conclusion

There is a single conclusion to this post: avoid using Parse+try/catch and start using TryParse. As simple as that.

All the best,
Shay.

kick it on DotNetKicks.com Shout it



Forget 42, –1 is My New Answer to Life

I’ve just stumbled upon the next code statement – Thread.Sleep(-1). It left me wondering what was happening there since MSDN tells you nothing about a –1 value for the milliseconds parameter:

“The number of milliseconds for which the thread is blocked. Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute. Specify Infinite to block the thread indefinitely.“ – System.Threading.Thread.Sleep, MSDN

To check that out, I opened the IronRuby interactive console and filled in System::Threading::Thread.Sleep(-1) and hit Enter just to find out that this call blocks the thread indefinitely. Could it be? –1 is Infinite?

Reflector to our aid! oh wait, RedGate now charges money for it and had planted a time bomb inside the free version which made it stop working. grrrr
ILSpy to our aid! (I highly recommend ILSpy as a Reflector alternative… very similar, free, oss… great community effort!)

Anyway, ILSpy proved my concerns:

System.Threading.Timeout.Infinite Value

So… –1 actually represents Infinity (when it comes to threading in .NET). And Infinity is much cooler than 42, hence –1 is the new answer to life.
Q.E.D.

All the best,
Shay.