Windows Phone 8 – Samsung ATIV S

After two and a half year of struggling with the crappy Android OS on Samsung Galaxy S I’ve finally decided that ‘enough is enough’.

I’ve wanted a small tablet so I can read (blogs and so on) easily so I was a bit into Samsung Galaxy Note II. Along with the fact that this too is an Android phone (OS which corrupts its own system files and lost my whole user data, lags horribly and so on) several fellow colleagues from RONUA (a local programming user group) warned me against as they already are owners.

One told me that approximately 50% of the phone calls he can’t hear the other party nor he can be heard and the other one told me he is experiencing approximately a complete OS freeze once per day. He is only able to restart the device by removing the battery and reinstering it.

I then looked for another-OS, large-display and low-SAR phone in the market. iOS ‘simply works’, I can’t deny but there was no large screen phone available, no low-SAR phone and nonetheless objective-C sucks incredibly bad.
Ironically I found another Samsung, the ATIV S.


Image source : Engadget

Read more »

Windows Explorer contextual menu gotcha

Recently I had to extract the public key from a signed .NET assembly and I needed to run the sn.exe tool in order to obtain it. That required opening a command prompt and then setting the current directory to the one in which the assembly resided.

Typically I did :

  1. Win+R (Run)
  2. cmd
  3. Enter
  4. F: [ENTER] (or whatever the drive was)
  5. CD and either type the directory (using the TAB autocomplete or not) or copy the folder path and pasting it into the command prompt [ENTER]

Then I thought how can I simplify this little tedious task, which I sometimes do many times a day. After looking for Microsoft PowerToys which is no longer available I found out a little gem hidden in Windows Explorer. This is what my contextual menu looks like normally :

But just pressing (and keeping pressed) SHIFT before the right-click will give you this :

Selecting this command will do the opening of the command prompt and setting the drive and path in one click.

Of course, the next thing is to add the path to SN.EXE in the Environment Variable PATH in order to be able to execute it “anywhere”.

I hope this helps at least some of us 🙂

Some more Android development peculiarities

There is a baked in logging class called, intuitively, Log. For some strange reason the authors chose to name its methods, most of them, with one letter. That is :

Log.d(..); // debug level
Log.e(..); // error level
...

Until you hit

...
Log.wtf(..);
...

This one’s funny and I appreciate their sense of humor as it goes up to renaming WTF to “What a Terrible Failure”. Like we’re so dumb that we can’t figure what they really had in mind 😛

Another peculiarity is that in an activity (this akin to a Page / Form / whatever) you have some methods that you can/should override such as onCreate(). Everywhere is stated that the first thing you should write in the overriding method is a call to the super (that is base) class’s method. If it is really all that important and vital why didn’t the class designers go with a template method in first place?

That is a design pattern, that in this case, would go like so :

public class Activity {

    // ...

    private void onCreateInternal(Bundle savedInstanceState) {
        //vital stuff
        onCreate(savedInstanceState);
    }

    protected void onCreate(Bundle savedInstanceState) {
    }

    // ...

}

Take note of another difference between C# and Java : the methods and classes are virtual/unsealed by default. So the onCreate method in my example above is overrideable in any subclass. Also in Java terminology the base class is called the superclass.

Other differences of terminology include :

  • A namespace is called a package
  • By default an import (which is akin to a using directive) imports by default just the specified type and not the whole package (namespace). You need to use a wildcard to import the whole package
  • The closest thing to an assembly is called a JAR (Java ARchive).
  • Eclipse by default is set to autocompile. That is whenever you hit CTRL-S (Save) to a Java file the project is (re)compiled. This sounds terrible but it isn’t! You can’t even notice. Either there is an incremental compilation either the performance of the compiler is incredible.
  • Unlike Visual Studio, Eclipse presents the import block collapsed by default. I wish I had this in VS… Just like a mobile app fan would say “there’s an app for that”, I bet for VS “there’s a plugin for that” 😛
  • In Java if you want to call the super (base) class’s constructor from the current class’s constructor you will write “super(…);” in the constructor’s body. When I first saw this I said to myself Fu-Kin-Su-Pa (er… “great”, that is). “Now I have the liberty to call the base/super constructor from wherever inside the constructor I want”. Well, no. It’s either the first line or it isn’t.

Well, I’ll rant more as I go learning Android development.

My goal is to get to know enough so I can do it in Xamarin via C# but first I must understand the underlying things in order to go a level of abstraction above.

In the next episode(s) : I am indebted with a follow-up from my presentation held at RONUA last year.

Java / C# differences part 1 of n

Recently I’ve been toying around with Android development (since I own an Android “smart” phone for over 2 years now) and mobile development is all the rage now. Moreover, I’ve been trying to do new things lately since even the pragmatic programmer guide advises us to learn a new language each year (kind of aggressive if you ask me).

Anyway I will try to show what a C# developer (almost 8 years now) discovers by doing Java development on Eclipse for Android.

For today :

leaving a member of a class without an access modifier defaults to internal instead of private :

// C#
void Test() // private method
{
}
// Java
void test() { // internal method
}

Overriding a method does not require any kind of keyword or special ceremony. You can use the @Override annotation but this is optional. You can get burned this way easily.

// C#
public override bool Equals(object other)
{
    return _id == other._id;
}
// Java; WRONG! DO NOT USE
public bool equals(Person other) {
    return this.id == other.id;
}

//Correct
public bool equals(Object other) {
    return this.id == other.id;
}

Overriding requires that you use the same method signature (that is, the same return type, the same parameter types and order). If you accidentally mistake the signature (Person instead of Object) you will overload instead of overriding with unknown effects.

Read more »

Efficiently serving binary content from SQL Server in ASP.NET MVC – local user group talk

This will be a local user group talk that I’ll be having, in Bucharest on Tuesday 13th of November.

Storing large binary objects (usually image files) in the RDBMS has been a blessing but for some is unconceivable. We will explore different ways to do this, from worse to best and we will take advantage of a new feature introduced by SQL Server 2012.

The location is TeamNet Int’l HQ – Sema Parc, Splaiul Independenţei nr. 319, clădirea RiverView, etaj 8
Except an ID there is nothing else that you need to bring in order to participate to the event.
Further geographical details.

The most popular way to get there is by taking the subway as there is a station right near the building.

The official announcement can be found on RONUA’s site.

See you there!

——–

Later edit : It’s been great! Not too many people but keen to learn new stuff. Here’s two pictures from the talk. Notice a new generation of programmers forming 🙂

Type check and inheritance – and a nice ReSharper tip

Let’s suppose you have three classes in a simple hierarchy :

public class A
{
}

public class B : A
{
}

public class C : A
{
}

Now suppose you receive an instance of one of these classes (you don’t know the exact type to which this instance belongs). How can you determine programatically if the instance is of a type inheriting from A or it is of type A exactly?

Normally I would do the following :

var instance = ObtainInstanceFromSomeWhere(); // this method will not return null
var instanceIsExactlyOfTypeA = typeof(A) == instance.GetType();
var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsAssignableFrom(instance.GetType());

All these work and are nice and dandy. However ReSharper showed me a nicer alternative to the last statement :

var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsInstanceOfType(instance);

Now, pro’lly, many of you knew about this method but I didn’t! 🙂
Hopefully it will help someone..

CallerMemberName – an easier way to do INotifyPropertyChanged AND MORE

In WPF, when applying the MVVM (an arhitectural pattern) we often need to implement the INotifyPropertyChanged on certain classes (ViewModel classes), which means something like this :


public class PersonViewModel : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name == value) return;
            _name = value;
            NotifyPropertyChanged("Name");
        }
    }

    private void NotifyPropertyChanged(string propertyName)
    {
        var evt = PropertyChanged;
        if (evt != null) evt(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

In case you’re wondering why I copied the PropertyChanged value to the local variable called “evt” and then tested it for null is that you can have race conditions, in general, triggering events (i.e.: you test the attribute value, it is not null and before you trigger it some other thread sets it to null and bang, NullReferenceException when you trigger it). More details on this CodeProject.

The next step is to pull the NotifyPropertyChanged method and PropertyChanged event into a base class (let’s call it ViewModelBase) and you’ve eliminated redundancy between several ViewModel classes.

The not-so-nice part is having the call to NotifyPropertyChanged stringly-typed. That means that if later you rename (via Visual Studio or ReSharper) the Name property to “FullName” the call will still pass “Name” as the argument.

Some blog posts around the web show how you can use a Func to make it type-safe (refactor safe etc).

More or less they’re doing the same thing :


public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(Expression<Func<object>> propertyAccessor)
    {
        var evt = PropertyChanged;
        if (evt == null) return;
        var propertyName = propertyAccessor.GetName();
        evt(this, new PropertyChangedEventArgs(propertyName));        
    }
}

public static class Utils
{
    public static string GetName(this LambdaExpression expression)
    {
        MemberExpression memberExpression;
        if (expression.Body is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)expression.Body;
            memberExpression = (MemberExpression)unaryExpression.Operand;
        }
        else if (expression.Body is MemberExpression)
        {
            memberExpression = (MemberExpression)expression.Body;
        }
        else
        {
            return null;
        }
        return memberExpression.Member.Name;
    }
}

This is definitely nicer, not-redundant and type-safe. It does have the drawback of having some runtime performance penalty associated with the reflection of the expression. You could cache the property name string in a private field but then you’d have to write more code in the ViewModel classes which would… suck. In practice this performance penalty is negligible so you can just ignore this.

Then came .NET 4.5 and among other improvements a new mechanism has been introduced : CallerMemberName.

Historically some folks tried to get programatically the name of the caller method by inspecting the StackTrace (for example using System.Environment.StackTrace) but this is prone to errors since in Release mode the compiler could eliminate some methods by inlining them and you’ll be screwed. Plus the penalty would be higher than reflecting an expression.

The new mechanism in .NET 4.5 is type-safe, has no runtime performance penalty and it’s more elegant. Here’s how you can use it :

public abstract class ViewModelBase : INotifyPropertyChanged
{
    protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var deleg = PropertyChanged;
        if (deleg != null)
        {
            deleg(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class PersonViewModel : ViewModelBase
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name == value) return;
            _name = value;
            NotifyPropertyChanged();
        }
    }
}

I’ve recently built a very small GuidGen utility (which as the name implies generates GUIDs, copies it in the Windows Clipboard and stores a history of past generated GUIDs). You can browse some of the code and check out the project.

Much nicer, isn’t it?

Funny thing, this new mechanism can be used for non-UI tasks. For example if you have a project that uses and RDBMS and you use stored procedures. Let’s say you have one method in a repository class for each stored procedure, and even more, the method’s name matches the stored procedure’s name :


public VerificationResult VerifyUser(VerificationData verificationData)
{
    if (EmailValidator.IsEmailInvalid(verificationData.EmailAddress)) throw new FormatException("emailAddress");

    var result = CreateNewCommand("VerifyUser").GetEnumResult<VerificationFailReason>(
        CreateEmailAddressParameter(verificationData.EmailAddress),
        CreateUniqueIdentifierParam("@VerificationCode", verificationData.VerificationCode));

    return new VerificationResult(result);
}

Observe on line 5 how the call to CreateNewCommand passes a string which matches the current method’s name. This can also be simplified (and become refactor-safe) using the new CallerMemberName mechanism.

So you can’t really say that CallerMemberName is useful only for UI tasks 🙂

OUTPUT clause in UPDATE statements

Sometimes you need to update data in a table and then update data in another table but based on a filter condition found from the first table. Specifically have you had to do this in the past?


-- ...

UPDATE Users
SET    Verified     = 1
FROM   Logins
WHERE  EmailAddress = @EmailAddress

DECLARE @UserId INT;

SELECT TOP 1
       @UserId = UserId
FROM   Logins
WHERE  EmailAddress = @EmailAddress

UPDATE  Users
SET     State = 2 -- Verified
WHERE   Id = @UserId

-- ...

This is not only inefficient (from an execution plan perspective) but also prone to race conditions and requires more code. The simpler and safer alternative is to use the OUTPUT clause of the UPDATE.

Here’s how :

DECLARE @UserIdTable TABLE ( Id INT );

UPDATE Users
SET    Verified     = 1
OUTPUT UserId
INTO   @UserIdTable
FROM   Logins
WHERE  EmailAddress = @EmailAddress

DECLARE @UserId INT = SELECT TOP 1 Id FROM @UserIdTable;

UPDATE  Users
SET     State = 2 -- Verified
WHERE   Id = @UserId

In the above code sample I take advantage of the new declare and initialize syntax introduced in SQL Server 2008. The OUTPUT clause has been introduced in SQL Server 2005 so nothing here is really news.

Another simplification that I hoped it was possible was to avoid the declaration of the local table variable and just push the OUTPUT into the local variable (@UserId) but it seems you can’t.

I found out about the OUTPUT clause recently from Remus Rusanu’s blog post about implementing queues with tables. These have, usually, high concurrency and any race condition that might occur will occur. OUTPUT is usually the best way to solve it.

Prefix cast or as-cast?

I read today a nice article, from Kathleen Dollard, called To “as” or not to “as”. This is a pain-point for me on which I stumble often, so I decided to write this little rant.

I particularly liked a paragraph from the above-cited article :

One of the things that makes hard bugs hard is when there is a disconnect in time or space between the cause and the symptom. Time is time, space is lines of code, assembly placement, etc. Code can be written to minimize these disconnects. One of the ways to do that is to fail quickly. When application state becomes incorrect, yell about it immediately and rarely continue with the application in an invalid state. A null-reference exception at an unexpected time just makes code more difficult to debug.

I couldn’t express this as good as Kathleen did. Make no mistake I am quite biased in this comparison (direct-cast vs. as-cast). I kind of hate the abuse of the as operator.

Very often people turn to as instead of the direct (prefix) cast because:

  • They fear the InvalidCastException (strange, they don’t seem to fear the NullReferenceException)
  • They feel the syntax more fluent, closer to the human language.

I would consider the only valid case to use the as-cast is, just like Kathleen states, when a null value result is valid for the rest of the execution of the code. For the rest of the cases it’s just wrong.

This also promotes (doesn’t necessarily causes but promotes) bad practices like this :


public static void OnButtonClick(object sender, EventArgs e)
{
    var button = sender as Button;
    if (button == null)
    {
        return;
    }
    if (button.Tag == &quot;somevalue&quot;)
    {
        // do something
    }
    // ...
}

In this example the event handler (which could be attached to more than one distinct button) simply forces under the rug a situation which would be abnormal (the sender not being a button) instead of releasing it so the developers could find it easier and debug it. A saner approach is :


public static void OnButtonClick(object sender, EventArgs e)
{
    var button = (Button)sender;
    if (button.Tag == &quot;somevalue&quot;)
    {
        // do something
    }
    // ...
}

This brings me to another advantage of the prefix-cast : it produces shorter, clearer code.

In other cases the as abuse does more harm, hiding the source of a bug :


public void ProcessData(Entity entity)
{
    var person = entity as Person;
    UpdatePersonStatistics(person);
    // .. more code
}

public void UpdatePersonStatistics(Person person)
{
    NormalizeData(person);
    // .. more code
}

public void NormalizeData(Person person)
{
    person.Name = person.Name.Substring(0, 50);
    person.Address = person.Address.Substring(0, 100);
    // .. more code
}

Of course this is a contrived example full of bad practices but for now let’s focus on the as usage. Suppose the ProcessData method receives an instance of Category by mistake. Since Category inherits Entity the compiler will not complain.

The result is that there will be a NullReferenceException two methods further, in the NormalizeData method. If the cast was done with a prefix cast the error was a little bit easier to spot. This is confusing two-fold :

  1. The name of the exception suggests that a null reference was somehow obtained but in fact a real instance of Category was passed, not a null
  2. The error does not originate from the NormalizeData code but from the caller of the ProcessData

Summary

Use as only if a null result of the conversion makes sense for the flow of the execution. Otherwise use prefix cast.

ReSharper hidden features – Generate Delegating Members

A frequently-used design pattern is the Decorator. This is also known as a mixin (or they might not be the very same thing but certainly they are related).

Typically you might need to create a class that implements a certain interface and uses another class that implements that exact interface but you need to provide some additional feature(s). An example would be a class that adds transactional behavior to an existing data-access class (a naive example) :


public interface IDataAccess
{
    void AddCustomerInvoice(Invoice invoice, User user);
}

public class DataAccess : IDataAccess
{
    public void AddCustomerInvoice(Invoice invoice, User user)
    {
        InsertInvoice(invoice, user);
        UpdateCustomerDebt(user, invoice.Total);
    }

    // ... the rest of the implementation
}

public class TransactionalDataAccess : IDataAccess
{
    private readonly IDataAccess _dataAccess;

    public TransactionalDataAccess(IDataAccess dataAccess)
    {
        if (dataAccess == null)
        {
            throw new ArgumentNullException();
        }
        _dataAccess = dataAccess;
    }

    public void AddCustomerInvoice(Invoice invoice, User user)
    {
         using(var tx = new TransactionScope())
         {
             _dataAccess.AddCustomerInvoice(invoice, user);
             tx.Complete();
         }
    }

    // ... the rest of the implementation
}

Another type of example would be the Adapter design pattern. An example would be providing access to a (static) class (that may be out of your control) in a mock-able manner. That is, implement another class, non-static, which implements a defined interface and eases unit-testing :

Read more »