A modular profile photo upload using ASP.NET MVC

ASP.NET MVC with Scaffolding and Razor template engine are great to get your LOB web application up and running shortly. But every once in a while, you find you need to do some extra work to add some features. Having a photo upload template was one of them.

My goals

  • To be able to edit user profile (name, email, etc.) as well as photo
  • To be able to view the uploaded photo before submit (similar to profile image upload of all social media apps)
  • To be built in compliance with ASP.NET MVC (i.e. no server-side controls)
  • To avoid writing extra code unless needed (no need for overkill)

Continue reading

CORS in brief

Q: What is CORS?

A: CORS or Cross-Origin Resource Sharing, is a mechanism and set of specifications developed by W3C as part of HTML5 specifications for organizing access to online resources in one online target domain by another domain (usually through AJAX and RESTful APIs).

Q: What was there before CORS?

A: Before CORS, same-origin policy was applied to prevent cross-site scripting security issues, which means that calling certain resources (i.e. fonts, JavaScript and XMLHttpRequest) from another domain was forbidden.

Q: Does CORS allow unrestricted access to online shared resources?

A: No, the target domain holding the shared resource or script must instruct a web browser that it “allows” certain request types for this resource from certain requesting domains.

Q: Is CORS similar to authentication?

A: No, authentication is checked by the web server before replying with a Response, while CORS is checked by a web browser that supports CORS before sending a Request (in some cases) or after sending the Request but before rendering a Response (in other cases). If the Request from the originator domain was not allowed, the browser generates an exception and prevents rendering or executing the requested resource.

Q: Which web browsers support CORS?

A: CORS is supported in the following browsers:

  • Chrome 3+
  • Firefox 3.5+
  • Opera 12+
  • Safari 4+
  • Internet Explorer 8+

(a complete list of supported browsers at http://caniuse.com/#search=cors)

Q: Are there other non-browser clients supporting CORS?

Continue reading

The art of debugging

I was reading “How to think like a computer scientist” and I liked a quote describing the art of debugging by elimination of impossible scenarios…

When you have eliminated the impossible, whatever remains, however improbable, must be the truth.

Sherlock Holmes (The sign of four)

The story behind reading that book is that I was interested to learn Python, just for the fun of it, and I found that book which is aimed for 1st year computer science students. I thought it would be interesting too to join the ride and start learning a new language assuming I had no experience too. 🙂

Movies that inspired Software

Antitrust

I will start first with the movies that inspired me at the beginning of my career as a programmer, it was Antitrust. Adapted from the story of Microsoft Antitrust case, the movie is based around a tycoon in software (NURV) with its CEO (who happened to look like Bill Gates 🙂 ) and a genius computer science graduate who was offered a job at NURV.

I enjoyed the movies because of its programmers’ appeal, credits written in coding style with <html> tags and // Comments, opening soundtrack was amazing, and cast well chosen. Despite the fact that in NURV (Microsoft) code was written in Java, but most details were taken care of.

The point I liked much was when the young boy was contacted by (Bill Gates) in person and offered his dream job that he didn’t even apply for. I liked the feeling of excelling in your field that jobs search for you not the opposite, the excitement of a young boy joining the company he never imagined he could join. The words that really inspired me for years later, was the welcome speech of the CEO when he said about software business:

This business is binary, you are a one or a zero, alive or dead. There is no second place.

You can watch this part here

Monty Python

I didn’t know about this British comic band of the 70’s before a few months ago; that was when I discovered how their Monty Python’s Flying Circus was a favorite for many programmers at that time. For a beginning, Python language was named after this show because programming with the language was supposed to be as much fun as the show was. One of the famous sketches of this show was the Spam sketch below.

In this sketch the word “spam” and “spam with eggs” was introduced frequently in a restaurant menu as an undesired ingredient and later all along the sketch, even the end credits. From this sketch came the word spam that describes unwanted mails. The words “spam” and “eggs” are also used in Python literature. I used to think that Python packages are named eggs because “pythons” are conceived in “eggs” but I think it has also to do with the show.

I don’t know if other movies or shows have inspired software or not but that was the ones I thought of.

Composite WPF and the Ribbon Control

While working for WPF and Composite Application Library (CAL) for the first time, I had some difficulty both understanding their concepts and apply them in the optimal way, but I tried harder.

One of the benefits of CAL I found was the Command Binding which truly facilitates complying to the Model-View-ViewModel UI Design Architecture. But finding an easy implementation for them in all the desired control was not as easy as with default menu items and tool bars. A question on stackoverflow was asking about implementing the Command Binding with the WPF Ribbon which is downloadable within the WPF Futures, and not included in the out-of-box visual studio installation.

The trick was to make custom region adapters as those of menu and tool bar. I have found samples of  RibbonRegionAdapter.

To comply with CAL and Model-View-ViewModel,  the View containing the Ribbon will be be bound to a ViewModel containing all commands. These commands would be exposed publicly and available to other modules to attach Executed and CanExecute handlers. It is possible also to expose a generic method to add commands at run time by providing their image and location on the ribbon.

I found also open source implementation for binding the docking manager. The Composite WPF Contrib Project on CodePlex contains a TabGroupPaneRegionAdapter for Infragistics TabGroupPane.

Augmented Reality

Every great magic trick consists of three parts or acts. The first part is called “The Pledge”. The magician shows you something ordinary: a deck of cards, a bird or a man. He shows you this object. Perhaps he asks you to inspect it to see if it is indeed real, unaltered, normal. But of course… it probably isn’t. The second act is called “The Turn”. The magician takes the ordinary something and makes it do something extraordinary. Now you’re looking for the secret… but you won’t find it, because of course you’re not really looking. You don’t really want to know. You want to be fooled. But you wouldn’t clap yet. Because making something disappear isn’t enough; you have to bring it back. That’s why every magic trick has a third act, the hardest part, the part we call “The Prestige

From the movie “The Prestige”

I had that feeling when I read an article about Augmented Reality which I haven’t heard of before.

The article mentioned a page developed by General Electric as an example

I went directly to the video and my eyes and mouth were wide open for 5 minutes until I realized what it is

Here is another video showing the “making” …

http://www.gotoandlearn.com/play?id=105

And now after being “enlightened” , I can tell the “trick”

We all know that we can render 3D graphics and change the viewpoint by changing the position (x, y, and z) of the camera object

We also know that with computer vision, we can detect the position and the rotation of a certain pattern on all axis

Combining the two concepts, we can use the computer camera to detect the position of the viewer (the human) relative to the position and rotation of the pattern and then render the 3D graphics respectively

So simple isn’t it, but yet amazing

Historical Debugger and Test Impact Analysis in Visual Studio Team System 2010

I was browsing some of the awaited-for Visual Studio 2010 and I found a video about two interesting features related to what we do everyday (and I do not mean coding ;))

The first feature is related to debugging “history”. Normally, when you find a bug while running your program, you insert multiple breakpoints on the statements you suspect might caused it, and repeat the scenario or restart the debug session.

With history debugging, you don’t need to do so, since the history debugger “logs” every event in your application, so you can “pause” running and inspect all the previous events and may be check if there were “swallowed” exceptions.

The second feature, is when you want to modify some “unit-tested” code either for bug fixing or refactoring, and you want to re-run the impacted tests. Normally it is hard to determine which tests are affected so you run all of them, but with Test Impact Analysis in VS 2010, you can get the impacted tests once you save your modifications, so you can either commit your changes or undo.

Here is the 19 minutes video showing these two features on Channel 9

Historical Debugger and Test Impact Analysis in Visual Studio Team System 2010

C# 4.0: What’s next

Since I have talked before about Visual Studio 2010 and Dynamic Typing, it is now time to talk about the upcoming C# 4.0 which we are expecting soon.

To understand how C# evolved and what is the paradigm of C# 4.0, let’s get a quick overview of previous versions.

In 1998 the C# began as a simple, modern, object-oriented, and type-safe programming language for the .NET platform. Since launched in the summer of 2000, C# has become one of the most popular programming languages in use today.

With version 2.0 the language evolved to provide support for generics, anonymous methods, iterators, partial types, and nullable types.

When designing version 3.0 of the language the emphasis was to enable LINQ (Language Integrated Query) which required the addition of:

  • Implicitly Typed Local Variables.
  • Extension Methods.
  • Lambda Expressions.
  • Object and Collection Initializers.
  • Anonymous types.
  • Implicitly Typed Arrays.
  • Query Expressions and Expression Trees.

Although C# is an object-oriented programming, but C# 3.0 included some capabilities of functional programming to enable LINQ

In version 4.0 the C# programming language continues to evolve, although this time the C# team were inspired by dynamic languages such as Perl, Python, and Ruby.

Another paradigm that is driving language design and innovation is concurrency and that is a paradigm that has certainly influenced the development of Visual Studio 2010 and the .NET Framework 4.0.

Essentially the C# 4.0 language innovations include:

  • Dynamically Typed Objects.
  • Optional and Named Parameters.
  • Improved COM Interoperability.
  • Safe Co-variance and Contra-variance.

To show these features, I’ll show some examples posted by Doug Holland on his The C# Programming Language Version 4.0 blog post…

Dynamically Typed Objects

In C# today you might need to get an instance of a class and then calls the Add method on that class to get the sum of two integers:

Calculator calc = GetCalculator();
int sum = calc.Add(10,20);

Our code gets all the more interesting if the Calculator class is not statically typed but rather is written in COM, Ruby, Python, or even JavaScript. Even if we knew that the Calculator class is a .NET object but we don’t know specifically which type it is then we would have to use reflection to discover attributes about the type at runtime and then dynamically invoke the Add method.

object calc = GetCalculator();
Type type = calc.GetType();
object result = type.InvokeMember("Add", BindingFlags.InvokeMethod, null,
    new object[] { 10, 20 });
int sum = Convert.ToInt32(result);

With the C# 4.0 we would simply write the following code:

dynamic calc = GetCalculator();
int sum = calc.Add(10,20);

In the above example we are declaring a variable, calc, whose static type is dynamic. We’ll then be using dynamic method invocation to call the Add method and then dynamic conversion to convert the result of the dynamic invocation to a statically typed integer.

Optional and Named Parameters

Another major benefit of using C# 4.0 is that the language now supports optional parameters (like C and C++) and named parameters.

One design pattern you’ll often see as that a particular method is overloaded because the method needs to be called with a variable number of parameters.

In C# 4.0 a method can be refactored to use optional parameters as the following example shows:

public StreamReader OpenTextFile(string path, Encoding encoding =  null, bool
    detectEncoding = false, int bufferSize = 1024) { }

Given this declaration it is now possible to call the OpenTextFile method omitting one or more of the optional parameters.

OpenTextFile("foo.txt", Encoding.UTF8);

It is also possible to use the C# 4.0 support for named parameters and as such the OpenTextFile method can be called omitting one or more of the optional parameters while also specifying another parameter by name.

OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 1024);

Named arguments must be provided last although when provided they can be provided in any order.

Improved COM Interoperability

When you work with COM interop methods, you had to pass a reference to Missing.Value for unneeded parameters, like the following:

object filename = "test.docx";
object missing = System.Reflection.Missing.Value;

doc.SaveAs(ref filename,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing);

Now, in C# 4.0 you can only write:

doc.SaveAs(filename);

Notice that you are able to omit the ref modifier although the use of the ref modifier is still required when not performing COM interoperability.

Also it was necessary to ship a Primary Interop Assembly (PIA) along with your managed application. This is not necessary when using C# 4.0 because the compiler will instead inject the interop types directly into the assemblies of your managed application and will only inject those types you’re using and not all of the types found within the PIA.

Safe Co-variance and Contra-variance

Co-variance means that an instance of a subclass can be used when an instance of a parent class is expected, while Contra-variance means that an instance of a super class can be used when an instance of a subclass is expected. When neither is possible, it is called Invariance.

Since version 1.0 arrays in .NET has been co-variant meaning that an array of string can be assigned to an array of object.

string[] strings = new string[] { "Hello" };
object[] objects = names;

Unfortunately arrays in .NET are not safely co-variant. Since objects variable was an array of string the following will succeed.

objects[0] = "Hello World";

Although if an attempt is made to assign an integer to the objects array an ArrayTypeMismatchException is thrown.

objects[0] = 1024;

To achieve safety, both C# 2.0 and C# 3.0 generics are invariant and so a compiler error would result from the following code:

List strings= new List();
List<object> objects = strings;

For the Liskov Substitution Principle (LSP) to be achieved, methods of a derived class need to have contra-variant inputs and co-variant outputs.

Generics with C# 4.0 now support safe co-variance and contra-variance through the use of the in (contra-variant) and out (co-variant) contextual keywords. Let’s take a look at how this changes the definition of the IEnumerable<T> and IEnumerator<T> interfaces.

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

public interface IEnumerator
{
    T Current { get; }
    bool MoveNext();
}

Given that an IEnumerable collection is read only, there is no ability specified within the interface to insert new elements, it is safe to treat a more derived element as something less derived. With the out contextual keyword we are contractually affirming that IEnumerable<out T> is safely co-variant. We can now write the following code without a compiler error:

IEnumerablestrings = GetStrings();
IEnumerable<object> objects = strings;

Using the in contextual keyword we can achieve safe contra-variance, that is treating something less derived as something more derived.

public interface IComparer
{
    int Compare(T x, T y);
}

Given that IComparer<in T> is safely contra-variant we can now write the following code:

IComparer objectComparer = GetComparer();
IComparer stringComparer = objectComparer;

It is important to notice that co-variance in IEnumerable<object> refers to the fact that its Current property can return a string instead of an object as output, while contra-variance in IComparer<string> refers to the fact that its Compare method can accept an object instead of a string as input.

Agile and CMMI

I wanted to talk about this issue a long time ago, but I didn’t have much to share with you.

My first trigger for this post was few months ago when Software Engineering Institute (SEI) of Carnegie Mellon University published a report under the name CMMI or Agile: Why not embrace both! which is a confirmation by CMMI authors that you can satisfy both requirements.

The report summarizes the history of both paradigms and why it is perceived that CMMI is waterfall while it isn’t. It also summarized the misconceptions in both ideas and how to overcome them. And it ends by a call for action for both practitioners and trainers to bridge the gap between both.

The report also addresses other issues such as:

  • The Origins of Agile Methods
  • The Origins of CMMI
  • Lack of Accurate Information
  • Terminology Difficulties
  • There Is Value in Both Paradigms
  • Challenges When Using Agile
  • Challenges When Using CMMI
  • Problems Not Solved by CMMI nor Agile

Yesterday, I have been in a 2-days workshop on the same issue where we have conducted some real life case studies to discover how we can come out with processes that satisfy both, and get useful feedback from experts in both schools.

If I can summarize what I have learnt in those 2 days, it is that you have to be first convinced why you need Agile and why you need CMMI, and when you do, you will be able to select to which level you want to embrace each, and what are the practices that would "add value" to your organization (not only individual projects)

Finally, I would like to refer you to this 2 years old post by Jeff Sutherland in which he says that Scrum supports CMMI level 5

Thinking out of the “box”

Ever got into a dead-end with no one to ask for help, or new ideas to try?

In 1975, one creative guy (not from an IT background) have came out with a “box” of ideas cards to give him clues whenever he gets puzzled and starts looking around without a purpose. He called it Oblique Strategies.

These cards actually doesn’t include answers, rather, it has some phrases that can trigger your mind to try new solutions that you might have not thought of.

The funny thing is that you can use these cards in software engineering and yet you can find it really useful. Here is how.