Sunday, August 16, 2015

Async await idea

In simple words .NET async await syntactic sugar helps to reduce limited resources usage.


Usually, UI thread in WPF and WinForms is the only one thread that can modify UI objects. If we use UI thread for a long-running task, the user will see freezing window. Same is relevant to ASP.NET ThreadPool, which has the limited number of threads to process requests. Async Await syntax helps to minimise usage of these resources.

If there is no need to switch back to initial context, you can continue operations on newly created thread (AsyncOperation) by using
     ConfigureAwait(false)


Recommend to watch Microsoft videos Essential Tips for Async

Monday, July 13, 2015

Public and private life key

In the dream there was an answer on private and public behaviours that I understood long time ago, but could not explain in a simple form. Accidentally the explanation appeared in amusing form.

Cryptography has the concept of Public/Private keys. And we are holding them in our life:


Rule 1
One cannot know private life key when taking a public key.

One of the nature part that people are hiding from society is a sexual (animal) behaviour, the problem is that it goes in thousands of years in the human history and so takes wide range of private key.
Possibly you dated partner, who is humble in public, but is crazy and hot in private life.
Go to another side.
Chaplin is still a famous comedian, most people think about him as a good and handsome man, but in real life he had relationship mostly with girls and young ladies, and changed them like gloves. His last wife were only 18 and he was 54 when they were married. Or Einstein who married his own cousin. People usually shocked when their lovely and polite neighbour becomes a maniac, these stories appear periodically in the news (Fritzl, Ridgway, Dr Harold Shipman). Or just look at Standard prison experiment, the base for Das Experiment movie.

Take another example, Walt Disney was scared of mice and he is the creator of Micky Mouse.

I believe you have good examples of quiet and ordinary colleagues who are amazing fathers and mothers in their private life.

Rule 2
Life keys are too wide and some cannot guess value with extrapolation.


You meet a girl in a party and she recognises pattern of your public key "he knows computer science", and next question is what? Right, "can you hack Google/Yahoo/Favourite site", or "can you repair my laptop/phone".
Or those surprised faces in work parties when people become to know each other a bit closer: "She is boxing and having professional skiing, wow, but she is so small and kind of quiet mice in the office, impossible", or "our brutal Mark is taking drawing lessons after work, girls, can you believe?".
Expectation of repeating same pattern in other parts of the key does not work and often reveals a surprise.


Guess the authors of the pantings:



The first and the second are painted by [Hitler], and the third is done by [Churchill].
Hint: to see the answer select the white part in [].

---
Good to see your positive stories of the rules in comments.

Monday, June 29, 2015

ADO.NET Dataset MS SQL procedure: Invalid object name #TempTable

This is commonly known error, but if you try to google it then hardly you will find immediately result. Hope this page will have better index in search engine.

So you create procedure in MS SQL with temporary table, e.g.:


CREATE PROCEDURE my_proc
AS
BEGIN
    create table #TempTable(ID int)
    
   -- insert, select data, etc

  return select * from #TempTable 

END

An attempt to add tableAdapter in DataSet will show error:  Invalid object name '#MyTempTable'. 

The solution is to come around ADO.NET with FMTONLY statement, it does not allow to run procedure. Adding IF 1= 0 will not run inside MS SQL, but will run on ADO.NET request.


CREATE PROCEDURE my_proc
AS
BEGIN
   IF 1= -- hint for ADO.NET
   BEGIN
     SET FMTONLY OFF
   END
    create table #TempTable(ID int)
    
   -- insert, select data, etc

  return select * from #TempTable 

END

Saturday, June 27, 2015

Universal web code | Part 1

This article illuminates modern tendencies in creation of universal web assembly code. Java-Script seems to be a winner in a Web rivalry with values of popularity, simplicity and universality nowadays.

HOW IS JAVA-SCRIPT GOOD

Douglas Crockford, famous Java-Script community contributor, in one of his presentations takes fun on the history of staging Java-Script, it is worth to see. The language itself has its own style, known as "Sex & Drugs & Rock & Roll": do some magic as you want, but be very, very cautious (more at weird syntax and dynamic nature)

alert('' == '0'); //false
alert(0 == ''); // true 
alert(0 =='0'); // true    
Browsers (written C++) parse Java-Script code and try their best to emit machine commands. Their best were not so good for a decade, and Java-Script has a reputation as very, very slow language (though the problem is not only in the language itself).

Lars Bak made a revolution in 2012 for Google Chrome V8 engine. He applied an idea of JIT compilation to the browser. This is very similar to Java and to .NET engines workflow, or in simplified form:
Parse java-script -> Abstract Syntax Tree -> ByteCode [Compile time] -> JIT [Execution time]-> Machine Code.
Optimisation in byte code step and machine code step drastically increased performance.
The same approach were taken by other browser vendors: Firefox with TraceMonkey, Safari with Nitro engine and Microsoft with JScript engine (now Chakra).


Alright, now we have the universal programming language with a good performance, hooray. Hold your horses, there is another problem with performance, it is much better now but still 10x's times slower  in comparison to a native client code.

BAILOUT
Web browser engines have a problem in optimisation of Java-Script due to its dynamism.
Engine prepares batch of instruction for a processor at byte code compilation. Then at execution time (running JIT) it checks how good was prediction, if there is a change then engine should invalidate command tree and start process again. The invalidation problem is called "bailout". For example engines do not optimise part that has with() statement.

function containsWith() {
    return 0;
    with({}) {}
}


ASM.JS

David Herman (Senior Researcher at Mozilla Research) has been contributing to asm.js project. Firefox team had an idea to make a restricted subset of Java-Script that provides only strictly-typed integers, floats, arithmetic, function calls, and heap accesses. This approach is closer to C/C++ programming and when browser meets ams.js hint the engine can better optimise code and finally get less bailouts.
The idea of transferring "favourite" language to Java-Script is not new itself, Microsoft started conversion of .NET code to JS in ASP.NET classic with ViewStates and Google developer has ScriptSharp project, Google converts Java to JS with GWT , Python has PyJs project. The difference in universality, asm.js is purposed to be universal assembly alike language.


At first step you can write code in statically-typed variant (C/C++/Objective C/Java/C#, ...), then transmit it to optimised byte code with LLVM, and finally to asm.js with Emscripten.
Where is a gain? LLVM is a project since 2000 that does excellent job in the optimisation of statically-typed languages into a low-level byte code. For example we can get C++ code, transfer it to the mentioned pipeline and at the end get Java-Script code in a kind of optimised assembler style.
Of course there are limitations and you cannot call special OS functions in an optimised way. Currently only value-type manipulations (integer, float, etc) with standard Math library are supported, external function calls and heap access.

Example
As a hint to an engine about optimised function there be a "use asm;" line, the hint itself is a prologue directive.

function Module(stdlib, foreign, heap) {
    "use asm";
    // module body
function NativelyFastCalculation(habraHugs)
{
   return stdlib.Math.sqrt(habraHugs); 
}
    return { module: module };
}

Then we can call our optimised function from any part of a usual non-optimised Java-Script code.

One of the areas with enormous structure manipulations is 3d calculation. Epic games and Mozilla converted 1 million lines of Unreal engine to Java-Script with asm.js and were able to get good performance:

Bananabread (demo) is another example of conversion Cube 2 engine, written in C++ and OpenGL, to Java-Script.

Current asm.js has draft version and is a subset of ECMAScript 6. So only browser supporting ES6 has full support of asm.js. In general vendors started experimenting with the subset a while ago. Mozilla was the first with Firefox 22, Chrome added special support in version 28, and recently Microsoft lined up with Chakra/Spartan. Within each version vendors provide better optimisation, e.g. usage of ahead-of-time compilation.

ASM.JS RESUME
Firefox presented asm.js with

  • Cross platform
    Already supported by all modern browsers, which is rare in the history. Architecture independent (ARM, x86, x64).
  • Performance
    The data differs from vendor to vendor and the reports show 75% to 10% of native client performance.
  • Partial backward compatibility
    If you do not use new features from EcmaScript6 (e.g. Typed arrays) then old browsers automatically support asm.js 
  • Minimised (non readable) code
    Users care about speed and do not care about page source code. Dear readers with a doubt, just view the source in Google and Facebook site.
    Now debugging is a problem, but can be solved in future with debugger symbol mapping.
  • Conversion from other languages through LLVM (C/C++/Java/C#/...)
  • Limited types
    Now only value types and operations on typed arrays. And you cannot manipulate DOM. However there are plans for extension. 
At present project has a very good start, the future will show us result.

It is worth to mention Low Level Java-Script project, which seems ideal for integration into asm.js, and possibly Mozilla team will do it.

In further parts we will see Google idea with Dart project, and then new web byte code library by popular browser vendors.

Saturday, January 24, 2015

Covariance Contravariance C# simple example

In .NET 4.0 Microsoft presented covariance (out) and contravarince (in). Next image shows simple class hierarchy:


Imagine there is a need of animal container class that can only return data
interface IAnimalHub<T>
        where T: Animal
    {
        T GetAnimal();
    }
We can declare and work with animal hub type as
  IAnimalHub<Animal> hub1 = new AnimalHub<Animal>();

Can we generalise left part or, in other word, downgrade type
 IAnimalHub<Animal> hub2 = new AnimalHub<Lion>();
 IAnimalHub<Animal> hub3 = new AnimalHub<Cat>();

Definitely it is possible, because we are going only to take out data and work with it, whether it is Lion or Cat. This idea is called covariance and can be done with out keyword in C#:
interface IAnimalHub<out T>
        where T: Animal
    {
        T GetAnimal();
    }

Now what if we have Add method with some animal argument in addition to our Get method
interface IAnimalHub<out T>
        where T: Animal
    {
        T GetAnimal();

        void Add(T animal);
    }

Should it work?
No! And the reason is that otherwise it would be possible to do
IAnimalHub<Lion> hub = new AnimalHub<Lion>();
var dog = new Dog();
hub.Add(dog);

So one cannot expect possibility to Add dog while waiting Lion object. It means covariance works only with returning data (out).

What about contrvarience?

As the word says this works in the opposite to covariance. Contrvariance expects only methods where one can put/write/insert data. In C# this is presented with in keyword. Consider only Add method in our interface:
    interface IAnimalHub<in T>
        where T: Animal
    {
        void Add(T animal);
    }

 Now we can do the opposite
 
            IAnimalHub<Animal> hub1 = new AnimalHub<Animal>();
            IAnimalHub<Lion> hub2 = new AnimalHub<Animal>();
            IAnimalHub<Cat> hub3 = new AnimalHub<Animal>();
            IAnimalHub<Dog> hub4 = new AnimalHub<Animal>();

In other words we can put Lion, Cat or Dog object where we expect Animal.

Limitations

Covariance and contrvariance can be declared only in the interface or delegate, not class. Generic parameter can be only reference type, not value type.

Examples  

In .NET IEnumerable<T> only returns data, so it is created as covariant IEnumerable<out T> in version 4 of the framework. And we simply can do
Animal[] animals = new Lion[0];
Animal[] animals = new Cat[0];
IEnumerable<Animal> animals = new Lion[0];
IEnumerable<Animal> animals = new Cat[0];