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

The Nature of TaskCompletionSource

| Wednesday, April 25, 2012
The Task Parallel Library is centered around the Task class and its derived Task<TResult>. The main purpose of these types is to represent the execution of an asynchronous workload and to provide an object with a means to operate on that workload, whether it be to wait for it, to continue from it, or the like. The primary type of asynchronous workload supported by Task is the execution of a delegate, either an Action or a Func<T>, such that the delegate’s execution in the underlying scheduler is represented by the Task. But in any compositional system that wants to use Task as its centerpiece, just support for asynchronous delegate execution isn’t enough: support must be provided for other asynchronous operations as well. For example, there are a variety of asynchronous operations already implemented in the .NET Framework and exposed through the Asynchronous Programming Model (APM) pattern or the Event-Based Asynchronous Pattern (EAP). In both of these cases, we’d like to be able to refer to these asynchronous operations as Tasks and operate on them as Tasks, even though the underlying work isn’t necessarily being performed by scheduling and executing a delegate. (More to come on both of those in future posts.)

To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource<TResult>.

The TaskCompletionSource<TResult> type serves two related purposes, both alluded to by its name: it is a source for creating a task, and the source for that task’s completion. In essence, a TaskCompletionSource<TResult> acts as the producer for a Task<TResult> and its completion. You create a TaskCompletionSource<TResult> and hand the underlying Task<TResult> it’s created, accessible from its Task property. Unlike Tasks created by Task.Factory.StartNew, the Task handed out by TaskCompletionSource<TResult> does not have any scheduled delegate associated with it. Rather, TaskCompletionSource<TResult> provides methods that allow you as the developer to control the lifetime and completion of the associated Task. This includes SetResult, SetException, and SetCanceled, as well as TrySet* variants of each of those. (A Task may only be completed once, thus attempting to set a Task into a completed state when it’s already in a completed state is an error, and the Set* methods will throw. However, as we’re dealing with concurrency here, and there are some situations where races may be expected between multiple threads trying to resolve the completion source, the TrySet* variants return Booleans indicating success rather than throwing an exceptions.)

As a simple example, imagine for a moment that you didn’t have Task.Factory.StartNew, and thus you needed a way to execute a Func<T> asynchronously and have a Task<T> to represent that operation. This could be done with a TaskCompletionSource<T> as follows:

public static Task<T> RunAsync<T>(Func<T> function) 
    if (function == null) throw new ArgumentNullException(“function”); 
    var tcs = new TaskCompletionSource<T>(); 
    ThreadPool.QueueUserWorkItem(_ => 
    { 
        try 
        {  
            T result = function(); 
            tcs.SetResult(result);  
        } 
        catch(Exception exc) { tcs.SetException(exc); } 
    }); 
    return tcs.Task; 
}

The operation is being performed asynchronously through a mechanism unknown to the TaskCompletionSource<T>. All it knows is that at some point, its SetResult or SetException method is being called to complete the Task<T> exposed through its Task property.

QR: Inline image 1

Posted via email from Jasper-net

Telerik, are you just mocking me? Yep! With the Telerik JustMock Free Edition

|
Are you already using SOLID principles in your code? Check out Telerik JustMock Free Edition. It's even available on NuGet!

You may be thinking to yourself, "Why bother when there are so many other alternatives?" I will give you just a few reasons...

JustMock Free is the best free mocking framework (try it out for yourself).
It's supported by a well-known and trusted vendor, Telerik.
It's the brainchild of Mehfuz Hossain, author of awesome open source frameworks such as AutoBox.
Here's the most important reason: if you find yourself in need of an extremely powerful mocking framework that can mock things like static classes, LINQ queries, and inject them regardless of how the code is constructed, your developers will already be familiar with the framework when you use the commercial edition.

QR: Inline image 1

Posted via email from Jasper-net

WebSharper

|
Inline image 1

Why WebSharper

WebSharper is an HTML5-centric web framework that lets you create web and mobile JavaScript apps complete with a server-side backend using a single language, F#.

WebSharper is designed to boost your productivity. Reduce complexity with a single language on the client and the server, enjoy code completion in Visual Studio®, and benefit from type inference and other great features of F#.

WebSharper is now open-source!

Features

  • F# to JavaScript compiler
  • Code completion and other IDE goodness
  • Extensions to JS libraries
  • Seamless client-server interop
  • Mobile development: Android and WP7
  • Formlets: UI form and wizard lib
  • Sitelets: composable websites
  • F# stdlib running on JavaScript
  • ASP.NET/MVC integration

Read more: WebSharper
QR: Inline image 2

Posted via email from Jasper-net

Вышла новая версия библиотеки qxdotnet

|
Несколько дней назад вышла новая версия библиотеки qxdotnet v 0.2. В этой версии были протестированы и исправлены большинство элементов управления.

Inline image 1

Напомню, что библиотека qxdotnet является серверной .NET оберткой над javascript-фреймворком qooxdoo. Она позволяет писать на .NET-овском языке (например, C#) приложения с богатым веб-интерфейсом.

Из всех исправлений следует отметить, что класс Table заработал. Этот класс отвечает за отображение на экране табличных данных. Редактирование данных пока не доступно.

Read more: Habrahabr.ru
QR: Inline image 2

Posted via email from Jasper-net

Introducing Google Drive and the Google Drive SDK

|
Inline image 1

Today, we're announcing Google Drive—a place where people can create, share, collaborate and keep all of their stuff. Drive is a natural step in the evolution of Google Docs. Drive is built to work seamlessly with other Google applications like Google+, Docs and Gmail, and your app can too. Joining the launch today are 18 web apps that have integrated with Drive using the Google Drive SDK.

QR: Inline image 2

Posted via email from Jasper-net

A world of pretty cloud drive icons - SkyDrive, Google Drive, Dropbox, BitBucket and GitHub

|
Inline image 1

Today Google Drive and Windows SkyDrive came out with clients for Windows and Mac. There's also SkyDrive apps for Windows Phone, iPhone, or iPad and OneNote apps that sync to SkyDrive for Windows Phone, Android,iPhone, or iPad.

I'm a paying DropBox customer myself with over 60 gigs in there. I also use BitBucket and GitHub for source code.

I also like tidy and pretty icons, for folders, programs and external drives. I made custom icons for the Visual Studio Command prompt as well as Visual Studio in PowerShell.

I put all these new cloud folders as well as my GitHub and BitBucket folders (these aren't custom apps, just folders where I keep my source repositories) in my favorites in Windows Explorer.

I made custom .ICO icons for GitHub and BitBucket from high-res PNGs. Just right click on a Folder, click Properties, then Shortcut Change Icon to select your custom icon.

Read more: Scott Hanselman 
QR: Inline image 2

Posted via email from Jasper-net

Basic4android

|
Inline image 1

Basic4android is the simplest and most powerful Rapid Application Development (RAD) tool available for the Android platform
  • Basic4android includes all features needed to develop great, real-world Android applications
  • Compiled applications are native Android applications, there is no extra run-time or any dependencies
  • Our community with over 20k developers is waiting to help you get started

General Features

  • Simple and powerful tool
  • IDE and programming language 100% focused on Android development
  • Compiles to native bytecode. No runtime libraries are required. Created APK files are exactly the same as APK files created with Java / Eclipse
  • Performance is similar to applications written with Java
  • Event driven programming language similar to Visual Basic with support for objects and code modules
  • No need to write any XML files
  • Highly extensible with support for custom Java libraries
  • Large, active and friendly community of developers. Over 20,000 registered developers!
  • The only available true WYSIWYG visual editor for Android. The visual editor supports multiple screens and resolutions
  • Easily create sophisticated layouts with the powerful designer scripts feature.New!
  • All Android phones and tablets starting with Android 1.6 and up to 4.0 are supported
  • Modern IDE with autocomplete, built-in documentation, internal index New! and other advanced features
  • Powerful step-by-step debugger
  • Large set of documentation with a custom online search engine and offline search engine tools
  • Built-in code obfuscation

Read more: Basic4android
QR: Inline image 2

Posted via email from Jasper-net

Debugging Mode in Windows 8

|
Inline image 2

Introduction

In this article we explain how to enable Debugging Mode in Windows 8. We are giving you Windows 8 Debugging Mode with the help of Advanced Startup Settings. Basically you can do Windows 8 Debugging Mode with the help of the shortcut key Shift + F8. Debugging Mode is accepted due to some problems caused by driver updates. The Advanced startup option is also known as Startup Menu. It includes various System Repair and Troubleshooting Modes. In Windows Startup Settings you can run Windows in Debugging Mode. If you want to access Windows 8 in Debugging Mode.

First you open the search box and type the Advanced Startup under Settings. You click on the Advanced Startup. After opening the Advanced Startup, you will see the PC Settings in the General and you click on the Restart Now Button under Advanced Startup and you choose Troubleshoot. You click on Troubleshoot and you will see many options and choose the Advanced option and click on it. After in this you can click on the Windows Startup Settings and open the Windows Startup, you click on the Restart Button. The Startup option is now in Windows 8 which allows the user to explication where the Computer has some trouble and causes problems.

Steps How to Enable Debugging Mode in Windows 8

Step 1 : You can move the cursor on the right-bottom and click on the search box and type in it what you want.

Read more: C# Corner
QR: Inline image 1

Posted via email from Jasper-net

Solarized Colors for Visual Studio 1

| Tuesday, April 24, 2012
Inline image 2

Update: I sent a pull-request to David Thibault and this update is now in his mainline repository.

I’m sure everyone and their dog knows by now that we changed the color theme in VS11 Beta to something a little more… ummm… monochromatic.

If you didn’t read about it, you should visit the Visual Studio blog and read Introducing the New Developer Experience.

Regardless of what you think about it, I do know that the UX designers had an admirable goal in mind, and that was making the code be the bit you see the most, and take the chrome out of your line of sight. The idea is to let you focus where it matters and not have Las Vegas lights happening all around it distracting you.

Regardless, I’m not here to comment on all that, but on what I like to do to make the experience even better.

SOLARIZE IT!

Solarized is a really nice, well-designed color scheme designed by Evan Schoonover. You can read all about how he designed it, the symmetry, contrast values, etc., over on his website http://ethanschoonover.com/solarized.

Read more: David Thibault
QR: Inline image 1

Posted via email from Jasper-net

Building Expression Evaluator with Expression Trees in C# – Improving the Api

|
This post is part of a series about building a simple mathematical expression evaluator. For previous posts and full source code see Table of Contents.

Introduction

In previous part we added support for variables but it has a big disadvantage: values of the variables are bound by position and not by name. This means that you should pass values for the variables in the same order as they appear in the expression. For example the following test will fail:

public void Can_Process_Multiple_Variables()
{
    var a = 6;
    var b = 4.32m;
    var c = 24.15m;
    Assert.That(engine.Evaluate("(c+b)*a", a, b, c), Is.EqualTo((c + b) * a));
}

On the other hand binding by name has following advantages: If you change the expression you do not have to worry about keeping order of the variables you pass in sync. So in this post we are going to change expression evaluator to bind parameters by name. We will also add a new overload for better performance when we need to evaluate same expression with different parameter values.

Binding Variables by Name

The easiest way to pass variables with their name is to pass a dictionary of variables with variable name acting as a key. While this will work it is not the most elegant and readable solution. A better solution will be to pass an anonymous object with properties pointing to the variable values. So our first task is to make the following test pass:

public void Can_Process_Multiple_Variables()
{
    var a = 6;
    var b = 4.32m;
    var c = 24.15m;
    Assert.That(engine.Evaluate("(c+b)*a", new { a, b, c }), Is.EqualTo((c + b) * a));
}

Read more: About My Code
QR: Inline image 1

Posted via email from Jasper-net

Compilify – Compile .NET Code In A Browser

|
Compilify is an online compiler as a service, started by Justin Rusbatch, which works on top of the Roslyn CTP. Started recently, it has already received a good amount of attention from the .NET community. We got in touch with Justin to ask him some questions.

InfoQ: Could you introduce yourself to our readers?

Justin: My name is Justin. I’m a self-taught developer working for a small .NET-based web development company in central Pennsylvania. I taught myself C# while working night-shifts as a Computer Operator, in between mounting tapes for a mainframe. I worked with ASP.NET webforms for a year, but I moved on to the MVC framework when it came out and I’ve been developing sites with that ever since. I enjoy learning other languages. I have some experience with Ruby on Rails, node.js, and F#.

InfoQ: You recently started Compilify - could you explain what is the purpose of this project?

Justin: Compilify (pronounced “compile-ify”) was inspired by many things. One of the primary sources of inspiration was the C# Interactive window that the Roslyn CTP brings to Visual Studio. This window provides a REPL environment that can be used to execute individual statements against the projects they’re developing and receive immediate results.

Compilify makes the .NET compiler completely portable and accessible through a fast, simple interface that fosters sharing and collaboration. It’s not an IDE in your browser, nor will it ever be. It’s simpler than that. You shouldn’t need to launch an IDE or create a new console project to experiment with a new idea that only takes a few lines of code. A developer’s time is incredibly valuable. Spending too much time thinking about a problem without actually trying solutions results in over-engineered solutions, killing productivity.

It also has a lot of potential as an educational tool for people who don’t know C# but want to try it. Downloading, installing, and launching Visual Studio can intimidate new developers. In fact, some developers might not install Visual Studio because of all the other applications that it install with it -- leading to an even more overwhelming experience. Compilify lets users get their hands dirty without needing to install anything -- not even a browser plugin.

InfoQ: Could you explain how Compilify works under the covers?

Justin: Lots of magic and coffee!

When the user submits code to the server for execution, a persistent connection is opened with SignalR. The web server wraps the code in an object with the SignalR connection ID that it was received from and then added to a processing queue on my Redis server. This frees up the web server to continue handling requests from other users.

Background workers do the heavy lifting. In order to prevent any malicious code from running, a new low-trust AppDomain is created to act as a secure sandbox for each execution. I haven’t taken the time to profile the performance, but so far I haven’t had a reason to worry about performance in this part of the application. Only essential assemblies are loaded into the AppDomain in addition to the user’s code. 
The user’s code is wrapped in a method, parsed into a compilation unit, and emitted into an assembly. The assembly is loaded inside the sandbox and the method that the user’s code was wrapped in is called. the result is serialized and returned to the worker. I perform this work in a separate thread that I can cancel if too much time is taken (the time limit is currently set at 5 seconds).

Once the result has been returned to the worker, it’s published back to Redis through a pub/sub channel along with the SignalR connection ID that originally made the request for the code to be executed. The web server subscribes to this channel on App_Start. SignalR is then used to forward any messages received in through this channel to the appropriate client.
This complex architecture was necessary to facilitate the secure execution of the user’s code, and to ensure the stability of the web servers.

Read more: InfoQ
Read more: Compilify
QR: Inline image 1

Posted via email from Jasper-net

Sony выпустил опенсорсный инструмент для анализа APK

|
Вы разрабатываете приложения и ищете мощный инструмент для их анализа? Вам нужно удобное представление их архитектуры? Вы пытались разобрать байт-код Android-программ? Всё это умеет новый виртуальный инструмент анализа приложений ApkAnalyser от Sony, который поставляется с открытым исходным кодом. 

ApkAnalyser предназначен для валидации и проверки работы вашего приложения. Вы можете распаковать, установить, запустить и проверить результаты команды Logcat. C помощью ApkAnalyser вы также сможете декодировать XML, выявить потенциальные уязвимости в вашем приложении и многое другое. ApkAnalyser полностью написан на Java и потребует JRE 1.6 или выше; работает на Windows, Linux и Mac OS X. 

Перед тем, как загрузить и установить его, пожалуйста, ознакомьтесь с подробными инструкциями в девелоперксом блоге Sony Mobile, для получения дополнительной информации о различных возможностях, посетите вики-страницу APKAnalyser.

Read more: Habrahabr.ru
Read more: APKAnalyser
QR: Inline image 1

Posted via email from Jasper-net

CXXI: Мост между мирами C# и C++

|
В рантайме Mono есть немало средств для взаимодействия с кодом на не .NET языках, но никогда не было ничего вменяемого для взаимодействия с кодом на C++.

Но это вскоре изменится благодаря работе Алекса Коррадо, Андрэа Гайта и Зольтана Варга.

Вкратце, новая технология позволяет разработчикам C#/.NET:

Легко и прозрачно использовать классы C++ из C# или любого иного .NET языка
Создавать экземпляры классов C++ из C#
Вызывать методы классов C++ из кода на C#
Вызывать инлайн-методы C++ из кода на C# (при условии, что библиотека скомпилирована с флагом -fkeep-inline-functions или если вы скомпилируете дополнительную библиотеку с их реализациями)
Наследовать классы C++ из C#
Переопределять виртуальные методы классов C++ методами на C#
Использовать экземпляры таких смешанных C++/C# классов как в коде на C#, так и в коде на C++

CXXI (прим. пер.: читается как «sexy») это результат двухмесячной работы под эгидой Google's Summer of Code с целью улучшить взаимодействие Mono с кодом на C++.

Альтернативы

Напоминаю, что Mono предоставляет несколько механизмов взаимодействия с кодом на не .NET языках, большей частью унаследованные из ECMA-стандарта. Эти механизмы включают: 
Двухсторонняя технология «Platform Invoke» (P/Invoke), позволяющая управляемому коду (C#) вызывать функции из неуправляемых библиотек, а коду этих библиотек делать callback'и обратно в управляемый код.
COM Interop позволяющий коду, выполняющемуся в Mono прозрачно вызывать неуправляемый код на C или C++ до тех пор пока этот код соблюдает некоторые конвенции COM (конвенции эти довольно простые: стандартная «разметка» vtable, реализация методов Add, Release и QueryInterface, а так же использование стандартного набора типов, которые могут быть отмаршалены между Mono и COM-библиотекой).
Общая технология перехвата вызовов, позволяющая перехватить вызов метода объекта и дальше самостоятельно разбираться с тем, что с ним делать.

Но когда дело доходит до того чтобы использовать в C# объекты C++, выбор остаётся не очень-то обнадёживающий. Для примера, предположим что вы хотите из C# использовать следующий класс C++:

class MessageLogger {
public:
    MessageLogger (const char *domain);
    void LogMessage (const char *msg);
}

Одним из способов предоставить этот класс коду на C# — обернуть его в COM-объект. Это может сработать для некоторых высокоуровневых объектов, но процесс оборачивания весьма нудный и рутинный. Посмотреть, как выглядит это неинтересное занятие можно тут.

Другой вариант — наклепать переходников, которые потом можно будет вызвать через P/Invoke. Для представленного выше класса выглядеть они будут примерно так: 

/* bridge.cpp, компилируется в bridge.so */
MessageLogger *Construct_MessageLogger (const char *msg)
{
    return new MessageLogger (msg);
}

void LogMessage (MessageLogger *logger, const char *msg)
{
    logger->LogMessage (msg);
}

Часть на C# выглядит так:
class MessageLogger {
    IntPtr handle;

    [DllImport ("bridge")]
    extern static IntPtr Construct_MessageLogger (string msg);

    public MessageLogger (string msg)
    {
        handle = Construct_MessageLogger (msg);
    }

    [DllImport ("bridge")]
    extern static void LogMessage (IntPtr handle, string msg);

    public void LogMessage (string msg)
    {
        LogMessage (handle, msg);
    }
}

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

Windows 8 מגיע ל-Enterprise

| Monday, April 23, 2012
Inline image 1

קצת לאחר השקת גרסת ה-Windows 8 Developer Preview שאלו אותי לא מעט, מה קורה עם גרסה לארגונים, מה החידוש שמביא איתו ל-IT הארגוני ואיפה היתרונות. אז Windows 8 זה לא רק Metro UI (שלדעתי זהו ממשק חדשני ומצוין) והחלטתי לסכם ממש בקצרה את החידושים והשינויים ש- 8 Windows מביא איתו לארגונים החל מהקטנים ועד הגדולים.

לפני מספר ימים נחשפו הגרסאות שמיקרוסופט מציעה ב-Windows 8 למשתמשי קצה, הגרסאות הנ”ל הן:

Windows 8

Windows 8 Pro

Windows RT

גרסת ה-Enterprise היא הגרסה שמזוהה עם גרסת ה-Windows 8 Pro אשר מכוונת למגזר העסקי. גרסת ה-Windows 8 Pro מציעה לא מעט חידושים.

השינויים שיש ב-Windows 8 Pro הן:

Windows To Go

גרסת של Windows 8 Desktop שמבצעת אתחול מדיסק/התקן חיצוני, ואשר מנוהלת בצורה מלאה מה-IT הארגוני. החידוש הנ”ל נותן גמישות רבה לארגון ע”י כך שמשתמשים חיצוניים כגון: סוכנים, אנשי מכירות ואנשי שטח שרוצים להביא מחשב “מהבית” והמושג הנכון יותר הוא Bring Your Own PC.

האפשרות של להביא מחשב מהבית מאפשרת ל-IT הארגוני לבצע Image שכולל בתוכו את המדיניות הארגונית לפי דרישות ה-IT ואבטחת המידע ולהתעדכן במידה ומתחברים לארגון, וע”י כך לתת למחשבים אלה להתחבר לארגון מה שלא אפשרי כיום.

Direct Access

מאפשר למשתמשים להתחבר לארגון בצורה שקופה ולקבל את המשאבים בארגון ללא כל צורך ב-VPN או בהגדרות נוספות. הרכיב הנ”ל מאפשר לאותם מחשבים שמתחברים “מבחוץ” לקבל פוליסי ארגוני, עדכונים וכו’.

אפשר ליישם Direct Access עם IPV4 מול השרתים הארגוניים.

Branch Cache – מאפשר למשתמשים לבצע cache לקבצים, אתרים ומידע נוסף מהשרתים הארגוניים, וע”י כך אין צורך להוריד מידע פעם נוספת או מחדש על גבי ה-WAN.

Read more: Eli Shlomo Blogs
QR: Inline image 2

Posted via email from Jasper-net

Wow - PlayStationSuite Open Beta - C# on the PS Vita

|

So I downloaded it and had thirty minutes of playtime :)

Here's a video of my experience:

Firstly I played with the UI Composer (designer) - and set up a tip calc like display (like the one in https://github.com/slodge/MvvmCross/ for MonoTouch, MonoDroid, WP7 and WinRT)

It was easy to do - just drag and drop the UI elements, then set their properties, including the generated variable name to use.

When finished, I just hit "Build" in the designer - this spits out:
  • a language csv resource file
  • a C# wrapper for that resource file
  • a scene.cs file - just a partial class with a constructor - this then becomes your "view controller" file for you to edit as you please
  • a scene.composer.cs file - this contains the generated code for the rest of the partial class - basically lots of layout code which matches what you drew in the designer

Read more: Forwards
QR: Inline image 1

Posted via email from Jasper-net

Windows 8 Metro style app samples

|
Download Windows 8 code samples and applications. New samples are added daily in C#, VB.NET, JavaScript, and C++ so check back often.
You can also download code samples for other products like Windows Azure, Office, SharePoint, Silverlight, or explore the Official Visual Studio 2010 C#, VB.NET, and 101 LINQ samples.

Read more: MSDN Code
QR: Inline image 1

Posted via email from Jasper-net

Windows 8 and the future of XAML: Part 5: More contracts in WinRT/Windows 8

|
In the previous article, we’ve introduced contracts in Windows 8. To quickly recapitulate, a contract allows Metro style applications in Windows 8 to communicate which each other or with Windows, without there being a hard reference between the participants of the communication. We’ve seen how the search contract allows applications to open themselves up to Windows so they can be search. There’s of course a contract that specifies how this searching is to be done: an application has to follow the rules specified in the contract so that Windows can communicate with the app in the way it needs to do.

In this article, we’ll dive some more in contracts, more specifically, the share contract. 

The code for this article can be downloaded here.

We love sharing
Sharing information has become something very trivial. Millions of sites out there have sharing options. “Share this on Twitter”, “Post on Facebook”, “Share via mail” and tons of other options have been popping up everywhere on the internet. Why? People love sharing. When they find something cool or they’ve just read the most interesting article, people want to share that with their contacts. Perhaps they want to broadcast it, using a social network. Or perhaps they want to target a specific contact and send the information via mail. Also, people sometimes want to share information related to something they have done or found inside an application. Perhaps they’ve achieved a high-score in some game and they want to brag with it. Or, they have found a great recipe in a cookbook application.

As you can see, sharing is all around us. One problem though is the fact that it’s sometimes still too hard for people to quickly share the information they want to share. As said, a lot of sites have embedded sharing icons. But are they always easy to find? Or what happens if you use a social network that the site you’re using isn’t listed? In that case you need to go and paste the link to the social networking site. Or as mentioned with the game high-scores: if the game doesn’t support sharing, how are you going to proof that you’ve really attained that high-score? Perhaps through a screenshot that you manually have to take, copy and paste to another site or application.

From a developer’s perspective as well, implementing the right sharing options can be hard. Sites offer often quite a few sharing options and maintaining all these external links can be a time-consuming task. What if tomorrow Twitter decides they want to implement that option differently? You as the developer need to go and change your implementation. And even then, perhaps the visitor of your site (or user from your application) uses some obscure social network (perhaps one that’s relevant in his home country) that you haven’t implemented…

Microsoft thought about offering an integrated sharing experience in Windows 8. It’s built into the system to offer both the end-user and the developer an easy and universal way of sharing information. This is the share contract.

The share contract
Through the share contract, Windows 8 makes it possible for 2 applications to share information with each other. The big plus for developers is that the 2 application don’t have to know each other. Sharing is always done between two applications: the share source and the share target. The share source will share information in a specific format defined by the contract; the share target will be getting that information through Windows. Since the information is in a specific format, the developer of the share target can anticipate on this and write his code based on this format.

Note that Windows is the mediator between the two apps. It handles the process of getting the information from the share source and getting it to the share target. It’s safe to say that we have some kind of pub/sub architecture.

Read more: Silverlight show
QR: Inline image 1

Posted via email from Jasper-net

Chunking Channel

| Sunday, April 22, 2012
   
    When sending large messages using Windows Communication Foundation (WCF), it is often desirable to limit the amount of memory used to buffer those messages. One possible solution is to stream the message body (assuming the bulk of the data is in the body). However some protocols require buffering of the entire message. Reliable messaging and security are two such examples. Another possible solution is to divide up the large message into smaller messages called chunks, send those chunks one chunk at a time, and reconstitute the large message on the receiving side. The application itself could do this chunking and de-chunking or it could use a custom channel to do it. The chunking channel sample shows how a custom protocol or layered channel can be used to do chunking and de-chunking of arbitrarily large messages.

Chunking should always be employed only after the entire message to be sent has been constructed. A chunking channel should always be layered below a security channel and a reliable session channel.

Chunking Channel Assumptions and Limitations

Message Structure
The chunking channel assumes the following message structure for messages to be chunked:

 <soap:Envelope ...>
  <!-- headers -->
  <soap:Body>
    <operationElement>
      <paramElement>data to be chunked</paramElement>
    </operationElement>
  </soap:Body>
</soap:Envelope>

When using the ServiceModel, contract operations that have 1 input parameter comply with this shape of message for their input message. Similarly, contract operations that have 1 output parameter or return value comply with this shape of message for their output message. The following are examples of such operations:

 [ServiceContract]
interface ITestService
{
    [OperationContract]
    Stream EchoStream(Stream stream);

    [OperationContract]
    Stream DownloadStream();

    [OperationContract(IsOneWay = true)]
    void UploadStream(Stream stream);
}

Sessions
The chunking channel requires messages to be delivered exactly once, in ordered delivery of messages (chunks). This means the underlying channel stack must be sessionful. Sessions can be provided by the transport (for example, TCP transport) or by a sessionful protocol channel (for example, ReliableSession channel).

Asynchronous Send and Receive
Asynchronous send and receive methods are not implemented in this version of the chunking channel sample.

Chunking Protocol

The chunking channel defines a protocol that indicates the start and end of a series of chunks as well as the sequence number of each chunk. The following three example messages demonstrate the start, chunk and end messages with comments that describe the key aspects of each.

Read more: MSDN
QR: Inline image 1

Posted via email from Jasper-net

OpenSSL: архитектура, приложения, ГОСТы, USB-токены

|
OpenSSL — мощный и современный криптографический пакет с открытым исходным кодом. В пакете реализованы различные криптографические алгоритмы, форматы и протоколы, что позволяет использовать OpenSSL для широкого круга прикладных задач. 

OpenSSL является основным криптопровайдером — «поставщиком» криптографических функций — для приложений Open Source. VPN, электронная подпись, HTTPS, Удостоверяющий центр, защищенная почта и многое другое реализовано на базе OpenSSL и его приложений.

Архитектура OpenSSL позволяет расширять его возможности с помощью написания специальных библиотек — ENGINE. Именно таким способом в OpenSSL была добавлена поддержка российских криптографических алгоритмов ГОСТ, подключены USB-токены с аппаратной реализацией криптоалгоритмов.

Обзор возможностей и архитектуры OpenSSL, поддержки в нем ГОСТов и токенов под катом.

Функционал OpenSSL условно можно разделить на 2 уровня: низкоуровневые криптографические «примитивы» и высокоуровневые криптографические форматы, протоколы. В примитивах реализованы базовые криптографические алгоритмы (симметричные алгоритмы, хэш-функция, асимметричные алгоритмы). Форматы и протоколы построены на алгоритмах и позволяют решать прикладные задачи. 

Пример: формат PKCS#7 использует электронную подпись по алгоритму ГОСТ Р 34.10-2001 и цифровые сертификаты формата X.509 и, при определенных условиях, позволяет обеспечить юридическую значимость электронной подписи.

На картинке представлены криптографические примитивы, реализованные в OpenSSL.

Read more: Habrahabr.ru
QR: Inline image 1

Posted via email from Jasper-net

Developing an engine for OpenSSL

|
For fun I thought I would see how hard it is to write an engine for OpenSSL. There are several existing ones that you can look at. I started by seeing how the opensc engine worked. This code shows the first step.

#include <stdio.h>
#include <string.h>
#include <openssl/crypto.h>
#include <openssl/objects.h>
#include <openssl/engine.h>

static int bind_fn(ENGINE * e, const char *id)
{
  if (!ENGINE_set_id(e, "simple") ||
      !ENGINE_set_name(e, "simple engine")) {
    return 0;
  } else {
    return 1;
  }
}

IMPLEMENT_DYNAMIC_CHECK_FN();
IMPLEMENT_DYNAMIC_BIND_FN(bind_fn);
Compile it like this

gcc -c -fpic simple_engine.c
gcc -shared -o simple_engine.so simple_engine.o

Make openssl.cnf look like this

openssl_conf            = openssl_def

[openssl_def]
engines = engine_section

Read more: sinodun
QR: Inline image 1

Posted via email from Jasper-net

OpenSC - tools and libraries for smart cards

|
OpenSC provides a set of libraries and utilities to work with smart cards. Its main focus is on cards that support cryptographic operations, and facilitate their use in security applications such as authentication, mail encryption and digital signatures. OpenSC implements the  PKCS#11 API so applications supporting this API (such as Mozilla Firefox and Thunderbird) can use it. On the card OpenSC implements the  PKCS#15 standard and aims to be compatible with every software/card that does so, too.

OpenSC is written by an international team of volunteers and is licensed as  Open Source software under the  LGPL license version 2.1 of the License, or (at your option) any later version. For a list of all authors and contributors as well as detailed license information see AuthorsAndCredits.

If you are new to smart cards, see OverView and FrequentlyAskedQuestions pages. Always check SecurityAdvisories.

The latest stable version of OpenSC is 0.12.2 ( released on 17.07.2011, milestone). See DownloadRelease for detailed information.

 Source targzip
 Windows (x86) installer (see WindowsInstaller for more information)
 Windows (x64) installer
 Mac OS X 10.6 and 10.7 installer (see MacInstaller for more information)
 Mac OS X 10.5 installer
Before you GetStarted with using OpenSC be sure to check the SupportedHardware list as typical smart cards are incompatible with all other smart cards and come with no public documentation.

DeveloperInformation is available for those who want to build smart card capable applications. Developers who want to GetInvolved with OpenSC are needed as well.

News

CALL FOR PARTICIPATION: OpenSC will be at FOSDEM 2012!

Read more: OpenSC
QR: Inline image 1

Posted via email from Jasper-net

How IIS processes ASP.NET request?

|
Before understanding the full flow, we have to go through following concepts:

IIS: IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it’s own ASP.NET Process Engine  to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and  process it and send response back to clients.

Worker Porcess (w3wp.exe): Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. In short, Worker process is the heart of ASP.NET Web Application which runs on IIS.

Application Pool: Application pool is the container of worker process. Application pools is used to separate the sets of IIS worker processes that share the same configuration. This makes sure that a particular web application doesn’t not impact other web application.

Note: One Application Pool can have one or many Worker Processes. An application pool with more than one worker process is called 'Web Garden'.

HTTP.SYS Process: HTTP.SYS resides in Kernel Layer of IIS. HTTP.SYS is responsible for pass the request to particular Application pool. It contains the ID of each Application Pool. (Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS).

WAS (Web Admin Services): WAS resides in User Layer of IIS. It takes the request from HTTP.SYS and pass it to the respective application pool.

ISAPI extensions: ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.

Note: Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.

Flow of ASP.NET Request:

1. Client Request hits the web server. Internally this request comes to Kernel Layer of IIS means at HTTP.SYS.

2. HTTP.SYS indentifies the name and ID of Application Pool for that ASP.NET Request.

3. Now Request comes to user level of IIS. WAS (Web Admin Service) puts the request from HTTP.SYS to Application Pool.

QR: Inline image 1

Posted via email from Jasper-net

The Developer’s Guide to HTML5 Canvas

|
Undoubtedly, the canvas element in HTML5 is the biggest feature that developers will want to use to develop truly rich web applications without needing to install browser plug-ins like Adobe's Flash player. IE9 was born at a time when client richness is at the forefront of developers' minds. Modern browsers like Chrome, Firefox, and Internet Explorer 9 and 10 all support it.  But what exactly is the canvas element in HTML5? How can you use it to create rich web applications? 

If you're unfamiliar with HTML5, before diving into this article, try learning more here.

What's the Canvas Element For?
Officially a canvas is "a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly". In layman's terms, the canvas is a new element in HTML5, which allows you to draw graphics using JavaScript. It can be used to render text, images, graphs, rectangles, lines gradients and other effects dynamically. Drawing on the canvas is via the canvas 2D API. This API contains a plethora of functions that give you the power to draw pretty much anything you like on the canvas. Currently, the canvas supports a 2D surface, not 3D. So what does a canvas look like? Not much. See for yourself.

The code above will render a canvas in the browser, but because the canvas is empty, you won’t see anything. Let’s add a border so you can see more clearly. The image below shows the canvas with a black border.

Read more: DZone HTML5 Zone
QR: Inline image 1

Posted via email from Jasper-net

Mono for Android Portable Libraries in VS

|
Thanks to Scott Hanselman's recent article on .NET's support for Portable Class Libraries (PCLs), there has been some renewed interested in using them for Mono for Android.

If you try to add a reference to a compiled PCL assembly, things should work, as VS simply checks that the version of mscorlib.dll referenced is the same as the MFA project (2.0.5).  However, if you try to add a reference to a PCL project, you get this nasty dialog box:

Inline image 1

The bad news is we don't ship any tooling for supporting these out of the box yet.  The good news is it's trivial to do it yourself!

The portable libraries are installed in .NET's Reference Assemblies folder, which is here:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.0

If you explore around in that folder, you will see there are something called "Profiles" which specify the common assemblies for a given set of targets.

For example, "Profile2" targets .NET 4, Silverlight 4, and Windows Phone 7.  This is the set that matches Mono for Android best, so we want to tell Visual Studio that it's okay for Mono for Android projects to use this set as well.

This is done by files in the "SupportedFrameworks" folder, specifically:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.0\Profile\Profile2\SupportedFrameworks

You can see there are already files for .NET 4, Silverlight 4, and Windows Phone 7:

Read more: Code monkey
QR: Inline image 2

Posted via email from Jasper-net

BareTail

|
Product Overview
A free real-time log file monitoring tool

Inline image 1

Real-time file viewing
  • Optimised real-time viewing engine
  • View files of any size (> 2GB)
  • Scroll to any point in the whole file instantly
  • View files over a network
  • Configurable line wrapping
  • Configurable TAB expansion
  • Configurable font, including spacing and offset to maximise use of screen space

Follow tail mode 
  • View the end of a growing file in real time, no matter how fast the file grows
  • Like "tail -f" on Unix systems, but with many more features

Tail multiple files 
  • Simultaneously monitor multiple files for changes using tabs
  • Visual indication on each tab of file status and changes
  • Tabs may be positioned on any side of the window and oriented horizontally or vertically

QR: Inline image 2

Posted via email from Jasper-net