Alle Beiträge von Sascha Baumann

Generic View Models in Silverlight

I like using Base-Classes for any kind of “Class-Group”. Very prominent groups are Models and ViewModels in Silverlight-Applications.

The ViewModel-Baseclass can hold any functionality, that applies to every ViewModel inheriting from it and, if we are talking about Generics, can be very convenient to use.

For example, if I want to apply the factory-pattern to my ViewModels and want every Model to have a static Create-Method I can simply implement this Method in the Base-Class.

public class ViewModelBase 
{ 
	public virtual ViewModelBase Create() 
	{ 
		return new ViewModelBase(); 
	} 
} 

Of cause, without Generics we are limited to the return-Type. We could now override this method in every specific ViewModel to at least return the right ancestor of ViewModelBase. An easier way is, to use Generics for this case. The class could look like this :

public class ViewModelBase where TViewModel : ViewModelBase 
{ 
	public virtual TViewModel Create() 
	{ 
		return Activator.CreateInstance(typeof(TViewModel)); 
	} 
} 

Now we can simply create our new specific ViewModel like this

public class MyViewModel : ViewModelBase

to get what we want generically.

 

Another possible scenario would be the following. We know, every ViewModel contains a Collection of Models, all inheriting from a class called ModelBase. we could extend out code the following way:

public class ViewModelBase where TViewModel : ViewModelBase 
{ 
	public virtual TViewModel Create() 
	{ 
		return Activator.CreateInstance(typeof(TViewModel)); 
	} 
	
	public List MyList {get;set;} 
} 

or, the better way, we could extend our Generic header to be type safe.

public class ViewModelBase 	
                                        where TViewModel : ViewModelBase 
					where TChildModel : ModelBase 
{ 
	public virtual TViewModel Create() 
	{ 
		return Activator.CreateInstance(typeof(TViewModel)); 
	} 

	public List MyList {get;set;} 
} 

Defining a Class by

public class MyViewModel : ViewModelBase

Like always, if we talk about inheritance, you should avoid to go too far with that. I implemented a Framework I use for rapid prototyping where a lot of things are done in the base-class via reflection, but in a productive environment its not always what you want. Plan your development as precise as possible.

  • What do you want to be individually implemented by each ViewModel ?
  • When is it a good thing to implement it in the Base-Class ?
  • How confusing is you inheritance for other developers ?

 

Good Luck 😮

Extension Methods in VB.Net

My preferred .NET-language is C#, but as a consultant I have to write VB every once in a while. Here is a little introduction, how my beloved
Extension Methods work in VB.Net.

Just two steps:

Step1 – Create a new Module called for example “StringExtensions.vb” and add an Import –Statement for System.Runtime.CompilerServices

Step2 – Write your Extension Method, and put an <Extension()> directive on top. Here is an example:

 _
    Public Function AddAbcX(ByVal mystring As String) As String
        Return myString + "ABC"
    End Function

Notice the _ behind the directive. Don’t forget this one.

You notive one additional thing. A while ago I read an article about Extension Methods and got the suggestion to add an X to each methodname.
So, if using intellisense, you will see directly if the method you’re about to call is an Extension Method or a build-in Method. Good idea I think.

Another suggestion – Put the method in the same namespace as the object it belongs to (I said namespace, not file!).

So you have your methods ready when you start using the object.

Cheers
Sascha

Styles from different files as static resources

Hello everyone,

to start a silverlight project, i have a kind of default-template which I enriched with a CSS-like decentralized style today. This is done very easy now in Silverlight 3. First you habe to set up a file containing your style. In my case it was a file in a new Styles folder called TextBock.Default.xaml where I entered this dummy code:


    
        
        
        
        
    

after that, I created a MergedDictionary in my app.xaml like that:

 
         
             
                 
             
          
     

from now on, you can call this style like you’re used to with {StaticResource TextBlock.Default} within your application. Nice way to manage the styles as I think, and much easier to maintain than having all your styles plugged in your app.xaml in total.

Have fun playing with it :o)
Sascha

InitParams with Out-Of-Browser Apps

Hello everyone,

I just tried to figure out, how to pass initial parameters to a Silverlight App, that runs out of browser. We dont have a Webpage to pass InitParams and we cannot access Web.Config entries.

So i came up with the idea, to use Isolated Storage for this task. Before installing an App Out-Of-Browser we need to access the Webpage. In this case, we can read the initial paramters from Web.Config or from Silverlight-Tag, and store them to Isolated Storage.

Now we need a code-block to check, if app runs OOB (Application.Current.IsOutOfBrowser) and in this case, we read the paramters from Isolated Storage instead. So the OOB-App is configured the same way as the Web-App.

This was just one Idea, that worked. Any other suggestions are very welcome.

C#-Code dynamisch kompilieren mit CodeDom – Ein Beispiel

Guten Nachmittag,
die Aufgabenstellung war in diesem Fall so simpel wie kompliziert. Eine Formel die als String vorlag, sollte evaluiert werden. Nach einiger Suche stieß ich dann auf eine Lösung mit JScript und VSA. Für die Lösung mussten zunächst das Assembly Microsoft.JScript im Projekt referenziert werden und über using Microsoft.JScript eingebunden werden.

Der Code für die Funktion sah dann so aus:

public static string Eval(string Formular)
{
     return Microsoft.JScript.Eval.JScriptEvaluate(Formular, Microsoft.JScript.Vsa.VsaEngine.CreateEngine()).ToString();
}

so weit so gut. Ich möchte hier aber noch eine zweite Variante anführen, die etwas moderner ist und auf dem CodeDom von DotNet basiert. Hierfür müssen auch keine extra Assemblies referenziert werden.
Zunächst benötigt man eine Methode, die eine Klasse dynamisch erzeugt.

private object MathSolver(string Formular)
{
            // Der dynamische Code
            StringBuilder sb = new StringBuilder ();
            sb.Append("using System;");
            sb.Append("using System.Collections;");
            sb.Append("public class DynamicMathSolver");
            sb.Append("{");
            sb.Append("  public decimal Eval()");
            sb.Append("  {");
            sb.Append("          return " + Formular + ";");
            sb.Append("  }");
            sb.Append("}");

            Microsoft.CSharp.CSharpCodeProvider scp = 
                 new Microsoft.CSharp.CSharpCodeProvider();
            System.CodeDom.Compiler.ICodeCompiler cc = 
                 cs.CreateCompiler();
            System.CodeDom.Compiler.CompilerParameters cp = 
                 new System.CodeDom.Compiler.CompilerParameters();
            System.CodeDom.Compiler.CompilerResults Results = 
                 cc.CompileAssemblyFromSource(cp, sb.ToString());
            return Results.CompiledAssembly.CreateInstance("DynamicMathSolver");
        }

Im Anschluss muss die Klasse nur noch angesprochen, und mittels Reflection die Methode aufgerufen werden.

public string Result
        {
            get
            {
                    // Evaluate Formula
                    object objMathSolver = MathSolver(SolvedFormula);
                    string  result = 
                          DynamicMathSolver.GetType().GetMethod("Eval").Invoke(DynamicMathSolver, null).ToString();
                }
                return result;
            }
        }

Das war nur ein Beispiel für das erzeugen einer dynamischen Klasse. Dieses vorgehen lässt sich aber sicher noch für eine Vielzahl weiterer Fälle verwenden.

Haltet mich mal auf dem Laufenden, was Ihr damit so anstellt !
Sascha Baumann