Wednesday, October 22, 2014

#1,185 – ItemsControl Customization Summary

You can can customize an ItemsControl, or any of the controls that derive from it (ComboBox, DataGrid, ListBox, TabControl, TreeView et al), in a number of ways.  The various customization mechanisms are summarized below.
  • Set Style to apply a set of property values for the main control
  • Set Template to change the control template of the control.
    • This changing the highest level of the control (e.g. for a ListBox, a Border wrapping a ScrollViewer, in turn wrapping an ItemsPresenter)
  • Set ItemsPanel to change the panel used to lay out the individual items
    • E.g. User horizontally oriented StackPanel to lay out ListBox items horizontally, rather than vertically
  • Set ItemContainerStyle to set properties that apply to the container for each item
    • E.g. Properties that apply to each ListBoxItem within a ListBox
  • Set ItemTemplate to change the data template used to render each item in the list
    • E.g. Create a custom layout for each item in a ListBox

Visual Studio 2013 Update 4 RC now Available

Visual Studio 2013 Update 4 RC is now available to download. This release has lots of small features and fixes for ASP.NET and web platform, Team Foundation Server, Visual C++, JavaScript Editor, Testing Tools, and some other areas. Specifically for updates to the web development tools checkout this new features announcement on .NET web development and tools blog.

The release notes have the complete list of features and fixes included in this release.

Read more: MS Download

Tuesday, October 21, 2014

Батники против эксплойтов

Я понимаю, что для всех батники выглядят как нечто очень простое и со времен AUTOEXEC.BAT уже практически забытое, в то же время эксплойты, если вы конечно не профессиональный исследователь уязвимостей, выглядят очень сложно и практически неправдоподобно, особенно для некоторых разработчиков. Но! В данном посте я постараюсь перевернуть эти представления и рассказать, что всё как будто наоборот. Батники чуть легче и сильнее по функционалу brainfuck'а, а эксплойты не страшнее сортировки пузырьком на basic'е. 

Как я до этого дошел?

Мне тут на глаза попалась коробка с Windows 7 x64 c минимальными системными требованиями в 2 ГБ оперативной памяти! И я тут подумал, неужели во всех этих гигабайтах не найдётся пары килобайт кода, которые могли бы защитить пользователей от такой напасти, как эксплойты и Drive-by? Это бич всех ОС от MS уже лет пять! Должны быть там средства для хоть какой-то защиты? Но как их заюзать, да еще и стандартными средствами? С помощью батников. А как? Чтобы это понять, нужно прочитать эту простыню до конца. 8) 

Теория

В упрощенной теории срабатывания эксплойтов всё выглядит так: «что-то где-то посмотрели, что-то где-то послали, что-то где-то запустилось». В реальной жизни это часто выглядит так: пользователь, гуляя по интернетам, попадает на честно взломанный сайт, где ему вместе с полезной информацией отдают или JavaScript или редирект на JavaScript, который, анализируя USER-AGENT, информацию о плагинах и т.д. выдаёт пользователю эксплойт, который точно у пользователя сработает. После этого на машину пользователя сгружается троянец, запускается, прописывается в системе и начинает делать свои грязные дела. 

Read more: Habrahabr.ru

Thursday, June 05, 2014

Visual Studio "14" CTP




  Today, we are making available a first community technology preview of the next version of Visual Studio, codenamed Visual Studio "14".  This early build is focused on enabling feedback and testing from the Visual Studio community.  Visual Studio "14" will most likely be available sometime in 2015, with a more complete preview release and final naming available later this year.  Given that this is a very early build, please install in a test environment with no earlier versions of Visual Studio installed.

You can read about the new features and known issues in this first Visual Studio "14" CTP, and also download today.

Over the last 3 months, we've announced many exciting technologies that will be important parts of Visual Studio "14" - including the "Roslyn" .NET compiler platform, ASP.NET vNext and Apache Cordova tooling.  The Visual Studio "14" CTP 1 includes a few of these tools, as well as many additional improvements across Visual Studio, including an early look at some new C++ 11 support that will be part of Visual Studio "14".

C# and VB with the .NET Compiler Platform ("Roslyn")

In Visual Studio "14", the C# and VB compilers and IDE support are fully built on the .NET Compiler Platform ("Roslyn").  This open-source compiler as a service now sits behind dozens of developer experiences in Visual Studio "14", powering build, IntelliSense, refactoring, CodeLens, debugging and many more features developers use every day.  In most places the experiences are unchanged, but there have also been many small improvements across the entire development experience as part of the new compiler platform.

Read more: Somasegar's blog
Read more: Visual Studio

Monday, May 19, 2014

#466 – Using a GridSplitter in Conjunction with a SharedSizeGroup



A GridSplitter allows a user to change the size of a row or column by dragging a visual splitter.  A SharedSizeGroup allows two rows or columns to automatically have the same size.  You can combine these concepts, allowing a user to change the size of one column and have another column automatically have the same size.
In the example below, the user can drag either splitter, but when dragging, the width of both left and right columns changes at the same time.

<Grid Grid.IsSharedSizeScope="True">
    <Grid.ColumnDefinitions>
        <ColumnDefinition SharedSizeGroup="A" Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition SharedSizeGroup="A" Width="Auto"/>
    </Grid.ColumnDefinitions>
 
    <Label Content="Left" Background="Azure" Grid.Column="0"/>
    <Label Content="Middle" Background="Lavender" Grid.Column="2"/>
    <Label Content="Right" Background="Moccasin" Grid.Column="4"/>
 
    <GridSplitter Grid.Column="1" Width="8" Background="DarkSlateBlue"
                    HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
    <GridSplitter Grid.Column="3" Width="8" Background="DarkSlateBlue"
                    HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
</Grid>

Tuesday, May 13, 2014

#575 – PropertyMetadata vs. FrameworkPropertyMetadata

     When you implement a custom dependency property and you register the property by calling DependencyProperty.Register, you specify some metadata for the property by passing it an instance of PropertyMetadata.  This can be an instance of the PropertyMetadata class or an instance of one of its subclasses.  The differences are shown below.

PropertyMetadata – Basic metadata relating to dependency properties
  • CoerceValueCallback – coerce the value when being set
  • DefaultValue – a default value for the property
  • PropertyChangedCallback – respond to new effective value for the property

UIPropertyMetadata – derives from PropertyMetadata and adds:
  • IsAnimationProhibited – disable animations for this property?

FrameworkPropertyMetadata – derives from UIPropertyMetadata and adds:
  • AffectsArrange, AffectsMeasure, AffectsParentArrange, AffectsParentMeasure, AffectsRender – Should layout calculations be re-run after property value changes?
  • BindsTwoWayByDefault, DefaultUpdateSourceTrigger, IsDataBindingAllowed, IsNotDataBindable – Dictates how property participates in data binding
  • Inherits, OverridesInheritanceBehavior – Does inheritance work for this property?
  • Journal – Store this value when journaling?
  • SubPropertiesDoNotAffectRender – Check properties of this object when layout changes?

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