Blog @nicoschuele.com


Week 29 in Tech

I'm trying a new thing on this blog: the week in tech. News that caught my eyes between Fridays and that I find relevant from a developer's perspective. The intent is to have a short digest which shouldn't take more than 5 minutes to read. If the audience justifies it, I'll make a separate outlet for it. Of course, feedback is welcome!

Microsoft eliminating up to 14% of its workforce

This made the news this week:

Microsoft Corp. said it will eliminate as many as 18,000 jobs, the largest round of cuts in its history, as Chief Executive Officer Satya Nadella integrates Nokia Oyj’s handset unit and slims down the software maker.

Among the first business units to get axed, Xbox Entertainement Studios. That means that there won't be any original shows for Xbox as initially announced by the company.

The full story here.

A new Apple and IBM partnership to focus on the enterprise

Times have changed since the 1984 ad: Apple and IBM announced a new partnership to help bring iOS devices in the enterprise.

The combination will create apps that can transform specific aspects of how businesses and employees work using iPhone and iPad, allowing companies to achieve new levels of efficiency, effectiveness and customer satisfaction—faster and easier than ever before.

The first thing that came to my mind was iAS 400.

Guess what! Tizen-powered phone delayed!

Originally announced for a September 2013 release, the Samsung Z which should be the first Tizen-powered phone has again been delayed by Samsung. No release date announced, though.

Microsoft boasts huge scope for growth to partners

Excerpt from Microsoft keynote at the Worldwide Partner Conference, on Ars Technica:

More broadly, Turner said that Microsoft has just a 14 percent share of all devices when one counts smartphones and tablets alongside PCs, and that this represents a huge opportunity for the company and its partners.

Does that mean that companies with 0% market share have even a larger growth opportunity? Interesting way to present numbers!

Apple publishes a blog on Swift

As stated in the first entry, the only one at this time (emphasis mine):

We have big plans for the Swift language, including improvements to syntax, and powerful new features. And as Swift evolves, we will provide tools in Xcode to help you migrate your source code forward.

This is yet another hint at retiring Objective-C as the first citizen language for any Apple-related development in the future.

Xcode 6 beta 3 available to anyone

Anybody can get Xcode 6 beta 3. No need for a paid developer subscription.

Yet another Apple-bashing ad from Samsung

Not even a month after the wall huggers anti-iPhone ad, Samsung now takes a stab at the iPad with yet another Apple-bashing ad. What if, for a change, Samsung would boast about its unique features without always feeling the need for a comparison with the competition? Stay classy.


Batch convert CRLF to LF

Ever worked with people using Windows machines while you are on Mac or Linux? Have you ever had issues with line endings formatting? Or even worse, reached the infamous Git error:

fatal: CRLF would be replaced by LF in ......

A quick script

So I wrote an absolutely not awesome script that converts DOS CRLF line endings with Unix LF line endings. just save this in a file named crlf2lf:

#! /bin/sh
for x
do
    echo "Converting $x ..."
    tr -d '\015' < "$x" > "convert.$x"
    mv "convert.$x" "$x"
    echo "$x done."
done

Simple! Don't forget to chmod u+x crlf2lf and if you want to use it on all the files within a directory, just do this:

crlf2lf *

...and that's it!

Extend it

I published the script on Github. Not because it's beautiful or complicated but because it would be fun if people would extend it to do more, like make it recursive and so on.

image


Discovering Markdown

I'm late to the party. Very late. 10 years late. Because the latest official release of Markdown dates back to 2004. Recently, I've been spending my nights writing technical documents, with a lot of embedded code and just made the switch from writing them directly in HTML to writing them in Markdown. Here's a brief tutorial on Markdown, how it can help you write faster and my current setup.

Markup

The basic idea behind a markup language is to arrange logically bits and pieces of data, usually text, by annotating them. There are many markup languages such as HTML, LaTex and XML. Markdown is itself a markup language.

Easy to read, easy to write

Markdown was created by Apple-centric blogger John Gruber with contributions from the late Aaron Swartz. The idea behind it is to let writers easily compose texts that would be converted to valid HTML. A text written in Markdown is easy to read and easy to write. Contrary to HTML, elements don't need to be wrapped in opening and closing tags.

Have a look

Let's just compare 3 times the same text. Once in plain text, once in HTML and once in Markdown.

plain text

This is the title
This is a subtitle
The following word should be rendered in italic and this one in bold.
Look at an unordered list:
Item 1
Item 2
Item 3
This is a piece of code that displays <Hello World> in the console:
public static Main(){
Console.WriteLine("<Hello World>");
}
And this is a link to my site.

HTML

<h1>This is the title</h1>

<h2>This is a subtitle</h2>

<p>The following word should be rendered in <em>italic</em> and this one in <strong>bold</strong>.</p>

<p>Look at an unordered list:</p>

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>


<p>This is a piece of code that displays <code>&lt;Hello World&gt;</code> in the console:</p>

<pre><code>public static Main(){
    Console.WriteLine("&lt;Hello World&gt;");
}
</code></pre>

<p>And this is a <a href="http://www.nicoschuele.com">link</a> to my site.</p>

Note the amount of tags needed to render this properly in HTML. Also note that the < character, for example, needs to be converted to &lt; in order to be displayed correctly when wrapped inside <code> tags. If you need to write code samples on a blog, that's a drag.

Markdown

# This is the title

## This is a subtitle

The following word should be rendered in *italic* and this one in **bold**.

Look at an unordered list:

* Item 1
* Item 2
* Item 3

This is a piece of code that displays `<Hello World>` in the console:

    public static Main(){
        Console.WriteLine("<Hello World>");
    }

And this is a [link][1] to my site.

[1]: http://www.nicoschuele.com

Much cleaner, easier to read, faster to write. And you know what? The HTML example above was generated from this same Mardown sample!

The result

And this is the produced output from the Markdown code above:

Output

Different flavors

The vanilla version of Markdown sparked some augmented versions. The most well-known are the Github Flavored Markdown (also known as GFM) and Multimarkdown. They each have their own additions to the basic Markdown syntax, for example, Multimarkdown has the capability to add footnotes.

Even if you are new to Markdown, chances are that you already encountered it. It is used to edit posts on StackOverflow, Reddit and GitHub, to name a few.

What you need

First, you'll need to learn the syntax. It should take you about 30 mins for it. Yup, it's that simple. Have a look at the reference.

Then, all you need is a plain text editor and start writing! Personally, I use a nice free app on OS X called MOU with a dark theme. It as a right pane showing you a live preview of your formatted text. With it you can also copy as HTML and your Markdown text will be stored in HTML format in your clipboard. MOU also allows you to generate formatted PDF directly. I might switch to LightPaper, though, but hadn't yet had the chance to write something significant with it. This is what MOU looks like:

Mou App

Sometimes, when on Windows, for example, I use a free online editor called StackEdit. It has the same features as MOU and can save files to your Dropbox.

Switching

Since I switched to Markdown from HTML to write, I really get my writings done much faster. So yeah, I'm late to the game but I enjoy it nonetheless. I've even modified the editor feature on my blog to use Markdown rather than HTML.


Understanding and implementing events in C#

I previously wrote about how to use delegates in C# and using delegates with anonymous methods. No discussion on delegates would be complete without at least introducing the event model. Let's do just that!

Things happen

Before diving into the intricacies of the code itself, let's just explain what events are. Imagine you have a smartphone and that it rings in your pocket: the ringing notifies you so you can take an appropriate action like answering the call. Well, that is the events model. An object (in this example, the phone) does something: it rings. The action of ringing is said to be an event which is raised (or fired). Another object (you) has subscribed to the event so it can in turn execute the appropriate method (answering). Here, we have two classes: Smartphone which is the publisher and Person which is the subscriber and an event which is Ringed.

Let's write a concrete example. Our publisher will be a class Monster which can Roar(). When the monster roars, it raises the event Roared. We also have a class Kid which will Subscribe() to the Monster.Roared event and execute the method Cry() when the monster roars. Each time the monster roars, we want all the kids to cry. Pretty scary stuff.

Creating a monster

Let's look at the Monster class. For brevity, it only implements a Name property and a Roar method:

public class Monster
{
    public string Name { get; set; }

    public delegate void RoarHandler(object sender, EventArgs e);
    public event RoarHandler Roared;

    public Monster(string name) {
        this.Name = name;
    }

    public void Roar() {
        Console.WriteLine("{0} roars loudly!",this.Name);
        if (Roared != null) {
            Roared(this, EventArgs.Empty);
        }
    }
}

Notice these two lines:

public delegate void RoarHandler(object sender, EventArgs e);
public event RoarHandler Roared;

We first start by declaring a special kind of delegate. It is known as the handler for the event. That is the method (or rather the method contained in the delegate) that will execute when the event is raised. By convention, in .NET, event handlers return void and take two parameters: the sender and the arguments for the events. More on that later. Just know it is a convention for now.

Then, we declare the event itself using the event keyword. It is of type RoarHandler and is called Roared. Again, this is a convention in .NET to name events as an action that has happened such as Clicked, Moved, Printed and so on.

We also have the instance method Roar(). When the monster roars, if any other object subscribed to the Roared event, we want to execute the appropriate RoarHandler containing the subscriber's method to be run.

Let's make kids

With our Monster class created, we now need to create another one that can subscribe to the Roared event. It will be Kid and when a monster roars, the kid will Cry(). Look at the class and I'll comment it after:

public class Kid
{
    public string Name { get; set; }

    public Kid(string name) {
        this.Name = name;
    }

    public void Cry(object monster, EventArgs e) {
        Monster m = monster as Monster;
        string monsterName = m == null ? "Some monster" : m.Name;
        Console.WriteLine("{0} cries because {1} is roaring.",this.Name,m.Name);
    }

    public void Subscribe(Monster m) {
        m.Roared += Cry;
    }
}

Look at the Cry() method signature. Notice something? It matches perfectly the monster RoarHandler delegate. That's because this is how delegates work (but you already know that as you read my previous posts on delegates). That's the method that will be contained within the RoarHandler and executed when the monster Roar(). The implementation of the method is trivial: we just test that the sender can be converted to a Monster object.

There's one more bit of plumbing needed for it to work. We must implement a Subscribe() method so our object can be connected (or subscribed) to the event. Just as with delegates, adding a method to a delegate is done using the += operator.

That's it for our Kid. Let's create a stub to see this in action.

Time to scare the crap out of kids

In our main program, we create a monster, two kids, enable them to hear the monster roaring and then, we have the monster roars loudly so we can see what happens:

class Program
{
    static void Main(string[] args) {
        Monster m = new Monster("Kaiju");
        Kid k1 = new Kid("Tim");
        Kid k2 = new Kid("Jill");

        k1.Subscribe(m);
        k2.Subscribe(m);

        m.Roar();
    }
}

Running the program outputs this to the console:

Kaiju roars loudly!
Tim cries because Kaiju is roaring.
Jill cries because Kaiju is roaring.

Our kids were notified that the monster roared and they started to cry.

This is not finished

That was the basics of the event model in .NET but we can go further. Remember when I talked about using delegates with anonymous methods? We can refactor our Subscribe() method a little bit by using an anonymous method thus removing the need for the Cry() method. This is how the Kid class looks like now:

public class Kid
{
    public string Name { get; set; }

    public Kid(string name) {
        this.Name = name;
    }

    public void Subscribe(Monster m) {
        m.Roared += delegate(object monster, EventArgs e) {
            Monster m2 = monster as Monster;
            string monsterName = m2 == null ? "Some monster" : m2.Name;
            Console.WriteLine("{0} cries because {1} is roaring.", this.Name, m2.Name);
        }; 
    }
}

I just renamed the second m object to m2 to avoid a name collision.

And now with lambda

To go even further, we could replace the delegate in the anonymous method with a lambda expression. That's what the cool kids do today. That's how the Subscribe() method would look:

public void Subscribe(Monster m) {
    m.Roared += (monster, e) => {
        Monster m2 = monster as Monster;
        string monsterName = m2 == null ? "Some monster" : m2.Name;
        Console.WriteLine("{0} cries because {1} is roaring.", this.Name, m2.Name);
    };
}

Have some sugar

There's also some syntactic sugar for declaring the event. In the Monster class, you could just rewrite these two lines:

public delegate void RoarHandler(object sender, EventArgs e);
public event RoarHandler Roared;

...with this one line which says the same but uses a generic method:

public event EventHandler<EventArgs> Roared;

That's because the definition for the System.EventHandler<> delegate is:

public delegate void EventHandler<TEventArgs>(Object sender, TEventArgs e);

Conclusion

That was a short introduction on how .NET implements the event model. Of course, there's much more to it, like replacing EventArgs with your own arguments class and making use of it. This could be the subject of a future post!


Using a Delegate with an Anonymous method in C#

Read the simple explanation od Delegates in C# I wrote previously.

In the this block of code taken from the example, the operation delegate references the existing Add method:

OperationDelegate operation;
if (opsType.ToLower() == "a") {
    operation = Add;
}

If you didn't have the Add method already created, you could create a method on the fly. This is known as an anonymous method. The previous example is rewritten using an anonymous method:

OperationDelegate operation;
if (opsType.ToLower() == "a") {
    operation = delegate(int a, int b) {
        Console.WriteLine("Anonymous addition: {0}", a + b);
    };
}

It is quite important to understand how to assign anonymous methods to delegates even though anonymous methods are not the flavor of choice anymore. They tend to be replaced by lambda expressions but it would be hard to introduce the subject without having seen anonymous methods first.

I will do an introduction to lambda expressions in a future post but for now, I just want to rewrite the example using one so you can see what it would give:

OperationDelegate operation;
if (opsType.ToLower() == "a") {
    operation = (a,b) => Console.WriteLine("Anonymous addition: {0}", a + b);
}

Parameters are on the left of the => operator and the method body goes on the right.


A simple explanation of Delegates in C#

Ask any developer new to C# about what is one of the most difficult concept to grasp and chances are pretty big that you will get "delegates" as an answer. Syntactically, there's nothing hard about them. The difficulty resides in when and how to use one. Let's see a short, simple and trivial example.

Declaring a delegate

To explain it simply, you can say that a delegate is a special type that can hold a reference to a function. A variable containing a function, if you will. People familiar with C++ could compare a delegate to a function to a pointer.

First of all, you need to declare a delegate. Much like a function, you specify a return type and parameters:

namespace DelegateSample
{
  public delegate void OperationDelegate(int a, int b);

  class Program
  {
      static void Main(string[] args) {
         
      }
  }
}

Functions that can be used by the delegate

The next step is to write one or more function that could be referenced by the delegate. If you want a delegate to reference a function, its signature (return type and parameters) must be the same as the delegate signature:

namespace DelegateSample
{
    public delegate void OperationDelegate(int a, int b);

    class Program
    {
        static void Add(int num1, int num2) {
            Console.WriteLine("Addition: {0}", num1 + num2);
        }

        static void Multiply(int someNum1, int someNum2) {
            Console.WriteLine("Multiplication: {0}", someNum1 * someNum2);
        }

        static void Main(string[] args) {
           
        }
    }
}

Putting the delegate to use

Everything is now in place to use our delegate. Let's assume that we create a small console calculation application. We will prompt the user for two numbers and the type of operation he wants to do (inputs check omitted for clarity):

namespace DelegateSample
{
    public delegate void OperationDelegate(int a, int b);

    class Program
    {
        static void Add(int num1, int num2) {
            Console.WriteLine("Addition: {0}", num1 + num2);
        }

        static void Multiply(int someNum1, int someNum2) {
            Console.WriteLine("Multiplication: {0}", someNum1 * someNum2);
        }

        static void Main(string[] args) {
            Console.Write("Enter a number: ");
            int firstNum = int.Parse(Console.ReadLine());
            Console.Write("Enter another one: ");
            int secondNum = int.Parse(Console.ReadLine());

            Console.Write("What type of ops? (A)ddition or (M)ultiplication: ");
            string opsType = Console.ReadLine();
        }
    }
}

Then, we declare a new variable operation of type OperationDelegate. We test our user's input: if he wants an addition, we assign the Add function to the operation variable. If he wants a multiplication, we store the Multiply method. If he makes no choice, we store both methods! Yes, delegates allow you to store more than one function. Both will be executed one after the other. This is known as a multicast delegate. Be aware that when using multicast delegates, you can't rely on which order the functions will be called.

Assigning a function to a delegate, like with any variable, is done using the = operator. To add another function to a delegate, you do it with the += operator. Let's see this:

namespace DelegateSample
{
    public delegate void OperationDelegate(int a, int b);

    class Program
    {
        static void Add(int num1, int num2) {
            Console.WriteLine("Addition: {0}", num1 + num2);
        }

        static void Multiply(int someNum1, int someNum2) {
            Console.WriteLine("Multiplication: {0}", someNum1 * someNum2);
        }

        static void Main(string[] args) {
            Console.Write("Enter a number: ");
            int firstNum = int.Parse(Console.ReadLine());
            Console.Write("Enter another one: ");
            int secondNum = int.Parse(Console.ReadLine());

            Console.Write("What type of ops? (A)ddition or (M)ultiplication: ");
            string opsType = Console.ReadLine();

            OperationDelegate operation;
            if (opsType.ToLower() == "a") {
                operation = Add;
            }
            else if (opsType.ToLower() == "m") {
                operation = Multiply;
            }
            else {
                operation = Add;
                operation += Multiply;
            }
        }
    }
}

Notice: When you assign a function to a delegate variable, you use the function name without its parenthesis nor its parameters. That is because you want to reference it, not execute it.

Executing the delegate

Like any function, you call the delegate by its variable name, passing in the required parameters:

namespace DelegateSample
{
    public delegate void OperationDelegate(int a, int b);

    class Program
    {
        static void Add(int num1, int num2) {
            Console.WriteLine("Addition: {0}", num1 + num2);
        }

        static void Multiply(int someNum1, int someNum2) {
            Console.WriteLine("Multiplication: {0}", someNum1 * someNum2);
        }

        static void Main(string[] args) {
            Console.Write("Enter a number: ");
            int firstNum = int.Parse(Console.ReadLine());
            Console.Write("Enter another one: ");
            int secondNum = int.Parse(Console.ReadLine());

            Console.Write("What type of ops? (A)ddition or (M)ultiplication: ");
            string opsType = Console.ReadLine();

            OperationDelegate operation;
            if (opsType.ToLower() == "a") {
                operation = Add;
            }
            else if (opsType.ToLower() == "m") {
                operation = Multiply;
            }
            else{
                operation = Add;
                operation += Multiply;
            }

            operation(firstNum, secondNum);
        }
    }
}

Result

Executing the above program, using 10, 20 and a as inputs will output the following:

Enter a number: 10
Enter another one: 20
What type of ops? (A)ddition or (M)ultiplication: a
Addition: 30

If instead of a, you'd input b, you'd get the following result because both Add and Multiply would be called:

Enter a number: 10
Enter another one: 20
What type of ops? (A)ddition or (M)ultiplication: b
Addition: 30
Multiplication: 200

And that's it for delegates. It is the most trivial example I could think of.


Why develop with Microsoft technologies in 2014

Recently, my post on learning to code with C# and .NET got some attention here and there. Some people do question the value of coding for the Microsoft ecosystem using Microsoft technologies such as .NET.

In one small graph, Net Market Share demonstrates this: OS market shares 2014-04

Yep, Windows is still relevant!


Recipe: Using a "where" constraint in a generic class

When building a generic class, the idea is generally to accept any reference type or value type in place of <T>. Sometimes though, you want to restrict the types that can be used as parameter types. For example, if you want <T> to only accept types implementing a certain interface. That's when you'd use the where keyword.

A simple interface and two classes

To demonstrate this quickly, let's build an interface called IAnimal and two classes implementing it: Cat and Dog.

public interface IAnimal
{
    void MakeNoise();
    string Name { get; set; }
}

public class Cat : IAnimal
{
    private string name;

    public Cat(string name) {
        this.Name = name;
    }

    public void MakeNoise() {
        Console.WriteLine("Meow");
    }

    public string Name {
        get {
            return this.name;
        }
        set {
            this.name = value;
        }
    }
}

public class Dog : IAnimal
{
    private string name;

    public Dog(string name) {
        this.Name = name;
    }

    public void MakeNoise() {
        Console.WriteLine("Woof");
    }

    public string Name {
        get {
            return this.name;
        }
        set {
            this.name = value;
        }
    }
}

The generic class

Next, we create a small generic class whose only purpose will be to build a List<T> of IAnimal. That's when we use the where in order to restrict the type parameter to only use types implementing IAnimal.

public class CreateAnimalsList<TAnimal> where TAnimal : IAnimal
{
    public List<TAnimal> List { get; set; }

    public CreateAnimalsList() {
        List = new List<TAnimal>();
    }

    public void AddAnimal(TAnimal value) {
        List.Add(value);
    }
}

Using the generic class

Now, when we use our CreateAnimalsList class, only type parameters implementing IAnimal can be used:

static void Main(string[] args) {

    // create a cat and a dog
    Cat c = new Cat("Luke");
    Dog d = new Dog("Han");

    // Use the generic class to build a list
    // of animals
    CreateAnimalsList<IAnimal> listBuilder = new CreateAnimalsList<IAnimal>();
    
    // add the cat and the dog to the list
    listBuilder.AddAnimal(c);
    listBuilder.AddAnimal(d);

    // let's have them each make some noise
    foreach (var item in listBuilder.List) {
        item.MakeNoise();
    }

    // ERROR: the following would throw an error at compile time
    // CreateAnimalsList<string> listOfStrings = new CreateAnimalsList<string>();

}

What's the use?

You'd use a constraint on a generic class for one purpose: throw an error at compile time rather than at run time which your users could potentially see. Added to that, you'll get full IntelliSense support in Visual Studio for the type(s) you constrain your generic class to.

It may seem like a small thing when designing a system but users happiness and well-being lie in these small things.


Displaying posts 1 - 8 of 71 in total




RailsBricks
An app generator I created to speed up Ruby on Rails development. RailsBricks is open-source. By the way, this site was built with RailsBricks!
HowToCode.io
I founded HowToCode.io to teach high quality web development, for free. The aim is to take students from novice to employable.
Trakx
I love lists. I create many and for everything, really. Trakx is built with RailsBricks and is my own list management tool. It is free and anybody can sign up.
qwikGit
Speeding up Git common actions by wrapping them in single switches. For example, to add, commit, merge and then push to a remote repository, just type qgit -cmp instead of a long serie of Git commands.
qwikGem
The main goal of qwikGem is to quickly create the needed boilerplate code and assets to start creating a CLI-style Ruby gem.