My name is Juri Strumpflohner and this is my technical blog. I'm a software architect, .Net, Android, Web and Java dev, TDD and best practices promoter and martial arts practitioner.

Recent Posts Subscribe

Dear reader of Juri's TechBlog,
I moved my blog to a new domain and a new hosting solution as well. I'm now blogging on juristr.com.

Server Error: Validation of viewstate MAC failed.

If you get the following error...

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

You have to specify the "<machinekey>" in your web.config. Actually the error itself already explains it.
<system.web>
    <machineKey validationKey="yourAlphaNumericValidationKey" decryptionKey="yourAlphaNumericDecryptionKey" validation="SHA1"/>
   ...
<system.web>
    

VS Designer: 'X' could not be set on property 'Y'

I'm currently developing some custom ASP.net server controls. Internally I often have lists, where the user (programmer) can specify a variable number of sub-controls which are consumed/managed by the parent custom server control:

public List<SomeControl> SomeControls
{
  get
  {
    ...
  }

  set
  {
    ...
  }
}

This kind of list is used for controls where the user (programmer) specifies something like
<mySrvCtrls:MyServerControl id="mySrvControl1" runat="server" ...>
  <mySrvCtrls:SomeControl id="...1" runat="server" ... >
  <mySrvCtrls:SomeControl id="...2" runat="server" ... >
  <mySrvCtrls:SomeControl id="...3" runat="server" ... >
</mySrvCtrls>

They're already working, but now I'd like to add some VS designer support, since when switching to Design-View my controls throw the error
'SomeControl' could not be set on property 'SomeControls'
Apparently the problem is that collections of controls such as my "SomeControls" (dummy) property here, have to be specified as readonly, meaning to change them to something like
public List<SomeControl> SomeControls
{
  get
  {
    ...
  }

}

But still, in such a case you have to pay attention to ensure in your get that you're properly instantiating the collection you're returning if it's null.
public List<SomeControl> SomeControls
{
  get
  {
    if(_SomeControls == null)
      _SomeControls = new List<SomeControl>();
    
    return _SomeControls;
  }

}

This solved my design-time error.

Automatically find the Label associated to a WebControl through the AssociatedControlID

ASP.net Label controls own the property "AssociatedControlID" which points to the control to which the label is associated. This property will then be rendered as "for" attribute on the final HTML.  This property is however one-way only: it's easy to find the associated control at runtime but there is no way to have a control, say a TextBox, and to find it's associated label (if any). There are however situations where you'd like to get this kind of information. Just to mention one: think of a custom TextBox control which, its visibility property is set to false at runtime, automatically also hides it's associated label. This is just a "dummy scenario" but it has some realistic elements.

Since I recently faced a similar situation I implemented a way for reaching the associated label of a WebControl. The idea is to collect all of the Label controls within a certain container (i.e. UserControl, Page, Panel etc...) and to use a Dictionary for creating the link between label and associated control. See the code example below.

private IDictionary<string, Label> associatedLabels; //1st=controlID, 2nd=Label instance
...
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    ...
    associatedLabels = new Dictionary<string,Label>();
    FindAllLabelControls(this.Page, associatedLabels);
    ..
}

...

/// <summary>
/// Finds all label controls on the page that have the AssociatedControlID set and adds them
/// to the passed Dictionary <paramref name="labelCollection"/>
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="labelCollection">The label collection.</param>
private void FindAllLabelControls(Control parent, IDictionary<string, Label> labelCollection)
{
    if (labelCollection == null)
        throw new ArgumentNullException("The IList<Label> labelCollection is null! That cannot be!");

    if (parent is Label)
    {
        Label lbl = parent as Label;
        if (!String.IsNullOrEmpty(lbl.AssociatedControlID))
            labelCollection.Add(new KeyValuePair<string, Label>(lbl.AssociatedControlID, lbl));
    }
    else
    {

        foreach (Control ctrl in parent.Controls)
        {
            FindAllLabelControls(ctrl, labelCollection);
        }
    }
}

Now, finding the label is easy...
Label lbl = null;
associatedLabels.TryGetValue(controlID, out lbl);

Note, the "FindAllLabelControls" method is recursive and may pose some performance degradation, although it shouldn't be that much if you choose the "parent" argument wisely :)

HTML list item background image disappears on IE

I recently faced the problem that the background images that have been added to an HTML li tag over CSS disappeared on Internet Explorer (on Firefox and Webkit browsers everything worked fine).

What I noticed is that the problem just happens when the text is wrapped to a new line. The following figure shows when it's working correctly

and if you then decrease the size of the browser window (or on a computer with a lower screen resolution) you'll get this result
Note that the icon is missing on the last list entry. The solution is to add the "position:relative" to the ul tag, either directly or over the corresponding CSS class
<ul style="position:relative">
 <li>...</li>
 <li>...</li>
</ul>

ExecutableTask pattern to tackle J2ME multithreading

Programming on the mobile device is quite different to more common environments like web or client-server desktop applications. Although mobile devices become always more and more powerful (i.e. like iPhone's OS and Android) one has still to consider issues like limited memory and I/O devices. Take for instance a look at the Android best practices.

When programming on J2ME for the CLDC these kind of things are key issues that have to be considered. There are a number of best practices around, one being the advise to place "heavy" computations in a separate thread in order to not block the J2ME system thread. That implies that you'll have to deal with a lot of threads that need to be handled. Keeping track of the execution of these threads can often become quite complicated.
Therefore - in my last J2ME project - I've created what I called the "Executable Task pattern" in order to handle these situations more easily. Actually it's not a pattern per sé but more like a variant of an Observer and Command pattern. A similar approach is used for defining the Java Swing event handlers for button clicks etc.

The "Executable Task" is composed of two objects.

public abstract class TaskProcessListener {
 /**
  * Gets invoked when the {@link ExecutableTask} finishes processing
  * @param result the resulting object from the computation
  */
 public abstract void onSuccess(Object result);
 
 /**
  * Gets invoked when an error occurs during processing
  * @param status the status message containing information about the error
  */
 public abstract void onError(String status);
}

This is the abstract class that defines the abstract methods that have to be implemented. This "TaskProcessListener" is used by the 2nd class, the "ExecutableTask".
public abstract class ExecutableTask implements Runnable {
 protected TaskProcessListener listener;
 
 public ExecutableTask(){ 
 }
 
 public void run(){
  //initializations prior the execution of the task itself
 }
 
 public ExecutableTask(TaskProcessListener listener){ 
  this.listener = listener;
 }

 protected void notifyTaskFinished(Object result){
  this.listener.onSuccess(result);
 }
 
 protected void notifyError(String statusMessage){
  this.listener.onError(statusMessage);
 }

 public TaskProcessListener getListener() {
  return listener;
 }

 public void setListener(TaskProcessListener listener) {
  this.listener = listener;
 }
}

This is the main class, but still quite simple, isn't it? There isn't much to explain here, just a couple of class members and getters and setters. Note however that the class is declared abstract and that it inherits from "Runnable", meaning that it can be executed within a thread.
Now comes the interesting part. When you actually have an operation that needs to run within his own thread (i.e. a network access) you inherit from the ExecutableTask class instead of Runnable as you would usually do. Consider for instance the simple code for downloading an Image from the web by using an HttpConnection which I've posted a couple of days ago. You would code that as follows:
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;

public class ImageLoaderTask extends ExecutableTask {
 private String imageUrl;
 
 public ImageLoaderTask(String imageUrl){
  this.imageUrl = imageUrl;
 }

 public void run() {
  HttpConnection connection;
  try {
   connection = (HttpConnection) Connector.open(this.imageUrl);
   connection.setRequestMethod(HttpConnection.GET);
   
   Image loadedImg = Image.createImage(connection.openInputStream());
   notifyTaskFinished(loadedImg);
  } catch (Exception e) {
   notifyError(e.getMessage());
  }
 }
 
}

The instantiation of the ImageLoaderTask is then done by writing...
ImageLoaderTask imageLoadTask = new ImageLoaderTask(imageUrlField.getString());
imageLoadTask.setListener(new TaskProcessListener(){

 public void onError(String status) {
  //alert the user about the problem
 }

 public void onSuccess(Object result) {
  //do something with the result
 }
 
});
...again really simple. You can use the "onError(...)" for notifying the user about some problem during the execution of the task and the "onSuccess(...)" for processing a successful outcome.
The following Form demonstrates the usage of the ImageLoaderTask:
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;

public class ImageForm extends Form implements CommandListener {
 private TextField imageUrlField;
 private Command loadImage;
 private Display display;

 public ImageForm(Display display) {
  super("Image Viewer");
  init();
  this.display = display;
 }

 private void init() {
  imageUrlField = new TextField("Image URL", "", 999, TextField.URL);
  this.append(imageUrlField);

  loadImage = new Command("Load Image", Command.SCREEN, 1);
  this.addCommand(loadImage);

  this.setCommandListener(this);
 }

 public void showLoadedImage(Image image) {
  if(this.size() == 2)
   this.delete(1);
  this.imageUrlField.setString("");
  this.append(image);
  this.setTicker(null);
 }

 public void commandAction(Command c, Displayable d) {
  if (c == loadImage) {
   downloadImage();
  }
 }
 
 private void showMessage(String message){
  this.setTicker(new Ticker(message));
 }
 
 private void stopMessage(){
  this.setTicker(null);
 }
 
 private void downloadImage(){
  showMessage("loading image");
  
  ImageLoaderTask imageLoadTask = new ImageLoaderTask(imageUrlField.getString());
  imageLoadTask.setListener(new TaskProcessListener(){
  
   public void onError(String status) {
    stopMessage();
    
    //show an alert notifying about the problem
    Alert alert = new Alert("Error", "Error when loading image " + status, null, AlertType.ERROR);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert);
   }
  
   public void onSuccess(Object result) {
    showLoadedImage((Image)result);
   }
   
  });
  
  Thread t = new Thread(imageLoadTask);
  t.start();
 }

}

What is a browser?

Do you know the answer? I'm pretty sure (> 90% of the blog readers here have a technical background). But check out this video to get a feeling of how non-technical users view the world of browsers, search engines and the Internet.

This survey has been conducted by Google and just about 8% knew the correct answer. The other 92% have no clue of what is IE, FF or Chrome. They even mix up things like search engines and browsers. This demonstrates how difficult it is to gain market share on browser applications and is probably also one of the reasons why Internet Explorer is still the most-used browser (by non-tech people): Just because Windows is the most widely distributed Operating System and it ships Internet Explorer. For non-tech users "Internet Explorer" is "the Internet". That's why sentences like "Can someone help me, I deleted the Internet" come up :)