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

Thursday, March 27, 2014

Get rid of deep null checks

Have you ever had to write a code like this one?

var store = GetStore();
string postCode = null;

if (store != null && store.Address != null && store.Address.PostCode != null)
     postCode = store.Address.PostCode.ToString();

I'm sure you have. We've all been there. 
The goal is to retrieve (or compute) a value, but in order to do that, we have to get through many intermediate objects, which could be in a default state. The aforementioned example is pretty easy. Sometimes, along the way, there are additional method calls, "as" conversions or collections. We have to handle properly each of them, which bloats further the code, making it less readable. There's got to be a better way.

 

Conditional extensions
Many developers found a solution in conditional extensions. If you google "c# deep null check" you will find several implementations. Their names vary, but the idea behind them is the same:

public static TResult IfNotNull<TResult, TSource>(
    this TSource source,
    Func<TSource, TResult> onNotDefault)
    where TSource : class
{
    if (onNotDefault == null) throw new ArgumentNullException("onNotDefault");

    return source == null ? default(TResult) : onNotDefault(source);
}

As you can see, the extension returns a value of TResult type. The source object is required to obtain the result. If the former is null, we are unable to do that, thus the method returns default value of TResult type. If it's not the case, we can safely invoke the onNotDefault delegate. 
After adding IfNotNull extension to our project, the first example can be rewritten in the following way:

var postCode =
    GetStore()
        .IfNotNull(x => x.Address)
        .IfNotNull(x => x.PostCode)
        .IfNotNull(x => x.ToString());

Wednesday, March 26, 2014

#166 – You Can Override Metadata for Any Dependency Property

Inline image 1

    Recall that you can set a dependency property value on a DependencyObject for any dependency property, not just the properties that the class implements or inherits.
Since any dependency property can be attached to any dependency object, you can override metadata for any dependency property in a class.

Here's an example where we override the Grid.Row and Grid.Column properties in a class that derives from Button.  If this ButtonLoner object is defined in a Grid in XAML, it will automatically appear in Row 1, Col 1, rather than Row 0, Col 0.

public class ButtonLoner : Button
{
    static ButtonLoner()
    {
        Grid.RowProperty.OverrideMetadata(typeof(ButtonLoner), new FrameworkPropertyMetadata(1));
        Grid.ColumnProperty.OverrideMetadata(typeof(ButtonLoner), new FrameworkPropertyMetadata(1));
    }
}

Here is example:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <app:ButtonLoner x:Name="btnLoner" Content="Loner" Width="100" Height="25"/>
</Grid>

Monday, March 17, 2014

Web Search

Inline image 1

    Web Search - Visual Studio Add-in , Search (Google, Yahoo, MSDN, Code Project, Stack Overflow and more...) for the selected text/item. Multiple search options included in all Text Editor, Reference Items, Error List. (Integrated search options for Visual Studio IDE)

#1,030 – Displaying an Indeterminate Progress Bar

When you display a ProgressBar to show progress on some background task, you often know how much work needs to be done and how much of the work has already been done.  The ProgressBar below shows that we've loaded 5 out of 12 records, so the ProgressBar is 42% full.

Inline image 1

In other cases, you may want to use a ProgressBar to show the user that something is happening, but you might not know how long the operation will take or how much of the total work has already been done.  In these cases, you can display an "indeterminate" progress bar by setting the IsIndeterminate property to true.  A green bar will repeatedly slide across the face of the ProgressBar to show that something is happening.

<ProgressBar IsIndeterminate="True" Height="15" Margin="15,15,15,0"/>
<Label Content="Connecting to database..." Margin="10,0"/>

Inline image 2