/page/2

Logging JavaScript errors in ASP.NET in three easy steps

If you are like me, you like to know about errors you missed especially those on fussy devices like an iPad. I had this in mind for quite some time to just log all JavaScript errors (I mean in particular app not all on interwebz) but I never actually did it. So I started googling tonight and I found that there is a very good NuGet for this called JSNLog by Matt Perdeck!

Thus this will be very easy. Let’s start with a new ASP.NET project (I used MVC 5 but you can use whichever framework you like).

① Run two following commands in Package Manager Console to install NLog and JSNLog:

Install-Package NLog.Config
Install-Package JSNLog.NLog

Then open NLog.config and uncomment target and logger elements.

② Open a view file (e.g. Index.cshtml) and add:

@Html.Raw(JSNLog.JavascriptLogging.Configure())
<script src="~/errorlogger.js"></script>
<script>
    window.setTimeout(foo, 1000);

    function foo() {
        bar();
    }

    function bar() {
        throw new Error('bar');
    }
</script>

(The Html.Raw line is taken from JNLog documentation).

③ Add new file errorlogger.js to project root and paste this (taken from JNLog documentation):

window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
    // Send object with all data to server side log, using severity fatal, 
    // from logger "onerrorLogger"
    JL("onerrorLogger").fatalException({
        "msg": "Exception!",
        "errorMsg": errorMsg, "url": url,
        "line number": lineNumber, "column": column
    }, errorObj);

    // Tell browser to run its own error handler as well   
    return false;
};

That’s it! If you run the project a bar error should be logged in logs project subfolder as follows (line breaks added):

2014-09-17 22:15:46.3326 FATAL {"stack":"Error: bar
    at bar (http://localhost:47091/:53:15)
    at foo (http://localhost:47091/:49:9)",
    "message":"bar","name":"Error","logData":{"msg":"Exception!",
    "errorMsg":"Uncaught Error: bar","url":"http://localhost:47091/",
    "line number":53,"column":15}}

On JSNLog page you can learn that this is a full-blown logging library and is also available for Node.js.

Delphi, ANSI Strings, diacritics and Windows 8

This is a quicky. My custom Delphi component caused problem on Windows 8. The Delphi version we are talking about is 2007 and component is not Unicode (is ANSI). The problem is when I copy or paste text with diacritics, even that I have “Language for Non-Unicode programs” Windows setting correctly set to support diacritics in question, diacritics are copied incorrectly and lost on pasting. I haven’t this problem on Windows 7 or prior so either this is something fundamental to Windows 8 or just my language settings are bit different than previously (Windows 8 has a new way of configuring those things using some kind of “language profiles”).

Nevertheless, the solution was simple. I found out that my component was calling Clipboard.AsText which is ANSI. I simply replaced calls with Clipboard.AsWideText and now it works!

But wait, there is no Clipboard.AsWideText!

You’re right. Thankfully I had CopyToWideClipboard procedure in my utils unit. I can’t tell the author (I probably got it on Usenet) because unit is really old but here it is:

procedure CopyToWideClipboard(AText: WideString);
var
    Data: THandle;
    DataPtr: Pointer;
    Size: Cardinal;
begin
    Size := Length(AText);
    Data := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, 2 * Size + 2);
    try
        DataPtr := GlobalLock(Data);
        try
            Move(PWideChar(AText)^, DataPtr^, 2 * Size + 2);
            Clipboard.SetAsHandle(CF_UNICODETEXT, Data);
        finally
            GlobalUnlock(Data);
        end;
    except
        GlobalFree(Data);
        raise;
    end;
end;

I didn’t have PasteFromWideClipboard but I used TClipboard.GetAsText as a template and here you go:

function PasteFromWideClipboard: WideString;
var
    Data: THandle;
begin
    Clipboard.Open;
    Data := GetClipboardData(CF_UNICODETEXT);
    try
        if Data <> 0 then
            Result := PWideChar(GlobalLock(Data))
        else
            Result := '';
    finally
        if Data <> 0 then
            GlobalUnlock(Data);
        Clipboard.Close;
    end;
end;

Inherited public property with protected mutator in .NET Reflection eyes

I found this issue when migrating Windows Phone 7 application to Windows Phone 8. To illustrate the issue, simplified view model looks like this:

public class Sub : Super
{
    public Sub()
    {
        MyProperty = "foo bar";
    }

    public override string MyProperty
    {
        protected set
        {
            base.MyProperty = value;
        }
    }
}

public class Super
{
    public virtual string MyProperty { get; protected set; }
}

The view model in use is Sub class which has inherited public MyProperty with protected mutator. This property was bound like this (XAML):

<TextBlock x:Name="PageTitle" Text="{Binding Path=MyProperty}"/>

In Windows Phone 7 this is displayed as “foo bar” but the same app on Windows Phone 8 (either as a WP 7.1 app or as migrated to WP 8) doesn’t like this binding:

System.Windows.Data Error: BindingExpression path error: ‘MyProperty’ property not found on ‘Blah.Sub’ ‘Blah.Sub’ (HashCode=51812368). BindingExpression: Path=’MyProperty’ DataItem=’Blah.Sub’ (HashCode=51812368); target element is ‘System.Windows.Controls.TextBlock’ (Name=’PageTitle’); target property is ‘Text’ (type ‘System.String’)..

Let’s make sure this has something to do with reflection:

MessageBox.Show(typeof(Sub).GetProperties().Length.ToString());

Indeed, message says “1” on Windows Phone 7 and “0” on Windows Phone 8.

Let’s try full .NET:

var sub = new Sub();
Console.WriteLine(sub.MyProperty);
Console.WriteLine(typeof(Sub).GetProperties().Length);

This console application prints same result on each .NET Framework version I have on laptop (2.0 - 4.5.1)

foo bar
0

The result is consistent with WP8. Perhaps WP7 was buggy? This is documentation for parameter-less Type.GetProperties:

Returns all the public properties of the current Type. A property is considered public to reflection if it has at least one accessor that is public.

MyProperty has public accessor. If you doubt it, see that we could read it fine in our console application: Console.WriteLine(sub.MyProperty).

So why it’s not returned by parameter-less GetProperties and we have to use overload accepting BindingFlags.NonPublic to get it? Is WP7 right?

The fix is just adding:

get
{
    return base.MyProperty;
}

Few comments on Swift Programming Language (part V)

This is final part of my wee notes on new programming language from Apple called Swift.

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

I have seen in passing similar feature in Oxygene language. This is convenience feature and as such should be praised but in reality isn’t it encouraging to Law of Demeter violating? I can see it being helpful while navigating data structures of some API when doing something quickly in a script or when writing not so good UI code and trying to display some deeply hidden value from data structure but nothing beyond that comes to my mind (I might be missing something though).

let roomCount = john.residence?.numberOfRooms

On the syntax level optional chaining feature feels cheap - you only need to add ? before .. But if you write unit tests, you still need to test this. Thus it’s better to write this alternatively so there is less to test. And this code is a violation of rule (‘law’) mentioned above anyway. Having said that this can be a nice tool when dealing with deeply data-structured external API as stated above and just shouldn’t be overused.

Another possible problem with optional chaining I can think of is when you have chain looking like variable.foo?.bar?.field and you are expecting that bar can be nil but foo rather shouldn’t be nil but since you are using optional chaining you want to use it here as well - nil is accepted result anyway. Then few months later something changes and foo is nil not as an exception but as a normal business situation which needs to be handled separately. Then you have a problem because when foo is nil the effect will be the same as when bar was nil so you will not get any exception and everything will look okay at a first glance… Obviously this is not be a problem when doing TDD.

if john.residence?.printNumberOfRooms() {

Will control flow enter if body when printNumberOfRooms function will return false? Yes, because all what is required to satisfy this if condition is residence to be assigned. Feels like magic trick although it’s in sync with language rules. Still, no magic tricks in language is less bug provoking.

init(name: String, director: String) {
    self.director = director
    super.init(name: name)
}

It’s nice to see you again, the ability to set order of superclass constructor execution (like in Delphi) instead of always executing it before derived class constructor (like in C# and Java). Yes, it can be dangerous but it can be also sometimes useful and the choice simply should be given.

let library = [
    Movie(name: "Casablanca", director: "Michael Curtiz"),
    Song(name: "Blue Suede Shoes", artist: "Elvis Presley")
]
// the type of "library" is inferred to be MediaItem[]

Wow, type inferring for collections! Even TypeScript, whose type inferring is very robust, doesn’t do it!

if let movie = item as? Movie {

Right, in this example the if let variable = <optional> form impresses with brevity. Note that as? works like as in other languages (safe cast).

An extension can extend an existing type to make it adopt one or more protocols. Where this is the case, the protocol names are written in exactly the same way as for a class or structure:

extension SomeType: SomeProtocol, AnotherProtocol {
    // implementation of protocol requirements goes here
}

This is interesting. Generally extensions in Swift look like a similar idea to extension methods in C# but they can do more things than just attaching methods to type. Some of those things (e.g. ‘Provide new initializers’, ‘Define and use new nested types’) are not much helpful as extensions in OO programming so I’ll not talk about them. But ability of making an existing type to conform to a protocol (I understand it as making implicit Adapter) sounds very nice and can simplify Adapter writing and using.

The only gotcha is the name itself. People use term ‘extension’ in C# for example for: extension method, subclass, partial class. Naming language feature just ‘extension’ doesn’t help. But Objective-C name for similar concept (‘category’) wasn’t intuitive neither.

If a class has a superclass, list the superclass name before any protocols it adopts, followed by a comma:

class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {

Syntax is exactly like C#. The only obvious difference: protocol in Swift is what interface is in many other languages. And it seems that Swift is free from ‘begin interface name with I' convention.

A protocol can require any conforming type to provide an instance property or type property with a particular name and type.

Speaking of experience of person who did it wrong: in good OO programming you are doing something wrong if you need property on interface. You only should have methods there.

protocol Togglable {
    mutating func toggle()

In theory it’s useful that mutating keyword can be used in interface because it’s important information for the caller. However mutating only applies to structures (cannot be used in classes).

I cannot see why one would write interface for structure other than maybe using structure instead of class for it’s memory specifics (though that would be misleading perhaps unless used coherently)? I’m just speculating here. Personally I’ve never written interface for structure although it’s possible in C# too and I always use structures only for data structures purpose so I don’t need to interface them.

protocol DiceGameDelegate {
    func gameDidStart(game: DiceGame)

Oh, the Java way. No direct support for events in Swift.

func wishHappyBirthday(celebrator: protocol<Named, Aged>) {
    println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!")
}

Protocol composition (<Named, Aged> in example above) is like telling that instance should implement both (or more) interfaces. In languages without this feature (such as C#, Java) this is often done by making new interface which inherits from two (or more) interfaces. But interface multiplying isn’t a good thing. On the contrary - reusable interfaces specific to single task type are good. Thus protocol composition seems like a very good feature in Swift because it promotes usage of well cut interfaces. The only gotcha is that if class implements two interfaces then almost by definition it has too much responsibility.

@objc protocol HasArea {

In order to use as or is operators on the left hand side of protocol you need to use special attribute (@objc) on protocol definition. That’s like enabling RTTI for only one type so it is probably optimal but still odd compared to some mainstream languages.

@objc protocol CounterDataSource {
    @optional func incrementForCount(count: Int) -> Int

The @optional attribute of interface method means that class implementing interface doesn’t have to implement this particular method. This is interesting because sometimes when class doesn’t implement a method, a dummy method which throws exception is written. This violates Liskov substitution principle. Using @optional instead wouldn’t violate it. At least in my opinion. The other matter is whenever interface is well designed if some of its methods is optional in the first place.

if let amount = dataSource?.incrementForCount?(count) {
    count += amount
} else if let amount = dataSource?.fixedIncrement? {
    count += amount
}

In this example the incrementForCount and fixedIncrement are both optional methods. If dataSource is our dependency, shouldn’t it do what we ask it for according to our preferences instead of forcing us to query it for implemented methods?

protocol Container {
    typealias ItemType
    mutating func append(item: ItemType)

Type alias (typealias ItemType above) is a way of making interfaces generic in Swift. It’s disappointing that usual generics syntax (type parameters after name) that works for classes, structures and functions cannot be used for interfaces in Swift.

One interesting rare thing which Swift does is that you don’t have to specify concrete (or generic) replacement for type alias in implementation as long as Swift can infer it. Most likely Swift designers thought that this is good reason to move type parameters away from interface name.

func allItemsMatch<
    C1: Container, C2: Container
    where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
    (someContainer: C1, anotherContainer: C2) -> Bool {

Use of type aliases instead of type parameters implies also different way of specifying constrains on them as can be seen above. The same effect could be achieved in other languages the usual way by declaring three type parameters (two for containers and one for item).

operator prefix +++ {}

The above code defines operator +++ which can be then overloaded by any types as required. This is not only operator overloading but also defining completely custom operators as long as they consist of / = - + * % < > ! & | ^ . ~ characters. Not something we find in C# or Java. Rare feature but do we have real good use for it? Badly used operator overloading can obviously be very misleading. Maybe rightful introduction of new operators will not be that bad as long as they differ visually enough from existing operators and are used consistently in project.

Thanks for reading. Head over here to read the previous comments on Swift.

Few comments on Swift Programming Language (part IV)

This is continuation of three previous comments on the Swift language.

The capabilities described above for computing and observing properties are also available to global variables and local variables. Global variables are variables that are defined outside of any function, method, closure, or type context.

World is fine without global variables, no need to go there again.

However, you can also define computed variables and define observers for stored variables, in either a global or local scope. Computed variables calculate rather than store a value, and are written in the same way as computed properties.

Why not just write a method?

For value types (that is, structures and enumerations), you can define stored and computed type properties. For classes, you can define computed type properties only.

Lets forget for a moment about existence of computed properties and think only about stored properties. What you can read above is very surprising. It seems at a first glance that this should be the other way around. But think about it. Structures are to hold data. If you really need (in these rare situations) to hold static data, hold it in a structure. Keep classes free of static data. Bravo!

Methods in Swift are very similar to their counterparts in Objective-C. As in Objective-C, the name of a method in Swift typically refers to the method’s first parameter using a preposition such as with, for, or by, as seen in the incrementBy method from the preceding Counter class example. The use of a preposition enables the method to be read as a sentence when it is called.

This is something I like very much. It just makes sense for reasons I mentioned in previous parts.

The second argument, however, is qualified by an external parameter name to make its purpose clear when the method is called. This default behavior effectively treats the method as if you had written a hash symbol (#) before the numberOfTimes parameter: func incrementBy(amount: Int, #numberOfTimes: Int) {

So by default the call will have (?) to look either incrementBy(5, numberOfTimes: 10) or incrementBy(amount: 5, numberOfTimes: 10). It should be like this in every language!

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods. However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method.

Constants department is excels again!

mutating func moveByX(deltaX: Double, y deltaY: Double) {
    self = Point(x: x + deltaX, y: y + deltaY)
}

This is one of those things in Swift. What this code does is just reninitalization of structure from itself. Why?

subscript(index: Int) -> Int {
    get {
        // return an appropriate subscript value here
    }
    set(newValue) {
        // perform a suitable setting action here
    }
}

This syntax for handling index operator (subscript in Swift) looks elegant and is just a mixture of C# solution to same problem and TypeScript way of declaring return type. It’s hard to not like it but indexes are not that often defined for custom types.

A class or structure can provide as many subscript implementations as it needs, and the appropriate subscript to be used will be inferred based on the types of the value or values that are contained within the subscript braces at the point that the subscript is used.

Allowing and supporting this is not the best idea in my opinion because of it’s threat to code expressiveness.

The next code snippet defines three variables of type Person?, which are used to set up multiple references to a new Person instance in subsequent code snippets. Because these variables are of an optional type (Person?, not Person), they are automatically initialized with a value of nil, and do not currently reference a Person instance. var reference1: Person?; var reference2: Person?; var reference3: Person?;

Two interesting thing there.

  1. It looks like you need to use optional to be able to assign nil to reference type variable. So no optional means no nil as a valid value for reference type variable? That’s really good. If existence of optionals allows me to control this, I’m officially a little bit less pained with optionals.

  2. Local variable was automatically initialized with default value. Normally it’s the instance variable who is automatically initialized with default and local who is not but Swift is different.

Because a weak reference does not keep a strong hold on the instance it refers to, it is possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference to nil when the instance that it refers to is deallocated. You can check for the existence of a value in the weak reference, just like any other optional value, and you will never end up with a reference to an invalid instance that no longer exists.

Automatically sets to nil. This is very nice feature. No one likes these memory access errors!

Like weak references, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is assumed to always have a value. Note also that Swift guarantees your app will crash if you try to access an unowned reference after the instance it references is deallocated. You will never encounter unexpected behavior in this situation. Your app will always crash reliably, although you should, of course, prevent it from doing so.

Another very nice feature. It’s much easier to find a bug when application will always crash on memory access violation rather than have random behavior depending on current memory state which makes it one of my favourite Swift features.

Place the capture list before a closure’s parameter list and return type if they are provided: @lazy var someClosure: (Int, String) -> String = { [unowned self] (index: Int, stringToProcess: String) -> String in

So if you want to use capture list in closure (to break ARC reference cycle) you bet the closure is parameterless otherwise Swift requires typing parameter list (types) two times.

@lazy var someClosure: () -> String = {
    [unowned self] in

That’s better but still, Swift, can’t you just automatically treat self as a weak reference in closures assigned to instance as per declaration? If someone just returns closure from a method that’s fine, use strong reference. I just don’t like to repeat this [unowned self] in each time. Better (because shorter) than [unowned self] in would be also @lazy var someClosure: (self) -> String = { if you need to be a little explicit, Swift.

Few comments on Swift Programming Language (part III)

This is continuation of two previous sketches on Swift language.

In its simplest form, an initializer is like an instance method with no parameters, written using the init keyword: init() {

It looks like Swift inherited from Objective-C a rarity of replacing commonly known ‘constructors’ with ‘initializers’.

To create a new instance of Vehicle, call this initializer with initializer syntax, written as TypeName followed by empty parentheses: let someVehicle = Vehicle()

No new keyword? This is fine with me. Can’t confuse it with anything else because in Swift the norm is to use camelCase for function names.

You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the @final attribute before its introducer keyword

In Swift all methods (and properties, ugh) are virtual by default. If you want to make it, er, final, you need to use @final attribute. Some very smart people will argue that it’s a part of class design to specify which parts are intended to override and which are not. On the other hand, how many times were you disappointed that you can’t override method when it could make complete sense but that method just wasn’t virtual? There are two sides to a coin. One is Java and the other is C#.

One could say that if you write SOLID code you shouldn’t be normally worried that one of methods can be overwritten (on the contrary) and you can always use final if that’s the case. However there are edge cases, e.g. versioning problem known in Java so it seems just safer to type that virtual every time it makes sense instead of having it by default. If you ask me, I understand both camps.

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

This can be redundant code to write. What’s wrong with automatic defaulting integers to 0 and booleans to false? I’ve to admit though that type inference in property declarations can mitigate this inconvenience but only when type inference can unambiguously work.

init(fromFahrenheit fahrenheit: Double) {
...
init(fromKelvin kelvin: Double) {

No need to use static methods with different names if required are two constructors with same input argument types. Argument naming to the rescue. It’s a nice feature of Swift.

You can modify the value of a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes.

Apparently in Swift a constant property (let text: String) works similar as readonly field in C# (very useful). Only the name ‘constant’ does sound awkward when you don’t see constant value in declaration - it will be set in initializer. It’s bad if we can set value in declaration and then modify it in constructor, er, initializer because otherwise you could say looking at declaration that this is a typical constant (has value) or just a read only (no value yet).

If default memberwise initializer (available only in structs) works with constant properties this combo can save some typing.

convenience init() {

Convenience initializers do seem complicated but apparently it’s basically telling that this initializer cannot be directly used in derived classes but users of this class can use it directly as Good Defaults initializer. In exchange for this ‘limitation’, base class’s convinence initializers are inherited and avaialbe for derived class’s users and they will internally call derived class’s normal (so-called ‘designated’) initializer. Effectively, designated initializer is virtual. It is also overwritten implicitly. Convenience initializers are also virtual and overwritten implicitly and apparently they can overwrite designated initializer too.

I would say this is ambitious initializer design and being a little complicated itself it leads to avoiding duplication in code so I like it but I have to try it. I think that named parameters will play important role in making this initializer jungle work in real project.

If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.

Even when all designated initializers take parameters? This can save us some typing!

class SomeClass {
    let someProperty: SomeType = {
        return someValue
        }()
}

Something which JavaScript user would call a self-executing function is a good citizen in Swift and can be used to initialize class fields. You can’t access other instance members during this initialization so it’s a nice feature if used with care. I have to try this technique in TypeScript.

Few comments on Swift Programming Language (part II)

This is second part of my wee notes on new programming language from Apple called Swift. Again, this is only after reading language guide, so not exhaustive!

Define an enumeration type called Barcode, which can take either a value of UPCA with an associated value of type (Int, Int, Int), or a value of QRCode with an associated value of type String.

If one needs to keep value with enum wouldn’t be class hierarchy instead of enum easier and simpler and more future-proof?

class VideoMode {
    var resolution = Resolution()
    var interlaced = false

I like type inference in fields declarations. For comparison with another safely-typed language, C# does this too and with same syntax but only for local variables, not for fields. The reason I like it is that we don’t need to repeat ourselves and type Resolution two times there.

Identical to (===)

Swift has both identity and equality operators for objects. There is only one character difference between those operators (=== and ==) which makes me worried. It seems to me that e.g. C# did this better, as you cannot confuse == with Equals.

Swift’s Array and Dictionary types are implemented as structures.

I understand that they are also possibly allocated on the stack and that’s fast.

The assignment and copy behavior for Swift’s Array type is more complex than for its Dictionary type. For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array.

var a = [1, 2, 3]
var b = a
a[0] = 42
println(a[0])
// 42
println(b[0])
// 42
a.append(4)
a[0] = 777
println(a[0])
// 777
println(b[0])
// 42

If you assigned array to two variables and modify element of array, both variables are affected by change (you have same array). But if you changed size of array then only one of variables is changed (you have two arrays). From code reader perspective it does (not) look like append has surprising side effect!

One can always use dictionaries as arrays (think JavaScript) if performance is not important and avoid those strange arrays altogether.

Call the unshare method on b to make it become a unique copy: b.unshare()

Why this array’s method is not a function which returns array?

If you simply need to be sure that your reference to an array’s contents is the only reference in existence, call the unshare method, not the copy method. The unshare method does not make a copy of the array unless it is necessary to do so. The copy method always copies the array, even if it is already unshared.

Arrays have unshare and copy methods. unshare is smarter and performance-wise is useful. Still the surprising nature of Swift arrays seems to be a bitter pill to swallow in exchange for those performance benefits. This can be easier.

If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties:

It seems that ‘keep constant constant’ department at Swift is doing a great job! Very nice.

One could hope that ‘properties’ is essentially Swift’s name for fields. But hey it’s not quite same thing conceptually:

If you have experience with Objective-C, you may know that it provides two ways to store values and references as part of a class instance. In addition to properties, you can use instance variables as a backing store for the values stored in a property. Swift unifies these concepts into a single property declaration. A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly.

This is definitely good that we don’t have getters and setters in Swift. Wait! We have them unfortunately:

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

They just look like in C# and not like in Objective-C.

Property observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.

Sounds similar to Knockout.js and ECMAScript 5. I like this feature because this is explicit declaration of dependency and makes things easier, especially in UI programming.

That’s it for today. Stay tuned!

Few comments on Swift Programming Language (part I)

Below are my thoughts on Swift programming language just after reading its Language Guide and not using the language itself so it’s very likely that I’ll miss something. This is first part, second part to follow.

Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish.

This is bad thing. JavaScript too doesn’t require semicolon and we all know to what bugs does it lead. Breaking long statement into two lines can effectively lead to having two statements or one depending on last part of first line, at least in JavaScript, but I don’t see how this could be different in Swift.

Int UInt Floating-Point…

Wouldn’t it be nice to ALSO have just single universal numeric type known in JavaScript? Less choice, less mistakes. Compiler could inference actual type when possible so it will be as effective as explicit int/float type and if not you could always use int/float.

Tuples - You can name the individual elements in a tuple when the tuple is defined.

The ability to name individual elements is missing in C# language and it’s nice to see it in Swift. I would even say that naming should be mandatory in Swift. It makes code easier to read.

Optionals

I’m not a fan of optionals, sorry. C# has Nullable which is same thing. You can use it to have a null/nil/nothing on value type. But, you know, that just leads to more bugs. If you really want to say that some value is not present why not introduce boolean field and be explicit? Not present value is not something you should obfuscate! Nulls on reference types is bad enough to not introduce it also for value types.

if convertedNumber {

This is a way in you can check that optional convertedNumber has a value. I have only one question: what if optional is of boolean type? Not good.

You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value.

I’ll repeat last question. Now state of affairs is even worse.

range operators

Being Delphi (Pascal) lover for years I like this and I missed it in C#. But Half-Closed ranges? So you can have range from 1 to 2 represented as 1...2 and range from 1 to 1 represented as 1..2? Really? In Delphi there is just single form: 1..2 which means from 1 to 2. That’s it. Instead, in Swift one . more or less and you have those nice boundary value bugs.

if let definiteString = assumedString {

You can have assignment and check at the same time? We all know what kind of bugs this could introduce. Swift designers also know as they say:

Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value. This feature prevents the assignment operator (=) from being used by accident when the equal to operator (==) is actually intended. By making if x = y invalid, Swift helps you to avoid these kinds of errors in your code.

So In Swift you need that extra let keyword. Okay, this is extra clarity but logic behind ‘bug situation’ stays there. Still not happy.

Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators do not allow values to overflow by default.

By default. This is good!

Strings Are Value Types

I like this. In Delphi strings are also value types so you cannot have null string. In C# and many other languages you can have null strings what I don’t like. Also strings in Swift are interned to safe resources. Best of both worlds.

A collection of UTF-8 code units (accessed with the string’s utf8 property)

A collection of 21-bit Unicode scalar values (accessed with the string’s unicodeScalars property)

I always wondered why you can’t do this in C# (easily). This is very nice.

You can also use subscript syntax to change a range of values at once, even if the replacement set of values has a different length than the range you are replacing.

That’s about arrays. Looks somewhat like Ruby. Nice.

if let oldValue = airports.updateValue("Dublin International", forKey: "DUB") {

Command Query Separation anyone? And old value as a return of setting value? This is bad.

External Parameter Names

func someFunction(externalParameterName localParameterName: Int) {

If you provide an external parameter name for a parameter, that external name must always be used when calling the function.

I like parameter names on call (makes reading and changing code easier) but having two names on parameter seems to be too much. Fortunately we have:

Shorthand External Parameter Names

func containsCharacter(#string: String, #characterToFind: Character) -> Bool {

This is better! If you write that # then you are forcing callers to always name function argument. This makes sense when functions has more than one argument and as a function author you can decide. I like this approach.

Function parameters are constants by default.

Super! Shouldn’t they always be constant? In C# they are always mutable. In Delphi you need to type keyword before parameter declaration to make it constant. Here it’s by default.

In-Out Parameters

Tragic. Why couldn’t they avoid temptation to do this? Compatibility with legacy API?

You use function types just like any other types in Swift. For example, you can define a constant or variable to be of a function type and assign an appropriate function to that variable:

So function as a value type just like in JavaScript. Nice. And with type checking it looks exactly like TypeScript. Very nice.

Closures

Again it looks that they work in same way as in JavaScript (but I need to do some experiments to be sure). Nice.

reversed = sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } )
reversed = sort(names, { s1, s2 in return s1 > s2 } )
reversed = sort(names, { s1, s2 in s1 > s2 } )

That’s lambda syntax (in and curly braces). Looks strange at first but I can get used to that.

Shorthand Argument Names

reversed = sort(names, { $0 > $1 } )

This is a way to use lambda argument without declaring it first. I would love it if it was limited to only one argument. I don’t like it in its current form.

That’s all for know. Stay tuned!

Single Knockout binding handler for two observables

Let’s say we have model with two observables:

  1. foo
  2. bar

What we need is a single Knockout binding handler. This handler will display value of both observables in a single field.

It will also attach click event handler so when we click field, both observables will be updated with random value.

What’s important, displaying value is expensive in our scenario so when both fields are updated in sequence, only single refresh should occur instead of two sequential refreshes.

It appears that above is relatively easy to do in KnockoutJS. For starters, below is some HTML and model for demo application.

<input type="text" data-bind="value: foo"/>

<input type="text" data-bind="value: bar"/>

<input type="text" data-bind="both: { first: foo, second: bar }"/>

var model = {
  foo: ko.observable('Foo'),
  bar: ko.observable('Bar')
};

As you can see, our binding handler uses { first: someObservable, second: someObservable } syntax.

This is how it looks like:

var counter = 0;

var refresh = function(element, valueAccessor) {
  var value = valueAccessor();
  counter++;
  element.value = counter + ' ' + ko.unwrap(value.first) +
    ' ' + ko.unwrap(value.second);
};

ko.bindingHandlers.both = {
  init: function(element, valueAccessor) {
    element.onclick = function() {
      var value = valueAccessor();
      value.first('Foo' + new Date().getMilliseconds().toString(3));
      value.second('Bar' + new Date().getMilliseconds().toString(3));
    };
    refresh(element, valueAccessor);
  },
  update: function(element, valueAccessor) {
    ko.computed(function () {
      var value = valueAccessor();
      return ko.unwrap(value.first) + ko.unwrap(value.second);
    })
    .extend({ rateLimit: 1 })
    .subscribe(function() {
      refresh(element, valueAccessor);
    });
  }
};

Primo, there is init function in which we are just attaching onclick handler where we are setting two values in model. Very simple stuff. Also in this init function, we are displaying initial value using refresh external function. This is external function because we will need it later elsewhere. What’s interesting about refresh is that it increments counter every time it is called so we can see that we are calling it only when necessary and no more (remember, we are assuming that displaying value is expensive).

Secundo, there is update function. In this function we are taking advantage of computed observables with rateLimit extender. What this extender does is it limits rate of informing interested parties about computed value change. Setting limit to one millisecond is just right when we are concerned about sequential changes. The value returned from computed observable doesn’t really matter, as long as it is different for different input values. When this value changes, attached subscriber starts working and all it does is to invoke refresh function you already know. Pretty simple, huh?

Do you want to JSFiddle it? Have fun with Knockout!

Mocking RequireJS modules in unit tests in Jasmine and TypeScript

If you read very useful blog Mocking RequireJS modules in unit tests you will learn how to do this in QUnit and JavaScript. Here for a change is how to do this in Jasmine and TypeScript:

describe('Controller', () => {
  beforeEach(() => {
    requirejs.undef('Controller');
    requirejs.config({ 
      map: { 
        '*': {
          'Model': 'ModelMock'
        }
      }
    });
    define('ModelMock', () => ModelMock); // ModelMock is a class
  });

  afterEach(() => {
    requirejs.undef('ModelMock');
    requirejs.config({ 
      map: { 
        '*': {
          'Model': 'Model'
        }
      }
    });
    requirejs.undef('Controller');
  });

  it('does something', () => {
    var Controller;
    require(['Controller'], (required) => Controller = required);
    waitsFor(() => Controller, 'Controller');
    runs(() => {
      var sut = new Controller();
      // test sut normally
    });
  });
});
Logging JavaScript errors in ASP.NET in three easy steps
Delphi, ANSI Strings, diacritics and Windows 8
Inherited public property with protected mutator in .NET Reflection eyes
Few comments on Swift Programming Language (part V)
Few comments on Swift Programming Language (part IV)
Few comments on Swift Programming Language (part III)
Few comments on Swift Programming Language (part II)
Few comments on Swift Programming Language (part I)
Single Knockout binding handler for two observables
Mocking RequireJS modules in unit tests in Jasmine and TypeScript

About:

Hi! My name is Paweł and on this mini blog you can find my
random ramblings on programming (Delphi, .NET in general)

@pol84_

Following: