Jul 8, 2014

Brackets for the web

While diving into web development I needed a lightweight editor for JS, CSS and HTML files. So I decided to check how it is going for Brackets – open sourced code editor for the web.
After launching
cinst brackets
I got an editor, it appeared that current version is 0.41. First impression was – “too lightweight”, and it is after Visual Studio. The first feature I missed was formatting of selected code – there is no such command to invoke (at least I was not successful finding it). After lurking back and forth, cloning the repo, looking through the code, adding new command to launch some existing APIs – I got what I want, but then I thought – there already should be someone who needed the same functionality. And that’s it, there were several attempts to provide such functionality, starting with the extension that does almost exactly what I did and ending with several cards in projects cardboard, describing different formatting desires.

I end up installing the Beautify extension for formatting and also Code folding for folding regions of code. Both does not look abandoned (Brackets itself as well) and they do the work so far.

There are several conclusions from that story:


  1. Before writing your own feature, check if somebody already did that
  2. You could pack Brackets with whatever you want - there are a lot of extensions for almost any needs

Why Brackets? I like its Live Preview feature, when you can edit page and see a result on the fly in browser. I like it for its weight – that’s exactly what I need for prototyping ideas. I like it’s pace of evolution – it’s moving forward quite fast, growing to a mature product. I like the fact that I can add the feature I am missing Smile

Go and check if you haven’t seen it yet.

Jul 3, 2014

My list of tools

Well, tools in a tool belt. Any skilled worker has some preferences, what to use, both for tools and ways to use them. Here are mine:

Visual studio – IDE that I use on everyday basis. Surely it depends on your profile as a developer, what languages do you use; now I use C#, so that’s my IDE of choice. I’m using it starting from VS2005, now it is VS13.

Resharper – VS extension to refactor everything, static code analysis and so on. I appreciate its capabilities for the C# and JavaScript support.

DisplayFusion – multiple monitor taskbar support for Windows 7 (at least I need only taskbar support from that tool, I do not use other bells and whistles). Taskbar for secondary display is what I’m missing most in multi-monitor workstation setup. For me, second display without taskbar loses almost half of its usability. Windows 8 has multiple taskbars support built in, but while I’m on Windows 7 at my work desktop, I have to select among third-party tools. I used ActualTools Window Manager before, but its slowness on my new desktop (I even switched off literally everything in its options except 2nd taskbar) forced me to search for alternative and here it is. So far it is stable and gives me what I want – toolbar with pinnable applications and Aero previews. Now I’m on trial period, will consider buying.

OneNote – collecting my notes and info on both Windows and Android. Synchronization and offline notes. I moved from Evernote because I like interface more – will see if the transition worth time spent on it.

Notepad++ – lightweight editor for everything, supports plenty of formats, but has slightly obsolete interface.

Paint.NET – replacement for standard Windows’ Paint. Editing images – free and powerful – however sometimes not enough powerful. In example, cropping images is not very convenient.

7Zip – compressing and decompressing everything, no comments.

Truecrypt – has been replaced by BitLocker – Windows integrated encryption support.

f.lux – I already posted and article (sorry, that’s on Russian) on that app. I do not have requirements to colors on monitor to look natural, I just want more comfort for my eyes.

Dropbox – synchronization of choice for my files. Considering OneDrive also – so far I do not see killer features that could force me to do the change.

Fiddler – web debugging proxy, allows to look under the hood of web development world.

Teamviewer – remote access to mine home PC + collaboration when needed. Paid for commercial use.

Keepass – keeping your sensitive info at safe; passwords management solution. I also use unofficial port on Android, not very user-friendly though.

Daemon Tools Lite– images management, paid for commercial use.

GitExtensions – UI for git. I still cannot get used to git console when I need to check repository tree.

Skype – messenger of choice. But not mine choice. Personally I do not like its interface, contact groups are not convenient for me, Android version UI is awful.

Windows Liver Writer – the editor which has been used to write this article.

Chocolatey – machine package manager, I use it for installing everything from the above, starting from Notepad++. Basically, that’s one of the first application I’m installing on fresh Windows.

I did not include MS Office there + I might be missing some tools I use occasionally – let it be, I could post about them later.

Feb 22, 2014

comparison with boolean

One of the things that smells for me in code is the comparison with boolean literals in C#.
All those things like
image
Recently, I was trying to find out, what makes people write such code and came to the conclusion that this is either lack of knowledge of statically typed language or mistake or just a fear of legacy code.
Let me explain the latter. There is a code that is stated it is working (possibly for decades). And there is a need to add a feature/fix a bug in that code. After the work is done, there could be changes that result in such code, and the person who does that changes is afraid of moving forward and lefts the comparison as it is.
Note, that this situation is just my imagination, I do not know exactly why such code exists. The situation is based on client’s legacy code, I have to work on. However, that’s not only clients with 10-years old code. Here is the same in Microsoft documentation:
http://msdn.microsoft.com/en-us/library/bb546150.aspx
The example text:
image

Jan 12, 2014

Git Extensions credentials issue

Second time I faced the issue while working with fresh-installed Git and GitExtensions. While pushing changes to github, GitExtensions said

geissue

I quickly realized that I already fought with that and here is the link to solution, so I could easily find it.

In short, the issue is in the global gitconfig file, [credential] option get some unnecessary backslashes.

Jan 5, 2014

Knockout in short

Knockout is a MVVM-style binding JavaScript framework. Home: http://knockoutjs.com/ – there are docs, tutorials (interactive also) and other. Could be extended by custom bindings.

View Model – pure JavaScript object.

To activate knockout on page: ko.applyBindings(viewModelObjectInstance); Can take second param (DOM object) to activate certain object only.

Observables

ko.observable() - functions that can update the UI when data changes, when setting multiple observables you could chain calls.

Computed

ko.computed() – computed observable. 1st par\am – computing func, second (optional) – ‘this’ for that func. With passing object like {read:func, write:func, owner: obj} you could create writeable computed observable. Computed recomputes dependencies when created and on each run. Circular are avoided (doesn’t enters reevaluating itself).

ko.isComputed(obj) – for all computed

ko.isObservable(obj) – for observables, observableArrays, all computed

ko.isWriteableObservable(obj) – for observables, observableArrays, writeable computed

Observable Arrays

Collections.

Methods like native: indexOf, slice, pop, push, shift, unshift, reverse, sort, splice. unshift\shift  = push\pop but for array start. splice = slice with removing from source array.

Own methods: remove, removeAll. destroy, destroyAll – set _destroy property to objects.

Bindings

Are done via HTML attribute data-bind, like <input data-bind=”text: myName”/>.

visible – applies to .style.display – sets to none or resets back to prev value.

text – sets the element content (innerText or textContent). Escapes the HTML. Could be used in containerless syntax (when no container is allowed in place where you need text) <!——ko text: name——> <!——/ko——>.

html – works with innerHTML.

css – add/remove classes. Static syntax - takes JavaScript object= “css {className: bool_JS_Expr }”. Dynamic syntax= “css: propertyName”.

style – takes JavaScript object. Use fontWeight instead off font-weight (see more in doc)

attr – any attribute. Takes JavaScript object.

Control flow

foreach – iterates by array copying the underlying HTML template. Could take a JS object, param data means array, as is an alias to be used in underlying HTML, there are also several callbacks. Also could use containerless binding syntax.

if, ifnot – adds or removes DOM and maintains bindings. Could be in containerless syntax.

with – creates binding context. Supports containerless.

Form bindings

click – binds a function. First param DOM object, second – event. clickBubble binding allows to sop bubbling. Return true from func to allow default action.

event – bind func to any event. Uses JS object syntax. Params and default action are as in click binding, bubbling is also similer (youreventBubble: false)

submit – like click.

enable, disable, hasFocus – intuitive.

value – for input, select, textarea (use checked for checkboxes).

checked – for checkboxes ad radiobuttons.

options, selectedOptions – for select. Main param is an array.

Templates

Use template binding. Can take either id of template or JS object with params. Manages the DOM to be generated inside and data to be used for binding.

Binding context

$parent, $parents (all parents chain), $root, $data (current context), $index(foreach only), $parentContext (for nested loops), $rawData (usually the same as $data), $context (current binding context),  $element (DOM element for current binding).

Nov 2, 2013

Moq

Moq - one of modern frameworks for mocking objects. It could do anything that could do inheritance in .NET. There is Castle under the hood, like Rhino.Mocks. But, there is no such diversity of object types - all of them are mocks. Yet there are 2 mock modes - that simplifies understanding.
And complicating thing is that Moq uses instances of Mock class to setup objects behavior and expectations. Below, Mock means Moq' class and mock means object instance that we need for test. I woud use the following style for examples:
public interface IRepository
{
    string ReadData();

    string Storage { get; set; }

    void SetData(object o);

    event EventHandler OnReading;
}

Creating objects

There are several means of creating object.
First, you could call
Mock<IRepository> mock = new Mock<IRepository>();
This constructor creates Mock for class or interface. There are several overloaded constructors - to specify mock mode, parameters for instance constructor (in case class has no parameterless constructor).
Modes available:
  • Loose - never throws, tries to return default values
  • Strict - throws in case there is no expectation for called method/property
Second option is to get mock-object directly:
IRepository repo = Mock.Of<IRepository>();
You could get an infinite collection and retrieve as many instances as you need:
IQueryable<IRepository> repos = Mocks.Of<IRepository>();
However, you would need an appropriate instance of Mock class to setup behavior of mock object:
Mock<IRepository> mock = Mock.Get(repo);

Mock abilities

You could tune mock object behavior, setup expectations.
Here are its properties:
  • Behavior - current mode, Loose or Strict
  • CallBase - should the base class be called in case expectations are not specified
  • DefaultValue - wat to return in Loose mode. You could get nulls for reference types, or try to create mocks for them automatically (you cannot create mock for sealed class obviously)
  • Object - instance of mock


Setting up behavior

There are a bunch of methods for setting up behavior:
  • Setup is used for defining expectations for methods.
  • SetupGet - for property getters
  • SetupSet - for property setters
  • SetupProperty - defines property to have "property behavior". That means that property would persist anything passed to setter.
  • SetupAllProperties - the same as SetupProperty - but for all properties at once.
All those methods allow to set expectations using Fluent method calls chain:
mock.Setup(r => r.ReadData()).Returns(() => "some result");

mock.Setup(r => r.ReadData())
     .Callback(() => Console.WriteLine("Read call"))
     .Throws<ApplicationException>();

mock.Setup(r => r.ReadData()).Verifiable();

That's quite intuitive: Returns defines what to return, Throws - what to throw, Callback - what to call.
Verifiable is for validation. All Verifiable expectations would be checked when calling Verify().

There is also SetReturnsDefault - that method sets the default value for some type. In example String    is a reference type, default value is null, but that could be changed:
mock1.SetReturnsDefault("abc");
All strings returned by mock1 by default would equal "abc".

In case arguments are not known beforehand, you could use It class:
mock.Setup(r => r.SetData(It.IsInRange("a", "c", Range.Exclusive)));
mock.Setup(r => r.SetData(It.IsAny<int>()));
mock.Setup(r => r.SetData(
    It.IsRegex("^4[0-9]{12}(?:[0-9]{3})?$")));//VISA credit card
There could be any arbitrary code:
Expression<Func<string, bool>> fridayPredicate =
    v => v == "HelloWorld" &&
    DateTime.Now.DayOfWeek == DayOfWeek.Friday;
mock.Setup(r => r.SetData(It.Is(fridayPredicate)));

Validation

There is no Fluent interface, but a lot of Verify methods, similar to Setup.
You could verify all expectations, marked as Verifiable - or just all expectation disregarding of marks (Verify and VerifyAll).
Also you could verify if particular class member has been called (with configurable error message and number of calls that is expected - from Never to range):
var mock = new Mock<IRepository>();

mock.Verify();

mock.VerifyAll();

mock.Verify(r=>r.ReadData(), "Read Data was not called");
mock.Verify(r=>r.SetData(123));

mock.VerifyGet(r => r.Storage, Times.AtLeast(4));

mock.VerifySet(r => r.Storage = "", 
    Times.Between(1, 10, Range.Exclusive));

Class It for arguments:
var mock = new Mock<IRepository>();

mock.Object.Storage = "b";

mock.VerifySet(r=>
    r.Storage = It.IsInRange("a", "c", Range.Exclusive));

Events

Events handling in Moq is quite interesting thing. There is method Raise, that accepts delegate as a first argument and EventArgs as a second. That delegate should attach a handler to event that is subject of handling. Moq runs delegate in a separate context, catching all class members calls. It catches add event method and thus knows what event to raise. Only virtual events could be handled that way (which limits this functionality greatly).
Looks like this:
string called = "one";

var mock = new Mock<IRepository>();
IRepository repo = mock.Object;
repo.OnReading += (sender1, eventArgs) => { called += "called"; };

EventHandler sampleHandler = (sender, args) =>
    { throw new NotImplementedException(); };

mock.Raise(r => r.OnReading += sampleHandler, new EventArgs());

Assert.AreEqual(called, "onecalled");

Delegate code is not important, Moq intercepts assignment and does not do anything in fact.

Conclusion

Framework is light and flexible in use, API is intuitive and easy, there is no complexities because of long library growth. Obsolete members and classes have [Obsolete] attribute, code is well documented.

Sources looks fine, there are attributes [SuppressMessage] for tuning code analysis (remove warnings about intentionally made things).

I described a part of Moq, it has much more, but I think there could be issues in complex situations, in example - there is no easy way to check order of method calls. However such tests would be quite brittle - I'm not sure of their value.

I like Moq more than Rhino.Mocks, both has their own pros and cons, but simplicity and organization won.

Rhino Mocks–what is it

Rhino Mocks, the mocking framework, appeared at 2005. It hasn’t had any changes for two years and author announced that he will not support the project anymore. Then, there was a guy who decided to continue development of Rhino Mocks. I took a look at source code – he would definitely have what to change and improve. Code is abandoned, documentation is almost absent.
Here, the last update.