This is a mirror of official site: http://jasper-net.blogspot.com/

Avoid shooting yourself in the foot with Tasks and Async

| Thursday, September 20, 2012
Since the release of .NET 4.5, you’ve been able to use the RTM version of Async & Await. There are some things though that can lead to very weird behaviors in your applications, and a lot of confusion. Kevin (Pilchie) over at Microsoft just gave me heads up on some of these and I thought that I would share it with the rest of you!

There was a very interesting discussion around this subject in the ##roslyn channel on freenode with @ermau and @jrusbatch.

Avoid async void

When you’re doing asynchronous methods that just return void, there is no way to track when these methods are done.

Look at the following example:

class FooBar
{
    public async void Biz()
    {
        await Foo();
    }
    public Task Foo()
    {
        return Task.Factory.StartNew(() =>
        {
            Task.Delay(2000);
            Console.WriteLine("Done!");
        });
    }
}

If we create an instance of FooBar and call Biz(), there’s no way for us to wait for the task to finish. Normally we would want a reference to a Task that we could wait for to finish, but in this case we don’t! Avoid async void whenever you can.

Just change the method signature to async Task instead and you will be able to do:

var foo = new FooBar();
foo.Biz().Wait();

The only reason you want to use async void is when you have an event handler that needs to await something. Such as a Click event handler like this:

private async void MyButton_Clicked(object sender, RoutedEventArgs e)
{
    var task = Task<string>.Factory.StartNew(() =>
    {
        Thread.Sleep(2000);

        return string.Empty;
    });

    var data = await task;

    MessageBox.Show(data);
}

Never getting that second exception when awaiting multiple results?

Consider that we have two asynchronous methods that both thrown an exception (almost at the same time), like these two methods here:

public static Task<int> Foo()
{
    return Task<int>.Factory.StartNew(() => {
        throw new Exception("From Foo!");
    });
}

public static Task<int> Bar()
{
    return Task<int>.Factory.StartNew(() =>
    {
        throw new Exception("From Bar!");
    });
}

What would happen if we called the following method?

public static async Task<int> Caclulate()
{
    return await Foo() + await Bar();
}

We would indeed get an exception thrown. But we would only get One exception thrown! In fact, the only exception that we will get is the First exception being thrown.

QR: Inline image 1

Posted via email from Jasper-net

How to Embed Arbitrary Content in a WPF Control

|
Introduction

Many WPF controls (e.g. Button, Border, etc.) can display arbitrary XAML inside them:

<Button>any XAML here...</Button>

How do you I create my own control with this capability? So, if I write something like:

<MyControl><TextBox Text="edit me" /></MyControl>

then a text box appears inside my control? This article will demonstrate how to do it the right way, as well as a couple of wrong ways and why they are wrong.

Naive Attempt: User Controls

My first attempt was to create a user control and try to add a ContentPresenter to it. Unfortunately, that did not work, and here's why.

I added a new user control to the project, and specified the contents in its XAML file:

<UserControl x:Class="MyNamespace.MyControl" ... >
    <StackPanel Orientation="Vertical">
        <Label>Foo</Label>        
        <Label>Bar</Label>
    </StackPanel>
</UserControl> 

Then I tried to use the control in my window like this:

<Window xmlns:local="clr-namespace:MyNamespace" ...>
    <local:MyControl />
</Window> 

Everything looks OK so far. Now I was told that ContentPresenter class can show user content in custom control, so I put it in the XAML definition for my user control:

<!-- don't do this at home --> 
<!-- MyControl.xaml --> 
<UserControl x:Class="MyNamespace.MyControl" ... >
    <StackPanel Orientation="Vertical">
        <Label>Foo</Label>        
        <ContentPresenter />
        <Label>Bar</Label>
    </StackPanel>
</UserControl>
...
<!-- MyWindow.xaml --> 
<Window xmlns:local="clr-namespace:MyNamespace" ...>
    <local:MyControl>User supplied content here</local:MyControl>
</Window> 

It does not work, because we end up defining user control's Content property twice: once inside the user control XAML, and once inside Window XAML. Window XAML wins this battle, and the only thing you will see is the text User supplied content here. Neither Foo, nor Bar are shown, and ContentPresenter has no effect.

Quick and Dirty Attempt

It turns out that ContentPresenter works only inside a <ControlTemplate>. So, I created a QuickAndDirtyAttempt project with a Decorator control there (yes, I know, WPF already has a Decorator type, but I could not come up with a better name). To achieve our goals in a brute-force kind of way, I just assign a control template to the user control. Contrary to this MSDN article, it is possible to apply a control template to a user control.

<UserControl x:Class="QuickAndDirtyAttempt.Decorator" ...=""
  <UserControl.Template>
    <ControlTemplate TargetType="{x:Type local:Decorator}">
      <StackPanel Orientation="Vertical">
        <Label>Foo</Label>
        <ContentPresenter />
        <Label>Bar</Label>
      </StackPanel>
    </ControlTemplate>
  </UserControl.Template>
</UserControl>

Note the TargetType property on the template: without it the project will happily compile, but the ContentPresenter will not work.

<Window ... >
    <StackPanel Orientation="Vertical">
        <local:Decorator>
            <Label Background="Wheat">User supplied content here</Label>
        </local:Decorator>
    </StackPanel>
</Window> 

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-net

iOS 6 released, supported by Xamarin

|
It would be hard to miss the news that Apple is launching their new iPhone 5 this week, and has also released the final version of iOS 6. What's also great is that Xamarin supports iOS 6 too, on release day! There's already plenty of documentation, using C# with StoreKit, PassKit, EventKit, UIKit changes and more.

QR: Inline image 1

Posted via email from Jasper-net

Google выпускает J2ObjC, open-source конвертер кода Java в Objective-C для iOS-приложений

| Wednesday, September 19, 2012
Google представили выпуск open-source проекта J2Objc, собственный конвертер из исходного кода на Java в Objective-C для приложений на iPhone/iPad.

Inline image 1

J2ObjC делает возможным использование кода на Java в качестве части билда iOS-приложений, при этом дополнительной правки кода не потребуется. Цель данного проекта — позволить программистам писать часть, которая не касается UI (доступ к данным или внтуреннюю логику приложения) на Java и получать код, который можно было было бы использовать для Android, веб-приложений и iOS.

Read more: Habrahabr.ru
Read more: J2ObjC
QR: Inline image 2

Posted via email from Jasper-net

New Metasploit 0-day exploit for IE 7, 8 & 9 on Windows XP, Vista, and 7

|
Inline image 2

We have some Metasploit freshness for you today: A new zero-day exploit for Internet Explorer 7, 8, and 9 on Windows XP, Vista and 7. Computers can get compromised simply by visiting a malicious website, which gives the attacker the same privileges as the current user. Since Microsoft has not released a patch for this vulnerability yet, Internet users are strongly advised to switch to other browsers, such as Chrome or Firefox, until a security update becomes available. The exploit had already been used by malicious attackers in the wild before it was published in Metasploit. The associated vulnerability puts about 41% of Internet users in North America and 32% world-wide at risk (source: StatCounter). We have added the zero-day exploit module to Metasploit to give the security community a way to test if their systems are vulnerable and to develop counter-measures.
 
Here's the back story: Some of you may remember that a couple of weeks ago, the Metasploit exploit team released a blog regarding a new Java exploit (CVE-2012-4681), with a blog entry titled "Let's Start the Week with a New Java 0day in Metasploit". You'd think the 0-day attack from the same malicious group might cool down a little after that incident... well, you'd be wrong. Because last weekend, our fellow researcher and Metasploit contributor Eric Romang just spotted another 0-day, possibly from the same group, exploiting a Microsoft Internet Explorer use-after-free vulnerability.
 
The Metasploit team has had the pleasure to work with Mr. Romang and @binjo together, and pretty soon we had a working exploit. You may download Metasploit here, and apply the latest update to pick up the exploit.

Read more: SecurityStreet
QR: Inline image 1

Posted via email from Jasper-net

GIF-сокеты. Коммуникации в реальном времени через анимированный GIF

|
Неизвестно, что курил разработчик Альваро Видела (Alvaro Videla) из компании VMware, но созданная им библиотека gifsockets явно должна была выйти 1 апреля, а не сегодня. Это библиотека для установки канала realtime-коммуникаций, используя анимированный GIF в качестве транспорта!

Идея в том, что в формате анимированного GIF'а не указывается количество фреймов, так что после отображения картинки браузер ждёт новых фреймов с сервера до тех пор, пока не получит сигнальные биты о конце файла. Другими словами, сервер может пушить в браузер сообщения по открытому каналу в GIF. Всё очень просто. 

Cложно найти этой технологии полезное применение, но у автора есть несколько идей: например, интерактивный прогресс-бар для отображения хода выполнения какой-то задачи на сервере. Кроме того, такие «Websockets из 90-х» работают в любом браузере, даже в IE6, то есть если клиент требует поддержки реалтаймовых коммуникаций во _всех_ браузерах, даже самых древних, можно предложить ему такой вариант, в шутку или всерьёз.

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

8 Command Line Tools to Monitor Linux Performance

|
It’s really very tough job for every System or Network administrator to monitor and debug Linux System Performance problems every day. After being a Linux Administrator for 5 years in IT industry, I came to know that how hard is to monitor and keep systems up and running. For this reason, we’ve compiled the list of Top 8 frequently used command line monitoring tools that might be useful for every Linux/Unix System Administrator. These commands are available under all flavors of Linux and can be useful to monitor and find the actual causes of performance problem. This list of commands shown here are very enough for you to pick the one that is suitable for your monitoring scenario.

Read more: Tecmint
QR: Inline image 1

Posted via email from Jasper-net

$linq, a .NET Linq to Objects for JavaScript script (i.e. LINQ for JavaScript)

|
Project Description 
$linq is a Javascript version of .NET's Linq to Objects, with some query operations inspired by MoreLinq (an extension to Linq to Objects).

What is $linq?
$linq is an implementation of .NET Linq to Objects for Javascript. It implements most of the corresponding .NET Linq to Objects methods. It also implements some methods inspired by MoreLinq (http://code.google.com/p/morelinq). $linq will work with arrays and jQuery collections. $linq can also generate values from a numerical range, as an item repeated a given number of times, and from RegExp match results.
Some of the Linq to Objects methods implemented
select
selectMany
where
orderBy
thenBy
distinct
groupBy
groupJoin
join
except
union
intersect
take/takeUntil
skip/skipUntil

QR: Inline image 1

Posted via email from Jasper-net

Goodbye Microsoft Network Monitor... Hello Microsoft Message Analyzer!

|
Inline image 1

Meet the successor to Microsoft Network Monitor!

Microsoft Message Analyzer has been released to the public, available here.  In order to download the program, please join Message Analyzer program.

As you might guess from the name, Message Analyzer is much more than a network sniffer or packet tracing tool.  Key capabilities include:

Integrated "live" event and message capture at various system levels and endpoints
Parsing and validation of protocol messages and sequences
Automatic parsing of event messages described by ETW manifests
Summarized grid display – top level is  “operations”, (requests matched with responses)
User controlled "on the fly" grouping by message attributes
Ability to browse for logs of different types (.cap, .etl, .txt) and import them together
Automatic re-assembly and ability to render payloads
Ability to import text logs, parsing them into key element/value pairs
Support for “Trace Scenarios” (one or more message providers, filters, and views)
We are providing this beta release to give you an opportunity to let us know what you like and don’t like and where we need to focus our energy as we drive towards a mid-2013 RTM date. 

QR: Inline image 2

Posted via email from Jasper-net