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];



Tuesday, November 25, 2014

Have a check list before being catch up

Here is a small history of subtle points with hosting from my experience.


One of our clients asked us at HighRobotics to redesign Wordpress site. We designed it and then started the creation of a theme. It is done with mix of PHP, javascript and CSS. Everything was going good till once I made an error in PHP code, while moving the code and updating the live site!
Whole site was crashed, so there was no possibility even to login in WP administration panel.
It can be simply fixed with changing code in corrupted PHP file.
The customer was not remember where the site was hosted and thought that Wordpress.com was used for hosting.
What was my surprise when I found that Wordpress.com does not support file access. At all!

It means that any small error on PHP and bye-bye to site!

Gladly customer uses Wordpress on another hosting and error was immediately fixed.

Mochahost is a cheap hosting company that we are using for our site. It costs for us only 250$ a year. However sometimes technical people can just stop the site for a day without any informing. Other point is that it is written on 50s page of there help that they do not responsible for site backup. There were some technical issues and they just deleted all files for the site (not with us)! You can find hundreds of this stories in the internet. So if you do not making DB and files backup you can say bye-bye to your business site.



Check important points before making agreement with company, even if it has good reviews.

Sunday, October 26, 2014

SVG fallback pure CSS: Can I use Part 5

Previous: External SVG: Can I use Part 4


SVG is old technology, but there are even older browsers in use that do not support SVG.
The idea of supporting such pure browsers is to provide PNG (JPG or GIF) image in background.

After making big research the best solution without using java-script is found with SVG trick:
  • switch tag, which takes first supported element
  • foreignObject tag, that gives ability to insert object from alien namespace
For inline SVG this works as:
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40">
  <switch>
     <circle cx="20" cy="20" r="18" stroke="grey" stroke-width="2" fill="#99FF66" />
     <foreignObject>
         <div class="nicolas_cage fallback"></div>
     </foreignObject>
  </switch>
</svg>
If browser supports SVG it will take <circle> as first child, otherwise <div class="nicolas_cage fallback"> is shown.

For external SVG we can use standard object fallback:
    <object type="image/svg+xml" data="circle_orange.svg">
     <div class="nicolas_cage fallback"></div>
    </object>

And inside <HEAD> just add a class with background image for fallback:
  <head>
    <style type="text/css">
     .nicolas_cage {
         background: url('nicolas_cage.jpg');
         width: 20px;
         height: 15px;
     }
     .fallback {
     }
    </style>
  </head>

For "No SVG" Nicolas Cage will show up

The <div> is chosen instead of <img> because image is mostly always downloaded by browsers, though {display: none} is set for <img>.

However test also showed that IE and Firefox still download background images for <div>, while Chrome and Safari works great with it. The twice download problem only occurs with
<foreignObject>
   <div class="nicolas_cage fallback"></div>
</foreignObject>
and is not a trouble for <object> fallback. At first I tried to set {display: none;} for <fallback> element in <head> style, but Android 2.x and Mobile Safari 4.0.4 parses it as object and hides hole object.

The solution is to set {display: none; background: none; } for <div>, then IE and Firefox stops download <div> background images. Finally the question appears:

How can we update <div> for SVG supporting browsers and hide it while leave it unchanged for those browsers that do not support SVG?

One solution is found, though it can not feet for all.
The trick is with ability of SVG to take a style from another SVG object.
 <svg id="SVG_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  
      width="20" height="20">
      <style>
        <![CDATA[
        .orange {
          fill: #FF9900;
        }
        ]]>
      </style>
 </svg>
 <svg id="SVG_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  
  width="20" height="20">
 <circle cx="10" cy="10" r="8" class="orange" />
</svg>

SVG_2 takes .orange style from SVG_1 even though they are different objects in one HTML file.

The solution is to paste special SVG inside <body> element with clear image style:
.fallback { background: none; background-image: none; display: none; }

And the result test page:
<!DOCTYPE html>
<html>
  <head>
    <title>HTML5 SVG demo</title>
    <style type="text/css">
     .nicolas_cage {
         background: url('nicolas_cage.jpg');
         width: 20px;
         height: 15px;
     }
     .fallback {
     }
    </style>
  </head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" style="width:0; height:0; display:0">
 <style>
 <![CDATA[ 
  .fallback { background: none; background-image: none; display: none; }
 ]]>
 </style>
</svg>

<!-- inline svg -->
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40">
  <switch>
     <circle cx="20" cy="20" r="18" stroke="grey" stroke-width="2" fill="#99FF66" />
     <foreignObject>
         <div class="nicolas_cage fallback"></div>
     </foreignObject>
  </switch>
</svg>
<hr/>
<!-- external svg -->
    <object type="image/svg+xml" data="circle_orange.svg">
     <div class="nicolas_cage fallback"></div>
    </object>
</body>
</html>

Starting tests in different browsers:

All renders great: small Cage for "No SVG" browsers and circles for those that support SVG.

What about fallback image downloading for SVG supporting browsers? 

Gladly double downloading does not occur with latest versions of browsers (IE 11, Chrome 38, Safari 8, Firefox 33).
As a plus this solution pushes strong hint to avoid downloading fallback images with
.fallback { background: none; background-image: none; display: none; },  
and it with a high degree will work for new SVG browsers that are hard to test (Kindle, Noble, etc).


UPD: eliminated error in CDATA closing tag ]]>, added style="width:0; height:0; display:0" to SVG fallback.

Saturday, October 25, 2014

External SVG: Can I use Part 4

Previous: Inline SVG, CSS and defs: Can I use Part 3

External SVG file can be included inside HTML with one of the next methods:
  • <object type="image/svg+xml" data="circle_orange.svg" class="blockSize" />
    
  • <img src="circle_orange.svg" class="blockSize" />
  • <iframe src="circle_orange.svg" class="blockSize" />
    
  • <embed type="image/svg+xml" src="circle_orange.svg" class="blockSize" />
  • CSS background with svg file
Each method, except CSS background, is tested for browser support. In addition we investigated CSS support in <head> section of HTML page and style inlining in external SVG file.

All browsers (except that do not support SVG) showed good results and support external svg referencing.


While investigating render with browsers that do not support SVG, at first all went as expected. Here is the result for IE 7:


But then Android Mobile Browser 2.2 showed this: 

You can see the CSS code, which should not be shown. It is inlined in external SVG.
The suggestion falls in 3d section with iframe in both cases. To confirm the suggestion the page with iframe reference is created:
<!DOCTYPE html>
<html>
  <head>
    <title>HTML5 SVG demo</title>
  </head>
 <body>
    <iframe src="circle_orange_defs.svg" class="blockSize"></iframe>
</body>
</html>

File circle_orange_defs.svg:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
      width="20" height="20">
      <style>
      <![CDATA[
        .orange_internal {
          fill: #FF9900;
        }
        >
      </style>
      <defs>
          <circle id="circle_orange" cx="10" cy="10" r="8" stroke="grey" stroke-width="2" class="orange_internal" />
      </defs>
      <use xlink:href="#circle_orange" width="20" height="20" />
</svg>
And Android 2.2 renders it as

As suggested old Android cannot clearly render iframe with external SVG, that contains inlined style.
We can use some tricks to fix it, but simple solution is not to use iframe for SVG at all, there are at least 4 alternatives to reference SVG file.

CSS support

All browsers that can render SVG support style in external files if they are inlined in SVG.
There is no possibility to apply HTML CSS from <head> section to external SVG file, because browser does not consider it as part of the DOM. This is the reason why one of the line with circles is black (lack of style).


Test results

Browsers that support SVG process external files without a problem. Android Mobile browser 2.2 has bad behaviour with <iframe>.

The results for desktop:
Chrome: 38, ..., 16 *
Internet Explorer: 11, 10, 9,  8, 7, 6
Firefox: 31, ..., 4, 3.6, 3.5
Safari: 8, 7, 6.1, 5.1

* - green - works as expected, red - does not support SVG 

The result for mobile devices:
Chrome Mobile: 37, ..., 31
Android Browser: 4.0, 2.2
Mobile Safari: 5.1, 5.02, 4.0.5, 4.0.4

In this test external reference with hash tag is not tested and will be done in future. There are some known problems with partial referencing (#) <img src="circle_orange.svg#circle" />. 

Next: SVG  fallback image without java-script.

Inline SVG, CSS and defs: Can I use Part 3

Previous: Inline SVG: Can I use Part 2

One of the great feature of SVG is <defs> or definitions, that allows graphic reusing.
Take a star with path
<path d="M46.19 9.21l1.96 7.76 7.98-.54-6.77 4.26 2.97 7.43-6.14-5.12-6.14 5.12 2.97-7.43-6.77-4.26 7.98.54z" id="star">

We can reuse the code of star and make some transformation (move, scale, rotate) for basic figure.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="160" height="152">
  <defs>
    <path id="star" d="M46.19 9.21l1.96 7.76 7.98-.54-6.77 4.26 2.97 7.43-6.14-5.12-6.14 5.12 2.97-7.43-6.77-4.26 7.98.54z"/>
  </defs>
    <use xlink:href="#star"/>
    <use xlink:href="#star" x="90" y="20" />
    <use xlink:href="#star" x="14" y="80" />
</svg>

What about browser support?

For test we use same page and the results are gladly equals to previous test.


Test are taken with inlined SVG (inside HTML as in previous tests).

The results for desktop:
Chrome: 38, ..., 16 *
Internet Explorer: 11, 10, 9,  8, 7, 6
Firefox: 31, ..., 4, 3.6, 3.5
Safari: 8, 7, 6.1, 5.1

* - green - works as expected, red - does not support SVG

The result for mobile devices:
Chrome Mobile: 37, ..., 31
Android Browser: 4.0, 2.2
Mobile Safari: 5.1, 5.02, 4.0.5, 4.0.4

Combining it with previous test we can make a rule:
If browsers supports SVG then it supports <defs> definitions.

There is convenient diagram for browser support: Can I use SVG.  And our tests confirm there topicality.


Next section: External SVG using Part 4