Monday, May 12, 2014

How to build Mono 3.4.0 / 3.4.1 on Windows

Introduction

This article builds on and updates a number of existing articles which attempt to describe the build process for Mono on Windows.

If you are just looking for Mono 3.4.0 binaries to use, I have provided the resulting binaries from this walk-through here.

The baseline instructions from the Mono project can be found here.

In theory these should be enough to get Mono compiled but, as ever in the real world, things are slightly more complex. As a result others have written pieces on how to build Mono, and I have found "Building Mono on Windows: The Final Battle" particularly useful.

That said, these articles are now a few years old and I ran into various issues building Mono which I have attempted to address with the walk-through below,

We are going to look both at building from the current, at the time of writing, Mono release tarball (3.4.0) and then at building the "latest and greatest" directory out of the git repository

The sequence of events is as follows,

Install pre-compiled Mono
Install & configure Cygwin
Retrieve and extract tarball Mono Sources
Build and Mono
Modify Cygwin/Mono to address any build failures
Install Mono and modify installation
Fix-ups/workarounds for Xamarin Studio
Retrieve and build git Mono Sources
This walk-through has been tested on an x64 machine running Windows 8.1.
Install pre-compiled Mono binaries

A stable, pre-compiled build of Mono 3.2.3 can be downloaded here. Download and install this.

Check that it runs by opening a Mono command prompt from the start bar and typing

mono --version 

You should see Mono come up and the 3.2.3 version shown

C:\Program Files (x86)\Mono-3.2.3>mono --version
Mono JIT compiler version 2.10.9 (tarball)
Copyright (C) 2002-2011 Novell, Inc, Xamarin, Inc and Contributors. www.mono-pro
        TLS:           normal
        SIGSEGV:       normal
        Notification:  Thread + polling
        Architecture:  x86
        Disabled:      none
        Misc:          softdebug
        LLVM:          supported, not enabled.
        GC:            Included Boehm (with typed GC and Parallel Mark)
C:\Program Files (x86)\Mono-3.2.3> 

Read more: Codeproject

Wednesday, May 07, 2014

Visual Studio 2013 Update 2 RC

This is a release candidate (RC) for Visual Studio 2013 Update 2.

Read more: MS Downloads

Thursday, May 01, 2014

Lowering in language design, part one

Programming language designers and users talk a lot about the "height" of language features; some languages are considered to be very "high level" and some are considered to be very "low level". A "high level" language is generally speaking one which emphasizes the business concerns of the program, and a low-level language is one that emphasizes the mechanisms of the underlying hardware. As two extreme examples, here's a program fragment in my favourite high-level language, Inform7:

Overlying relates one thing to various things. The verb to
overlie (it overlies, they overlie, it is overlying) implies 
the overlying relation. 

The jacket overlies the shirt. The shoes overlie the socks. 
The slacks overlie the undershorts. The shirt overlies the
undershirt.

Before wearing something when something (called the impediment)
which overlies the noun is worn by the player: try taking off
the impediment; if the player is wearing the impediment, stop 
the action.

This is part of the source code of a game;1 specifically, this is the code that adds a rule to the game that describes what happens when a player attempts to put on a pair of socks while wearing shoes. Note that the function which takes two objects and returns a Boolean indicating whether one overlies the other is not written as a function but rather as a relation associated with a verb, and that the language even allows you to provide a conjugation for a non-standard verb so that you can use it in any natural English form in your program. It is hard to imagine a language getting closer to the business domain.

By contrast, x86 assembler is a very low-level language:

add ebx, eax
neg ebx 
add eax, ebx
dec ecx

In one sense we know exactly what this fragment is doing; adding, negating and decrementing the values in registers eax, ebx and ecx. Why? Hard to say. The business domain is nowhere found here; this is all mechanism.

Wednesday, April 23, 2014

WPF: Inheriting from custom class instead of Window

In ASP.NET, we learned that it is often interesting to inherit from another class than from System.Web.UI.Page. This allows to define common methods, such as utilities, etc... which are used by a set of web pages throughout an application.
In WPF, it's also possible to do the same, and to inherit from a custom class instead of System.Windows.Window, of System.Windows.Controls.Page, or of System.Windows.Controls.UserControl for example.
When you add a Window (or Page, or UserControl...) to a WPF project, the chain of inheritance is as follows:




If you have a special method "doSomething()" which you want to reuse in every Window in the application, then you can store it in an abstract class GalaSoftLb.Wpf.WindowBase and modify the inheritance as follows:




In the diagrams above, the Window class is the framework's one, and the class GalaSoftLb.Wpf.WindowBase is abstract.
In order to get the new Windows to derive from this abstract class, not only the C# code must be modified, but also the XAML code. This is a little tricky, because a special syntax must be used. Instead of the usual:

<Window x:Class="WindowsApplication1.Window1"
  Title="WindowsApplication1" Height="300" Width="300"
  >
  <Grid>        
  </Grid>
</Window>

We have instead:

<src:WindowBase x:Class="WindowsApplication1.Window1"
  xmlns:src="clr-namespace:GalaSoftLb.Wpf" 
  Title="WindowsApplication1" Height="300" Width="300"
  >
  <Grid>
  </Grid>
</src:WindowBase>


Wednesday, April 16, 2014

Dart on Raspberry Pi.

Building Dart VM for the Raspberry Pi.

Introduction
These instructions will let you build and run the Dart standalone VM for a Raspberry Pi device running the Raspbian distribution of Linux. For now, this process will likely only work on a Linux machine.

Build
First, grab the Dart source as described in PreparingYourMachine and GettingTheSource.

Cross-compile
This build will require a cross-compiler that you can obtain by cloning this repository from github.

You can specify the cross-compiler to the build.py command using the --toolchain argument, as follows. From your Dart checkout:

$ ./tools/build.py -m release -a arm \
  --toolchain=/path/to/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf \
  runtime
You'll find the build products under out/ReleaseXARM/. You can optionally strip the dart binary to make it smaller:

$ /path/to/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-strip \
  out/ReleaseXARM/dart
Run on Hardware
To run Dart programs on the Pi, we'll need to create a dart-sdk using the host toolchain:

$ ./tools/build.py -m release -a ia32 runtime create_sdk
Then, we'll upload this sdk to the device:

$ scp -r out/ReleaseIA32/dart-sdk pi@[raspberry pi ip address]:./dart-sdk

Monday, April 14, 2014

#153 – Returning a Subset of Array Elements Matching a Particular Criteria

   Because System.Array implements the IEnumerable interface and because LINQ extends IEnumerable, you can use the IEnumerable.Where method on arrays to find a subset of elements that match a particular criteria.

   The Where method accepts a delegate to a function that takes a single element of the same type as the array and returns a boolean value, indicating whether a match is found.  Where returns an IEnumerable collection, which can be iterated on to get the elements in the subset.

Here's an example, finding the set of passing scores in a set of scores.

int[] scores = { 89, 98, 72, 100, 68 };
// Count number of passing grades
int numPassed = scores.Where((Func<int,bool>)IsPassingGrade).Count();

Here's the implementation of IsPassingGrade.

static bool IsPassingGrade(int score)
{
    return (score >= 75);
}

You can avoid defining a separate function by using a lamba expression.

Tuesday, April 01, 2014

Intel(R) Atom™ x86 Image for Android* KitKat 4.4 Installation Instructions - Recommended

Introduction
This document will guide you through installing the Intel® Atom™ x86 image for Android* KitKat, which can be used for development on Intel's x86 architecture.

Prerequisites
The Android x86 Emulator Image requires the Android SDK to be installed. For instructions on installing and configuring the Android SDK, refer to the Android developer website (http://developer.android.com/sdk/).

Optional: The x86 Emulator Image for Android can be accelerated using Intel Hardware Accelerated Execution Manager (HAXM). For more information, refer to the "Optimization" section of this document.

Installation
Downloading through Android SDK Manager

Start the Android SDK Manager.
Under "Android 4.4 (API 19)", select "Intel x86 Atom System Image":

Inline image 1


Read more: Codeproject

Creating your first HTML5 spaceship game for the Android* OS on Intel(R) Architecture

Introduction
I'm certain most of us have some insane or not so insane video game plans in mind. The majority of these thoughts are never acted on as many people think game coding is exceptionally hard to do. Indeed that is true to a degree, but it is not as hard as you may think.

If you have a fundamental understanding of HTML, CSS, and JavaScript*, you have all the requisites to start a straightforward project.

Adding a Canvas element to a web page

One of the most exciting features of HTML5 is the <canvas> element that can be used to draw vector graphics and engender astonishing effects, interactive games, and animations The web defines canvas, as a rectangular area that allows for dynamic, scriptable rendering of 2D shapes and bitmap images. The HTML5 Canvas is perfect for creating great visual results that augment UIs, diagrams, photo albums, charts, graphs, animations, and embedded drawing applications. HTML5 Canvas works with JavaScript libraries and CSS3 enabling you to create interactive web-based games and animations.

The elementary code for using and setting a canvas looks like this:

<body onload="spaceShipGame()">
    <h1>
      SpaceShipGame
    </h1>
    <canvas id="spaceCanvas" width="300" height="300">
    </canvas>
 </body>

This looks very similar to the <img> element, the difference being that it doesn't have the src and alt attributes. The <canvas> element has only two characteristics, width and height. If your renderings seem inaccurate, try designating your width and height attributes explicitly in the <canvas> attributes, instead of CSS. The width and height attributes default to 300 and 300, respectively. The id will be acclimated to initialize the canvas using JavaScript, and the text next to the equal to sign will be used as a call back when the mobile browser doesn't support it.

Drawing the background and spaceship for a game using HTML5 canvas and JavaScript

canvas = document.getElementById("spaceCanvas");
ctx = canvas.getContext("2d");
The variable canvas creates the canvas that we need to draw graphics objects, and ctx holds the rendering context. In this case it is a 2d graphics object.

This context contains the elementary methods for drawing on the canvas such as arc(), lineto(), and fill().

Next we paint the background black, place shiny asteroids on it, and draw the spaceship using the context object.

// Paint it black
          ctx.fillStyle = "black";
          ctx.rect(0, 0, 300, 300);
          ctx.fill();

         // Draw 100 stars.
         for (i = 0; i <= 100; i++) {
         // Get random positions for stars.
         var x = Math.floor(Math.random() * 299)
         var y = Math.floor(Math.random() * 299)

          // Make the stars white
          ctx.fillStyle = "white";

          // Give the spaceship some room.
          if (x < 20 || y < 20) ctx.fillStyle = "black";

          // Draw an individual star.
          ctx.beginPath();
          ctx.arc(x, y, 3, 0, Math.PI * 2, true);
          ctx.closePath();
          ctx.fill();
        }

Read more: Codeproject

Дружим Git с Putty

Inline image 1  Inline image 2

Итак, представим, что у нас девственно чистая система, в которой нет ни Putty, ни msysgit. Приступим к настройке нашего рабочего окружения.

Установка Putty

Качаем, устанавливаем, генерим и настраиваем ключ c Pagent (инструкция, ?).

Добавляем ключ на git-сервер

Копируем публичный OpenSSH ключ из Putty-ключа
Открываем страницу с SSH ключами и добавляем из буфера наш ключ

В картинках (на примере GitHub)

Создаём и сохраняем в Putty профиль «git@github.com» и проверяем, что удаётся зайти по ключу – должна открыться и сразу закрыться консоль.

Read more: Habrahabr.ru

Rhino Mocks 4.0.0 Alpha Released

It has been a little longer than expected but the latest version of Rhino Mocks has been released and is available from NuGet. You can download the package from here:


This is an "alpha" release since there are more than likely going to be a few things that come up. As a matter of fact, there are two things that I am already thinking about changing.

One is to be a little more explicit with arranging expectations against properties. Right now when you arrange an expectation against a property the intent is inferred. Instead I think it would be better to be explicit by adding ExpectPropertyGet and ExpectPropertySet.

The other is more of an internal modification to help track expectations easier. Currently an expectation is stored in a single data structure which includes the method, arguments, constraints and return values. When a method is intercepted all of the expectations have to be checked to find a match (clearly there are short circuits but… you get the idea). This modification will help account for how many times a method has (or hasn't) be called and increase performance.

Read more: Refactoring… Me

Управленческие инструменты: Формула нужды или Каким образом нас отжимают?

Неделю назад мы с коллегами наконец выпустили в свет бесплатный курс "Переговоры в схемах" (доступен после регистрации), поэтому сегодня решили поговорить об инструментах не столько управленческих, сколько переговорных. Тем более, что вещи это более чем связанные. 

После статьи «Управленческие инструменты: 4-фазный алгоритм решения проблем с людьми или «А чего ты хочешь, если ты такой хреновый менеджер?» нам писали: мол, ну так же не бывает, что со всем людьми и во всех случаях этот алгоритм работает? Это правда — этот алгоритм не очень хорошо работает, когда другой человек не видит с вами общего будущего. И/или же хочет вас банально отжать на что-то.

Один из самых полезных управленческих опытов в своей жизни я получил от руководства ремонтом собственной квартиры. На тот момент я уже 4 года работал менеджером — сначала руководил командой по тестированию Java на мобильных устройствах (мы работали с Sun), потом руководил командой в Intel. Я прочел Тома Демарко. Джоэла Спольски, прошел несколько управленческих тренингов. В общем, чувствовал себя очень крутым управленцем. Но это меня не спасло. 

Управление ремонтом квартиры требует немного других навыков, тем более когда тебе противостоит опытный прораб. Мой прораб в самом начале сотрудничества применил переговорный инструмент "Формула нужды", чем и обеспечил себе однозначную и безоговорочную победу.

Сам по себе инструмент достаточно часто применяется в переговорах с заказчиками — прежде всего, ими и применяется. Итак, как выглядит Формула нужды:

Нужда = 1*t + 2*E + 3*$ + 4*Эм

Эту формулу мы впервые услышали от нашего коллеги Дмитрия Коткина, руководителя питерской школы переговорщиков ШиП, после чего и попросили Диму изложить науку переговоров в схемах. Но вернемся все-таки к формуле:

1*t = Время

Первый фактор – это время, которое мы потратили на подготовку и проведение данной встречи или встреч. Чем больше времени мы затрачиваем на переговорный процесс, на взаимодействие с человеком, тем большую зависимость мы получаем.

Бытовой пример. Два человека, семейная пара – скандалы, ругань, живут несчастливо. Но на вопрос ей: «А чего ты с ним не разведешься?» – мы получаем гениальный ответ: «Ну я же с ним три года прожила, мне жалко этого времени». Вот, сформировалась нужда, сформировалась зависимость — в первую очередь, в голове у человека.


2*E = Объем уже приложенных усилий

Второй фактор, который играет на увеличение нужды, – это объем усилий, которые мы приложили, для того чтобы что-то сделать в этой ситуации. Например, если для проведения переговоров вам нужно подняться пешком на сотый этаж и вы на это потратили полтора часа времени, то вернуться без результата вам будет очень тяжело. Чем больше усилий мы совершили, тем нам жальче отказываться от любых результатов как таковых. Это делает нас уязвимыми.

Read more: Habrahabr.ru

FxCop Installer

Since FxCop 10.0 is distributed as part of Windows 7 SDK, you have to do some download and extractions to install it on servers which are not running Windows 7.

I followed instructions on http://ruthlesslyhelpful.net/2011/06/09/liberate-fxcop-10-0/ to extract the setup file and uploaded it to this project for easy access.

Read more: Codeplex

Vaadin.NET switching to C#

Inline image 1

When you thought Vaadin.NET 7.2 and 7.3 were on the way, we've been hard at work on a secret project all along. Today we're proud to announce the release of 12 intensive months of work behind the scenes by our R&D department. We at Vaadin.NET always strive to stay on the edge of the wave and having seen the popularity of C# in the past few years, we decided to pull the switch behind the scenes. Vaadin.NET now fully supports C# as the first-class programming language on the server-side as well as on the client-side.

"The largest effort was converting GWT into supporting C#. You can now stay inside Visual Studio, that you've learned to love, and compile to C#Script and HTML with Microsoft Web Toolkit Framework (aka MSWTF) faster and more conveniently than ever before." says VP of Vaadin.NET R&D Artur Seagull.

This is a huge thing for all developers around the world, you can work in a superior sharp language while developing full-blown Ajax applications. We've even built in support for the <blink> tag and backported support for IE6 mode into Windows 8 through a Webcomponents widget using JS-Interop. Sharepoint server was a natural choice and is as of today the dedicated platform for deploying Vaadin.NET applications. These have been the major requests in the community for the past few years and we're pleased to finally answer the call.

"According to a Gartner market study even C#Script hackers have always preferred C# to jQuery and now they can finally move to a platform with a future." says the newly appointed .NET evangelist Matti Pehvanen.

We've managed to build in support for all major browsers starting from IE5. The project is still quite new, only used in a handful of Vaadin.NET internal projects so there might still be some stability problems. We've especially had a hard time building support for marginal browsers such as Google Chrome, but are sure to have full support by the end of 2015Q1.

Read more: Vaadin .NET

Sunday, March 30, 2014

Unit Test a project having external dependency using Fakes and Visual Studio 11

Inline image 1

    I'll explain the steps to generate unit tests for a project which calls a WCF service using Fakes. Microsoft Fakes is an isolation framework for creating delegate-based test stubs and shims in .NET Framework applications. The Fakes framework can be used to shim any .NET method,

Compare Visual Studio Offerings

  Visual Studio 2013 with MSDN  Visual Studio Online
 Ultimate 
Buy Now
Premium 
Buy Now
Test Pro 
Buy Now
Pro 
Buy Now
MSDN Platforms
Learn More
Basic 
Get started
Pro 
Set up billing
Advanced
Set up billing
Debugging and Diagnostics
IntelliTrace in Production check              
IntelliTrace (Historical Debugging) check              
IntelliTrace Performance Indicators check              
Code Metrics check check            
.NET Memory Dump Analysis check              
Graphics Debugging check check   check     check  
Advanced Web Debugging (Page Inspector) check check   check     check  
Browser Link check check   check     check  
Static Code Analysis check check   check     check  
Code Map Debugger Integration check              
Debugger check check   check     check  
Windows 8 Simulator check check   check     check  
Performance and Diagnostics Hub check 1 check 1   check     check  
Windows Phone 8 Emulator check check   check     check  
Testing Tools
Web Load & Performance Testing check              
Microsoft Fakes (Unit Test Isolation) check check            


Read more: VisualStudio.com