Solving development problems  |  About this blog

Archive for the ‘c#’ tag

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

So, you can not delete Cookie? Huh, something about headers or headache…

We wanted to delete cookie setting its expired date property to something in the past like this:

HttpCookie cookie = new HttpCookie(this.Name);
cookie.Expires = DateTime.UtcNow.AddMonths(-1);
HttpContext.Current.Response.Cookies.Add(cookie);
But we got an error:

Server cannot modify cookies after HTTP headers have been sent.

After searching and searching if we have somewhere Response.Write in or ASP.NET MVC code we found out that we don’t have such things.
Suddenly, we found out that we played with Session object (trying to clear it) before deleting Cookie and that was it. Reordering these operations solved our problem.

Conclusion
Session object also use cookies, we forgot.

Update on this case

This “solution” didn’t helped… Everything is so simple and was done with JQuery cookie plugin. One line of code from Javascript!

Create random web hex color in C# / ASP.NET MVC

Random random = new Random();
int red = random.Next(0, 255);
int green = random.Next(0, 255);
int blue = random.Next(0, 255);
string hexColour = String.Format("#{0:X2}{1:X2}{2:X2}", red, green, blue);

Written by Avivo

April 22nd, 2011 at 11:46 pm

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

How to trim leading and trailing HTML spaces in C#

Some HTML WYSIWYG editors create ‘br’ tags or leave ‘&nbsp;’ garbage spaces when no content is entered. Described TrimWhiteSpaces method is useful when you need to determine if user left blank content in WYSIWYG editor or if you just want to clean HTML code.

TrimWhiteSpaces accepts raw HTML content and removes white spaces, tabs, new line characters, ‘br’ tags and ‘&nbsp;’ chunks from before and after the actual content.

public static string TrimWhiteSpaces(string html)
{
  string result = html;

  //Remove leading spaces
  result = Regex.Replace(result, @"^(?<leading>(\s|\r|\n|\<br\s*/?\>|&nbsp;)*)", "",
RegexOptions.IgnoreCase);

  //Remove trailing spaces
  result = Regex.Replace(result, @"(?<trailing>(\s|\r|\n|\<br\s*/?\>|&nbsp;)*)$", "",
RegexOptions.IgnoreCase);

  return result;
}
Example:
Input:

&nbsp;<br /><BR   ><BR> &nbsp;
&nbsp;&nbsp;<br />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
&nbsp;&nbsp;<br />
<p>Pellentesque lorem neque, accumsan eget euismod ut, tristique et odio.</p>
&nbsp;<br /> <br>
&nbsp;
Output:


<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
&nbsp;&nbsp;<br />
<p>Pellentesque lorem neque, accumsan eget euismod ut, tristique et odio.</p>

Written by developer

December 13th, 2010 at 1:27 pm