Solving development problems  |  About this blog

Archive for the ‘Projects’ Category

Flash vs Silverlight

We at Avivo thought that we should post something about Silverlight vs. Flash as we use both technologies at our work. We always want to explore different techniques in production to bring out innovative approach for each project and to inspire our clients.

This post is about choosing right technologies when dealing with interactive or animated content on the web. It is a our test of Silverlight and Flash technology and we will describe our experience working with both of them. For the record: »HTML5 is not being part of experiment«.

Adobe Flash

Flash is well known as being the tool for animations and able to bring all kind of interactive content on web. Flash golden era of last decade is coming to an end. Currently web site trends are banning Flash out for many different reasons. First was jQuery that started to replace Flash in many simple tasks and HTML5 will probably be the final executor. Then, also Apple announced that it will not support Flash on iPhone/iPad. Nevertheless Flash will stay around long time especially when you want to bring extremely good interactivity inside browser for smaller parts like games or banners and for such specifics tasks Flash is still without competition.

Microsoft Silverlight

On the other side Silverlight was many times quoted as Flash competitor but not any more and lately is obvious that has many other advantages like delivering best video quality/performance and out of browser experience. And developing in C#/VB/other dynamic languages and reusing the code naturally with the project and through the projects. Speed, frame rate accuracy and low CPU usage give few good strengths to the Silverlight down the road. Nowadays that Silverlight is used also as platform for Windows Phone we think Silverligt is more attractive then ever.

Both are RIA

We need to mentioned that also many Flash developers didn’t want to switch to Silverligt and many reasons why they didn’t are very clear to us. To say it in short: Silverlight demands new approach that Flash developers just can’t or not willing to adopt. When you converting you have to convert fully to have chance for success. Only then you are comfortable enough to work with Silverlight and you are on better position to decide what would be the best technology for specific given task.

Nice example is Shine Draw web site where each animated example is done in both technologies. Our task was to bring out animated effect as good as it is possible to be smooth and visual attractive. We decided that this can be good example to try both technologies out and at the same time we was also eager to test them both.


Our project

We wanted to create appealing visual effect of changing triangular pattern animation as best as it gets with bit of 3D look and feel. We made grid out of triangles and we wanted to transform grid while changing images with seamless transitions.

Design ready to animate. Skip reading and see final result here.

Pattern design ready to animate

The goal was to animate 6 different pattern designs with seamless transformations with use of 3D on each triangular element.

First try with Silverlight

We had experience with Silverlight transitions while working on Superia Player and process was very natural and very quick from start to finished. When we wanted to bring even more interesting 3D transformation on irregular triangles positioned grid parts we encounter issues and we decide is time to switch to Flash and repeat the process.

Input parameters

Using 'initParams' in HTML input parameters are passed to Silverlight application. Application collects the parameters on load and requests the specified pattern XML file and initial image from the hosting server. Each other image is loaded once on demanded and cached by browser.

Mapping images to triangles

Triangle vector objects were created dynamically by the pattern defined in XML and they fit to the container size. Application has been developed in Silverlight 3 which has no native 3D support but already supports graphic acceleration. So triangles are drawn in 2D space faking the 3D look, 2D is also used because of better performance. Images are mapped to triangles by calculating rotation and offset using ImageBrush that could be later replaced by VideoBrush allowing to map video frames. Lot of geometrical math was done to do this job.

Flip animations

Triangle flip animation was done in two ways: transforming around diagonal centre point or transforming vertically/horizontally. In either way front side hides and back side shows or vice versa resulting in image change. Since the triangles are drawn on 2D spaces animations are faking 3D transitions by scaling, skewing, rotating, translating and remapping image. Animation can flip triangles progressively from the top left corner towards the bottom right. Another more appropriate animation starts flipping random triangles progressively with short delays between phases.

Hosting Silverlight

Silverlight is embedded in HTML using 'object' tag and 'params'. Setting parameters is straightforward, no tricks or work-arounds. Additionally HTML content can be inserted into 'object' allowing user to view the alternative content in case Silverlight is not installed or plug-in not enabled in browser.

The catch

Working with 2D, drawing triangles and mapping parts of image may seem easy at the beginning but when it goes towards fake 3D rotations it can get complex. Having multiple layers, calculating offsets and transitions, mapping images, switching images (front/back) during animation, generating animations, generating delays between flip... Finally algorithms get too complex to continue in 2D space without real 3D engine.

Making Flash pattern

We knew that flash might be better shaping irregular transformation but one thing we need to know is that Flash until recently didn't have direct 3D support. Sure, you could make it your own 3D effect by using math to calculate 2D movement and rotation in such way that would resembles 3D feeling, also we need to mentioned that out there are many excellent package of 3D utilities and one is called Paper Vision 3D that was and is still used to produce nice 3D effects in Flash. But we were up to try something (relatively) new and besides that, we wanted to see what can be done with Flash-only 3D in Flash CS4 version.

Creating our triangular pattern animation required a few critical parts of AS3 code:

  • Loading XML data for pattern definition
  • Loading images used to create pattern
  • Mapping images to triangles
  • Animating the actual transitions

Pattern XML data

Since introduction of AS3, handling XML data in Flash has become much, much, less complicated, thanks to the adoption of ECMAScript for XML (E4X). Now XML acts as native data type, you don't need to create special objects to copy data from XML. Now data from XML is directly accessible from XML object, using actual element and attribute names to select appropriate data form XML. Picture preloading is also now much more simple, although the "art-of-preloading" was conquered long ago, classes used to load external content are now better organized, and callback functions for various events that can happen during load are now handled by proper event listeners.

Another good thing in AS3 is that every DisplayObject is by default invisible until you explicitly add it to some other, visible or DisplayObject as it's child. So you can do any kind of manipulation of size, position, alpha, and so on, until you decide that your object is finally in a state you want it to appear on stage. Sticking images on triangle parts Applying pictures to triangles was another task to perform even before we could use 3d effects. Although it takes a bit of math to draw triangles on proper locations, it is still a combination of well-known lineTo, moveTo, curveTo methods (if you want triangles with rounded corners) and even better in newer version of Flash, you can now use drawPath method. Performance in drawing should be better as well as precision.

Using 3D in Flash

With all this we had the basic setup completed, and we came to the funny parts, exploring 3d effects. Using 3d in Flash has become quite easy, you can set rotationX, rotationY, rotationZ, and x, y, z values for any visible objects. Tweening any of these properties will create 3d animation effect. Nice and easy. Of course, some experimentation was needed, to get some idea how change z value effects the object, its appearance in the stack of objects. Any sudden and extreme change of z value will produce quite unnatural effect.

Unfortunately, there must be a glitch, when 3d engine is activated (that is when you change any property that directly or indirectly changes z property of an object) the object itself is immediately blurred and this is bad for display animation. In fact, the object is bitmap-cached (to make animation easily to compute) with smoothing. Usually that is not a big deal, unless, as it was the case with our pattern, you need very precise positioning of some elements and crystal sharp edges.


Blur edges and timers were pian in the ass.

Solving problems with 3D to 2D world

This has becomes a first major problem with our pattern project and solution isn't easily at least not in all circumstances. Luckily for our pattern, we struck such a layout that we could overcome this. To make elements clear, once you used 3d effect on an object it will be bitmap cached and blurred, and there's nothing you can do about it. But if your animation is such that in the end your object is in such position that any z-axes related property is zero-ed, you can bring you object back to the 2d world.

How Flash is transforming

The thing is, Flash uses two different transformation matrices to track 2d and 3d properties of an object. If 3d transformation matrix exist - than your object is blurred. But if you can get rid of it, your object will be returned to the crystal sharp realm of 2d transformations. All you need to do is to copy 2d properties (x, y position and xscale, yscale) from 3d transformation matrix, remove the 3d transformation matrix, and apply those x, y, xscale, yscale to your object. The only backdraw of this method is that you can not use it on objects that needs z-axes related properties to display themselves correctly.

Timers and fine tuning

One thing we've noticed after the pattern was created is that timers we've used to control the timing of the rotations are performing somewhat strange if the HTML page containing the Flash embedded object looses focus. For some reason, when Flash page looses focus, background priority obviously doesn't have not enough memory for Flash timers to work correctly. Flash timers do not guarantee perfect timing anyway, but in the background window it will probably drop out of sync completely. So we needed some quick fix, to detect when the page containing our Flash is loosing focus. Again AS3 have come to the rescue, with it's External interface, and ability to easy communicate with JavaScript, that is, on the other hand capable of detecting when the page has lost the focus.

View final comparison solution between Flash and Silverlight pattern.

Conclusion

We found that with Flash we succeed to create pattern transformation as we wanted with smooth transitions and nice 3d effect. Working with Silverlight was very quick and we might even explore it further but we run out of time and beside that we where happy with Flash result. When looking closely you will see that when you embed Silverlight object and Flash object to HTML site, Silverlight need little more time to appears in browser than Flash and this is something we don't know the answer yet.

What have we learned:

  • Flash has "dirty" history and uses bad mix of 'object' and 'embed' tags.
  • Flash cannot display HTML content reliably if plug-in is missing while Silverlight can do that easily. If plug-in is missing we just display static content.
  • Flash has native 3D support while Silverlight has no native support for 3D at the time. Silverlight has some experimental libraries which are heavily under development and not for production use.
  • Calculating 2D to look like 3D is overkill for developers. Too much effort, too small output. Use 3D engine for serious 3D development.

Share your thoughts in the comments.

Written by Avivo

December 22nd, 2010 at 5:51 pm

The dark side of Android phone development – part 2

About this blog post
Unlike the Official Google articles that are mostly praising Android as Mobile platform, this article covers practical development experiences with Android platform.

Authors of this article have prior practical experiences in web and desktop enterprise software development and have recently developed few Java applications for Android 2.1-update1. Content has been written in Autumn 2010, statements in the article are referenced to that time and to the testing on Samsung Galaxy S i9000 phone.

Android Development

As we pointed out in this blog title, we just wanted to make an awesome Android phone application and we wanted to find out how much effort does Android OS really take for a development. Users don’t care about this and web press don’t care much as long Apps are great and working and all the hard work by developers isn’t mentioned a lot, except at dev blogs.

How Android is working
Android market is the main source from which users download mobile Apps to their phones. First thing that we noticed is that Google, the grandmaster of web search engines, doesn’t even have search feature on Android Market website so you can not find mobile App that you are looking for. By statistics there is only a small amount of payable Apps and their price is around a dollar ($1) and most of the applications on the Market are free.

Web view of Android market v iPhone App store

Google definitely plays whole different game on mobile space. Knock-outing all other players with free OS for all handset Vendors it gained mass and popularity and is trying to secure future dominance over mobile search and advertisement, Apps. This isn’t such a bad strategy after all if you think that predictions for Mobile market are $17.5 billion $ by 2012.

Developers are the most collateral damage inside Android value system. They are trying to make good Apps and it is a shame that Google don’t care to promote developers properly with better Market and it looks like Google is the only one who gains profit out of this relationship. Is it also true that Google has been lucky, or to say it better, just on time with Android launch and become the only real competitor to iPhone, which is sold by only one vendor – Apple.

On the contrary, Android, that has open approach, allowed many different vendor carriers to get into smart phone market (HTC, SAMSUNG, …). Taking advantage of growing Apps market and advertising Android platform Google is collecting large statistic numbers for variety of marketing use. At the same time public relationship (mostly fans) has done a great job hiding the background of so called always beta Android platform.


Why Android is not very friendly for developers and can improve a lot in the future?

  1. No earnings for developers Developers have less chances to earn money on the market since the users expect to download FREE applications - good for users, bad for developers. In the long term is also bad for users because they will get lower quality products. Here are not counted enterprise solutions for real clients.
  2. Market is not organized Market is huge, tens of thousands of Apps, lots of daily uploads with no quality control... Lots of free Apps are very poor and not very good and this means that is harder to find a quality product on Android market. Consider how can normal user find your application?
  3. Bad API consistency Java in theory is a good idea, you should learn language, coded once and then run the code on different platforms and Android runs Java applications. Android platform have different features, like file structure, graphical interface, accessing hardware features, etc. So programmers make APIs and libraries to simplify development, to avoid writing code for same functionality over and over again. Android API has like every other API issues with backward compatibility, extensibility, maintainability... and backward compatibility is poor, applications written for 2.1 are not guaranteed to work on newer phones (2.2). Code does not necessarily compile for latest version because Google has renamed a method or a constant (e.g. frequently used FILL_PARENT renamed to MATCH_PARENT).
  4. API bugs API documentation is sometimes inaccurate and outdated, for example saying "this method will always return a list with at least one element" but what it does is exactly the opposite - returning null. As Android has many documentation issues phone manufacturers interpret documentation in their own way, not following the documentation strictly (e.g. random phone resolutions). Manufacturers improvize to gain some hardware features, like accessing the secondary camera or secondary SD card (e.g. originally /sdcard is for external storage but on Samsung Galaxy S /sdcard is used for internal, /sdcard/sd for external). Developers always have to look for work-arounds, trying to write some logic code at first that it does not work, trying the other way and it does not work either, trying for the third way when it finally works. Dealing with that kind of work-arounds takes time and nerves. In long-term this issues may result in non-consistent APIs, different for each phone model, as it was back in J2ME days.

  5. Other Android disadvantages we experienced:
    • Not so easy customizable (you can change colour of a button but cannot change the transition animation between activities)
    • Emulator is slow, no camera support
    • Sometimes during development testing Phone Galaxy S freezed and the only way to wake up the phone was to take battery out.
    • Not as friendly to use as iPhone, e.g. you have to deal with USB drivers. Not as fast as iPhone.

Conclusion: Android solutions are short-terms for developer, patch it and "works now" and API design is really a large downside for a mass consumer product as it is Android.

Why Android is also not perfect for final users?

  1. Bound to Google Android phone user needs GMail account to download an application from the market. Once a user logs in with GMail account and downloads at least one application it can no longer remove the account from the phone without resetting the phone to the factory defaults. With default settings open Google has chance to always track an account for controlling downloads and tracking IP and GPS location of the phone (default settings on Samsung Galaxy S phone).
  2. Hacks, viruses, security, privacy issue on Android phones can be exploited easily with numerous hacks to unlock the phone (e.g. by uploading custom firmware ROM) or bypass security restrictions (root access hacks). Even with the brand new phone you can type *#*#...# sort of secret codes to access the hidden or debugging features on Android phone. For access to for hidden GPS settings type: *#*#1472365#*#* on Samsung Galaxy S phone).
    Pre-installed system applications can enable Wi-Fi, Bluetooth, camera, browse contacts without user ever knowing or agreeing. In our case we get unwanted silent imports of GMail messages and contacts just by logging with GMail account on the Android market.
  3. Beta quality products for users Nowadays Mobile phone market is already huge and touch screens are very popular and competitors are fighting for every percent on the market. To be a step before or to catch the competitors Google needs to provide Android products fast. Quick releases mean less testing and buggy features, resulting in fair-quality beta products. Samsung Galaxy S is at the time of writing the hottest Android phone on the market and many are comparing as Android iPhone, but guess what: GPS does not even work correctly with the initial firmware. Sometimes touch screen freezes and you cannot turn off or reset the phone because "turn off" is triggered with a touch (there is always a way to take battery out and insert it again).
    To emphasize this test with Galaxy S: Android software is currently the main problem, not hardware. Software could be a whole lot better, hardware is at it's optimum.


What are the conclusion sorted by the facts:

  1. Users expect free apps resulting less $ for developers
  2. Fairly compatible platform versions
  3. Android market is big with lot of toy apps and few very useful everyday applications
  4. Privacy issues: Google holds you and you can not escape
  5. Questionable security, easily exploited platform (hacks)
  6. Constant searching for work-arounds during development
  7. Phone manufacturers use API in its own interpretation
  8. Fair quality software, is it a bug or feature?

Final words

In the terms of software and UX we have to admit that iPhone is currently much better then Android, who is trying to catch up, resulting in quick decisions, bugs, and lower quality product. Android is improving and we can soon expect it will be a stable platform (1 year) and because is »open« platform compare to »closed« iPhone system has lot of potential to overcome iPhone. There is large amount of phone manufacturers that produce Android phones with free Android OS opposite to iPhone which is under Apple control. Very important fact is that number of Android developers are growing more rapidly than developers for iPhone and also on the market Android phones are selling faster then iPhone (USA example). Android is definitely a step forward compared to J2ME but now it looks that it is going to the same problematic direction (resolutions, different hardware, compatibility).

What do you think? Share your thoughts in the comments.

How to create a SSL certificate and bind it to IIS 7.0

This article describes how to create a SSL certificate using OpenSSL and how to setup a HTTPS connection on IIS 7.0 with the created certificate.

IIS7 can import .pfx certificates.
Avoid tutorials that say ‘-des3′ because DES3 is outdated (not secured as others), use RSA instead

Certificate creation using OpenSSL

Download OpenSSL application for Windows:
http://www.openssl.org/related/binaries.html

on Ubuntu:
> sudo apt-get install openssl

Generate a private key and certificate using the command:
> openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout cert.pem -out cert.pem
Country Name (2 letter code) [AU]:SI
State or Province Name (full name) [Some-State]:Slovenia
Locality Name (eg, city) []:Ljubljana
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Avivo d.o.o.
Organizational Unit Name (eg, section) []:
Common Name (eg, YOUR name) []:example.com
Email Address []:info@example.com

Convert to PKCS#12 (.pfx)
> openssl pkcs12 -export -out cert.pfx -in cert.pem -name “Certificate Friendly Name”

You may have to enter a password several times for private key and generated certificate.
cert.pfx file is created when the procedure is successfully completed.

Also be aware to enter domain name under ‘Common Name’

Set-up HTTPS on IIS
Open IIS Manager (Start -> Run -> inetmgr). Click on the root tree node on the left side and select ‘Server Certificates’ on the right side.

When you click on ‘Server Certificates’ you can see  on the far right side. ‘ under ‘Actions’  ‘Import…’ Click on it.

Browse for the generated ‘your_cert.pfx’ file from previous step. Enter the password and click OK.


Certificate now appears on the list.

Back to the IIS tree, right click on a web site and select ‘Edit Bindings…’

Click on ‘Add…’ -> Type = https and choose SSL certificate to your certificate

How to fix IIS problem with multiple certificates

Problem:

On IIS 7 that you can not create more than one HTTPS binding, even though you have more then one SSL certificate and you need HTTPS binding on different hosted websites. If you have one IP address you can bind only one SSL to chosen website. This small application can fix this.

Solution:

Download our mini utility from Codeplex: http://iishttpsbinder.codeplex.com/

How to use:


References:
http://forums.iis.net/t/1117559.aspx
https://www.iis.net/ConfigReference/system.applicationHost/sites/site/bindings

Avivo d.o.o.

Written by developer

November 26th, 2010 at 4:40 pm

Create Linq to SQL classes from .sdf (Local database)

Linq allows to handle data easily. Linq to SQL tools are integrated in Visual Studio but is limited to can generate code only for  certain databases. To create ORM from .sdf database file read on…

What to do?
Copy next script to a file with .bat extension.

Change DATABASE_NAME, DATABASE_PASSWORD and NAMESPACE according to your needs.

@echo off
rem Input parameters
rem DATABASE_NAME should NOT contain spaces
set DATABASE_NAME=MyDatabase
set DATABASE_PASSWORD=mypass
set NAMESPACE=MyNamespace.Database

rem Set full path to SqlMetal.exe
rem For 64-bit Windows
set SQLMETAL="%ProgramW6432%\Microsoft SDKs\Windows\v6.0A\Bin\SqlMetal.exe"
rem For 32-bit Windows
if "%ProgramW6432%"=="" set SQLMETAL="%ProgramFiles%\Microsoft SDKs\Windows\v6.0A\Bin\SqlMetal.exe"

rem Other parameters
set DATABASE_PATH="%CD%\%DATABASE_NAME%.sdf"
set OUTPUT_CS_PATH="%CD%\%DATABASE_NAME%.cs"
set OUTPUT_DBML_PATH="%CD%\%DATABASE_NAME%.dbml"
set CONNECTION_STRING="Data Source=\"%DATABASE_PATH%\"; Password=\"%DATABASE_PASSWORD%\";"

rem Check and run sqlmetal
if not exist %SQLMETAL% goto error-missing-sqlmetal
%SQLMETAL% /conn:%CONNECTION_STRING% /dbml:%OUTPUT_DBML_PATH% /namespace:%NAMESPACE% /context:%DATABASE_NAME%DataContext /pluralize
%SQLMETAL% /conn:%CONNECTION_STRING% /code:%OUTPUT_CS_PATH% /namespace:%NAMESPACE% /context:%DATABASE_NAME%DataContext /pluralize
goto end

:error-missing-sqlmetal
echo Error: cannot find sqlmetal.exe
echo Search location: %SQLMETAL%
goto end

:end

Example

If the database is stored in C:\db\Website.sdf then copy script into C:\db\make.bat. Change DATABASE_NAME to Website and run the script. Script should generate C:\db\Website.cs and C:\db\Website.dbml files. Include the generated .cs file into your project.

Using the generated code

class Program
{
  static void Main()
  {
    //Suppose that Website.sdf has Page table with CreationDate column of type DateTime
    WebsiteDataContext db = new WebsiteDataContext(@"C:\db\Website.sdf");
    var list = from p in db.Pages
                 where p.CreationDate > DateTime.Today
                 selet p;

    //Show number of pages that match Linq query
    Console.WriteLine(list.Count() + " pages created today.");
  }
}

Written by developer

March 30th, 2010 at 7:53 pm

Posted in Projects

Tagged with , , , , , , ,

Auto-incement assembly build version in Visual Studio 2008

When building a project with Visual Studio an output assembly with embedded version is generated. Version indicates how an application is advancing in development.

Developer can change output assembly version for each project by opening project’s properties (right click, Properties), clicking Assembly Information… button and editing text in fields (see marked area on the image below).

VS2008 window for changing assembly version

VS2008 window for changing assembly version

Alternative is to open Properties/AssemblyInfo.cs or .vb and change AssemblyVersion value in a text editor.

Version can be automatically incremented on each build. To enable counter open Properties/AssemblyInfo.cs and set:

//Change AssemblyVersion's value from 1.0.0.0 to 1.0.* and comment AssemblyFileVersion
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]

Auto-increment symbol (‘*’) cannot be set in GUI (like screenshot above) but only in code.

Written by developer

January 18th, 2010 at 5:12 pm