Solving development problems  |  About this blog

Archive for the ‘Silverlight/WPF’ Category

The easiest way to generate a QR Code for software developers

So you want to simply generate a QR Code image without diving into the technical specifics? This blog post contains a few simple examples. Just copy-paste where you need it.

Idea is to build a URL, make an HTTP request and download the QR Code image. Result is the following image:

your content goes here

HTTP Request

URL looks like http://www.esponce.com/api/v3/generate?content={content}&format={format} where {content} is URL encoded content to be embedded in QR and {format} is output image format. Available formats are png, jpg, bmp, tif, xaml, svg, eps, txt, html, zip (containing all listed formats)

List of other parameters like color and size can be found here.

C# Sample

This code can be used in .NET 2.0 including ASP.NET and WPF or Silverlight for web or WP7

using System;
using System.IO;
using System.Web;
using System.Net;

public class Program
{
  public static void Main(string[] args)
  {
    //Generate a QR Code and save it to file "sample.png"
    Generate("your content goes here", "png", "sample.png");
  }

  public static void Generate(string content, string format, string path)
  {
    string encoded = HttpUtility.UrlEncode(content);
    Uri uri = new Uri("http://www.esponce.com/api/v3/generate?content=" + encoded + "&format=" + format);
    WebClient client = new WebClient();
    client.DownloadFile(uri, path);
  }
}

Java Sample

This code can be used in a classic Java application or web applet or Android application

import java.io.*;
import java.net.*;

public class qrcode
{
  public static void main(String args[])
  {
    //Generate a QR Code image and save it to file "sample.png"
    generate("your content goes here", "png", "sample.png");
  }

  public static void generate(String content, String format, String path)
  {
    try
    {
      String encoded = URLEncoder.encode(content, "UTF-8");
      String url = "http://www.esponce.com/api/v3/generate?content=" + encoded + "&format=" + format;
      BufferedInputStream ins = new BufferedInputStream(new URL(url).openStream());
      FileOutputStream fos = new FileOutputStream(path);
      BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

      int size = 0;
      byte data[] = new byte[1024];
      while ((size = ins.read(data, 0, 1024)) > 0)
      {
        bos.write(data, 0, size);
      }

      bos.close();
      fos.close();
      ins.close();
    }
    catch (Exception e)
    {
    }
  }
}

Python Sample

Using Python 2.7

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import urllib
import httplib

def generate(content, format = "png"):
    query = urllib.urlencode({ "content": content, "format": format })
    con = httplib.HTTPConnection("www.esponce.com")
    con.request("GET", "/api/v3/generate?" + query)
    response = con.getresponse()
    image = response.read()
    con.close()
    return image

image = generate("your content goes here")
file = open("sample.png", "wb")
file.write(image)
file.close()

JavaScript Sample

JavaScript in combination with HTML

<img id="qrcode" src="" alt="QR Code" />
<script type="text/javascript">
    function generate(content)
    {
        var url = "http://www.esponce.com/api/v3/generate?content=" + encodeURI(content) + "&format=png";
        var img = document.getElementById("qrcode");
        img.src = url;
    }
    generate("your content goes here");
</script>

PHP Sample

<img src="<?php echo generate("your content goes here"); ?>" alt="QR Code" />

<?php
function generate($content, $format = "png")
{
    $encoded = urlencode($content);
    $url = "http://www.esponce.com/api/v3/generate?content=$encoded&format=$format";
    return $url;
}
?>

There is more

Download all samples with make script here.

Other QR Code related methods like decoding (reverse process of generating) and tracking scans can be found at esponce.com.

Written by developer

January 24th, 2012 at 3:46 pm

Set IIS binding manually (add and remove IIS binding)

We had an issue that we need to add or remove IIS 7 or IIS 7.5 additional bindings on one web application and we wanted to do this from one of our ASP.NET MVC applications.

It is possible so you need to use IIS system program appcmd.exe (you can find it in C:\Windows\System32\inetsrv\ (we suggest you to put this into your PATH variable)

Adding additional bindings

You want to add your-subdomain.your-domain.com binding to your IIS 7 app named your-domain.com

C:\Windows\System32\inetsrv\appcmd set site /site.name: your-domain.com /+bindings.[protocol='http',bindingInformation='*:80:your-subdomain.your-domain.com']

Removing existing bindings

You want to remove your-subdomain.your-domain.com binding from your IIS 7 app named your-domain.com (please notice - sign in front of bindings word)

C:\Windows\System32\inetsrv\appcmd set site /site.name: your-domain.com /-bindings.[protocol='http',bindingInformation='*:80:your-subdomain.your-domain.com']

And that’s it but if you want to run it from ASP.NET you could try to use Process and ProcessInfo classes to run DOS command but there are some permissions problems (we didn’t investigated much).

Other (alternative way that we tried is directly from the code)
You will need to reference this DLL: c:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll

using (ServerManager serverManager = new ServerManager())
{
  if (serverManager.Sites == null)
    throw new SimpleException("There are no IIS applications!");

  var esponceApp = serverManager.Sites.FirstOrDefault(
x => x.Name == Settings.IISAppName);
  if (esponceApp != null)
  {
    BindingCollection bindingCollection = esponceApp.Bindings;
    Binding binding = bindingCollection.CreateElement("binding");
    binding["protocol"] = "http";
    binding["bindingInformation"] =
string.Format(@"{0}:{1}:{2}", "*", "80", this.DomainName);

    //Remove this binding if already exists.
    int oldBindingIndex = -1;
    int bindingIndex = -1;
    foreach (Binding currentBinding in esponceApp.Bindings)
    {
      if (currentBinding.BindingInformation ==
binding["bindingInformation"].ToString())
      {
        bindingIndex = esponceApp.Bindings.IndexOf(currentBinding);
      }
      if (!string.IsNullOrEmpty(oldDomainName) &&
      currentBinding.BindingInformation ==
string.Format(@"{0}:{1}:{2}", "*", "80", oldDomainName))
      {
        oldBindingIndex = esponceApp.Bindings.IndexOf(currentBinding);
      }
    }
    if (bindingIndex != -1)
    {
      esponceApp.Bindings.RemoveAt(bindingIndex);
    }
    if (oldBindingIndex != bindingIndex && oldBindingIndex != -1)
    {
      esponceApp.Bindings.RemoveAt(oldBindingIndex);
    }

    //Add this bindings
    bindingCollection.Add(binding);
    serverManager.CommitChanges();
  }
}
}
catch
{
throw new SimpleException("Could not add binding into IIS application!");
}

Important!
Set identity of your app’s Application Domain from Advanced Settings > Process Model > Identity > Change “ApplicationPoolIdentity” to “Local System”

Investigate also security implications if you are not running this in Intranet….

Silverlight: Equidistant items in a stack panel

This post describes how to align items in a container so the two neighbour items are always aligned with equal distance. Solution should be flexible, meaning that when items are changed or when container is resized items should keep equal distance in between. Reader should have some basic knowledge about C# and XAML for Silverlight.

Ideas

  • using Canvas and positioning items with absolute coordinates – items are always fixed, coordinates need to be calculated, so it is the least flexible approach, no
  • using StackPanel with items that have margin – margins need to be recalculated when an item is added or removed or when container is resized, maybe
  • using Grid with predefined rows and columns – notice predefined, means less flexibility, but offers equal size rows/columns, maybe
  • using a custom control – making Grid more dynamic but extending number of rows/columns when items are added, yes

Custom Control: EqualDistanceStackPanel

As written before, custom control should extend Grid to become more flexible

public class EqualDistanceStackPanel : Grid
{
}

 

EqualDistanceStackPanel should implement ItemsSource and ItemTemplate just like ItemsControl

#region ItemsSource
public IEnumerable ItemsSource
{
  get { return (IEnumerable)GetValue(ItemsSourceProperty); }
  set { SetValue(ItemsSourceProperty, value); }
}

public static readonly DependencyProperty ItemsSourceProperty =
  DependencyProperty.Register("ItemsSource", typeof(IEnumerable),
  typeof(EqualDistanceStackPanel), new PropertyMetadata(ItemsSourceChanged));

private static void ItemsSourceChanged(DependencyObject d,
  DependencyPropertyChangedEventArgs e)
{
  var panel = d as EqualDistanceStackPanel;
  if (panel != null)
  {
    if (e.OldValue != null)
    {
      panel.ClearItems();
    }
    if (e.NewValue != null)
    {
      panel.BindItems(e.NewValue as IEnumerable);
    }
  }
}
#endregion

public DataTemplate ItemTemplate
{
  get;
  set;
}

 

ClearItems method deletes all previous elements from the panel and BindItems attaches fresh controls from item template.

protected void ClearItems()
{
  this.Children.Clear();
}

protected void BindItems(IEnumerable items)
{
  if (this.ItemTemplate == null)
  {
    return;
  }

  //Create and attach children
  foreach (var item in items)
  {
    var element = this.ItemTemplate.LoadContent() as FrameworkElement;
    element.DataContext = item;
    this.Children.Add(element);
  }

  //Realign in container
  Refresh();
}

 

How should the custom control look in XAML? EqualDistanceStackPanel gets a collection of items, e.g. of UIElement type.

<Grid xmlns:c="clr-namespace:Avivo.Controls">
  <c:EqualDistanceStackPanel ItemsSource="{Binding Items}" Orientation="Vertical">
    <c:EqualDistanceStackPanel.ItemTemplate>
      <DataTemplate>
        <ContentPresenter Content="{Binding}" />
      </DataTemplate>
    </c:EqualDistanceStackPanel.ItemTemplate>
  </c:EqualDistanceStackPanel>
</Grid>

 

Example

Ruler has been made to demonstrate the usage of EqualDistanceStackPanel. Numbers are bound to the control and ticks are bound to another control using the same binding collection. Left image represents container height 300px and right when resized to 460px – elements are automatically aligned with equal distance.

Try demo, resize browser to see the effect. This control has been originally developed for custom chart axes in QR Code Statistics application. EqualDistanceStackPanel control is lightweight, works for the statistics application and should be improved for general usage.

Source code

  • Source code, Visual Studio sample Silverlight and web project

References

Written by developer

March 29th, 2011 at 2:00 pm

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 service cannot be activated due to an exception during compilation. The exception message is: This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.

You can solve this issue by adding the following code to your web.config:

<system.serviceModel>
	...
	<serviceHostingEnvironment>
	  <baseAddressPrefixFilters>
	  	<add prefix="http://sample.domain.tld/Sample/"/>
	  </baseAddressPrefixFilters>
	</serviceHostingEnvironment>
	...
</system.serviceModel>