Darko Micics Development Blog

The first thing I thought when I heard about the Code First approach was: Cool, now we can create clean entities without any EF specific code. After the first demo app I saw, that you have to deal with the IDbSet interface, which is placed in the Entity Framework library. (I’m working with EF 4.3)
When you place the entities in your business dll you have to reference the EF library. This is a bit ugly. After some testing I saw that the IDbSet interface implements the generic IQueryable interface.
So it’s possible to cast the IDbSet to a more common interface.
In this example you will see how to use EF code First without referencing the EF lib in your business library.

Here is a picture of my solution folder. The business dll references only the System lib. In the contract folder is the interface for the infrastructure context defined.
The Domain folder contains the entities.

Solution Folder

Solution Folder


The context interface is very clean. There are no EF specific types used:

public interface IContext
{
    IQueryable People { get; set; }
    IQueryable
Addresses { get; set; } void Add(T obj) where T : DomainObject; void Save(); }

And here are the entities:

public class DomainObject
{
    public Guid MyId { get; set; }
}

public class Person : DomainObject
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public ICollection
Addresses { get; set; } } public class Address : DomainObject { public string Street { get; set; } public string City { get; set; } public int Zip { get; set; } public virtual Person Person { get; set; } }

In the infrastructure library I created a context class which implements the IContext interface.

public class Context : DbContext, IContext
{
    public Context()
        : base("MyDb")
    { }

    public IDbSet PersonSet { get; set; }
    public IDbSet
AddressSet { get; set; } public IQueryable People { get { return this.PersonSet; } set { this.PersonSet = (IDbSet) value; } } public IQueryable
Addresses { get { return this.AddressSet; } set { this.AddressSet = (IDbSet
)value; } } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity() .HasKey(x => x.MyId) .Property(x => x.MyId) .HasColumnName("Id"); base.OnModelCreating(modelBuilder); } public void Add(T obj) where T : DomainObject { this.Set().Add(obj); } public void Save() { base.SaveChanges(); } }

The both public properties PersonSet and AddressSet are used by the EF. But for development only the both properties “People” and “Addresses” are important.
My Entities do not have any entity framework specific Data Annotations like [Key], [ForeignKey] etc.
This definition is made in the OnModelCreating method.
This is it! Here are some test queries:

Database.SetInitializer(new CreateDatabaseIfNotExists());

Business.IContext db = new Infrastructure.Context();

// Create
db.Add(new Person()
        {
            Id = Guid.NewGuid(),
            Firstname = "Darko",
            Lastname = "Micic",
            Addresses =
                new List
() { new Address() { Id = Guid.NewGuid(), Street = "Unknown", City = "City", Zip = 1234 } } }); db.Save(); // Select person var person = db.People.FirstOrDefault( x => x.Firstname.ToLower() == "darko"); // Select person with address var personWithAddress = from u in db.People.Include("Addresses") where u.Firstname.ToLower() == "darko" select u; // select address var address = from u in db.People where u.Firstname.ToLower() == "darko" select u.Addresses;

It is not possible to deploy referenced libraries with the assembly which contains the crm plugins. You can install the libraries into the GAC, but it isn’t really a good solution. Two weeks ago, I found a cool solution in the internet about embedding referenced assemblies into one library or exe. I implemented this code in my crm plugin project.

 

Example
Here is my plugin project with 5 referenced libraries. Inside the project I created a folder “_Resource” and defined a pre-build event, which copies the compiled referenced libraries into this folder. Then I set the “build action” to “embedded resource”.

 

Embedded Libraries

Embedded Libraries


With this pre-build event the IDE copies the dlls into the resource folder. (Example with the business dll)

copy $(ProjectDir)..\MyProject.Business\$(OutDir)\MyProject.Business.dll $(ProjectDir)_Resource /Y
 

After compiling the solution, the referenced assembly are embedded inside the plugin dll.
Here is a picture of the compiled dll.

 
Embedded Libraries in DLL

Embedded Libraries in DLL

 

Now we need custom code, which loads the embedded dll at runtime.

AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
    var resourceName = AssemblyLoader.ResourceName + new AssemblyName(args.Name).Name + ".dll";

    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
    {
        Byte[] assemblyData = new Byte[stream.Length];
        stream.Read(assemblyData, 0, assemblyData.Length);
        return Assembly.Load(assemblyData);
    }
};

The runtime raises the “AssemblyResolve” event when the the resolution of an assembly fails.
The code above loads the assembly out of the resources and returns it to the runtime.
This is it! Now you can split your code in 100 assemblies (like in every good designed application ;) ) and merge them into one file.

 

There are other solutions like “ILMerge”. But the above described solution is the most suitable, because you don’t need extra tools.

In my first crm 2011 project I struggled a little bit with the early binding functionality. When you generate the entities with CrmSvcUtil and place the entities in the plugin project everything works fine. But when you seperate the entities from you plugin logic in a other dll, early binding won’t work.
The first solution I found in the internet was this here. Referencing following libraries in the plugin project:

Microsoft.Crm.ObjectModel.dll
Microsoft.Crm.Platform.Server.dll

And then setting the ProxyTypesAssembly attribute.

(Microsoft.Crm.Extensibility.PipelineExecutionContext)context).ProxyTypesAssembly = typeof(AnyGeneratedEntity).Assembly;

This works fine. But when your plugin runs asynchronous the code above will fail. Because the context isn’t a PipelineExecutionContext object. Context in async plugins are of type AsyncExecutionContext. And this class is placed in the AsyncCrmService.exe (yes! EXE). This means, you have to reference this exe file and cast the context to set the ProxyTypesAssembly.

(Microsoft.Crm.......AsyncExecutionContext)context).ProxyTypesAssembly = typeof(AnyGeneratedEntity).Assembly;

A other solution is to set the ProxyTypesAssembly with reflection. It works but isn’t really a nice solution too.

Both solutions are not very nice. Because you have to reference CRM 2011 dlls,exes which are not really meant for creating plugins, or you have to develop type unsafe.


My solution is
Afer inspecting the AsyncExecutionContext class with ILSpy I found out, that every context implements the interface IProxyTypesAssemblyProvider. And this interface is placed in the xrm sdk ;)

Now, the solution is simple. Remove any CRM 2011 dlls,exes like ObjectModel, Platform.Server or CrmAsyncService.exe and set the ProxyTypesAssembly property like here:

(IProxyTypesAssemblyProvider)context).ProxyTypesAssembly = typeof(AnyGeneratedEntity).Assembly;

(The interface is placed in the xrm sdk dll which you need for plugin development.)

This will work for every other context which supports early binding.

RavenDB is a document database. The main difference between RavenDB and a relational database is, that RavenDB doesn’t support relation between the rows/entities/documents. A document contains structural data, which is stored in JSON format.

This is a quickstart into RavenDB:

Step 1 – Database:
Create a new database. This DB doesn’t contain any structure. It’s just a empty container.

Step 2 – Structure:
Define your entity/POCO/document structure in C#.
I created a company and a employee class. A company can contain multiple employees.

public class Company
{
     public string Id { get; set; }
     public string Type { get { return "company"; } }
     public string Name { get; set; }
     public string Region { get; set; }
     public IList Employees { get; set; }
}

public class Employee
{
    public enum ERole
    {
        CEO,
        CFO,
        Developer
    }

    public string Id { get; set; }
    public string Type { get { return "employee"; } }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public ERole Role { get; set; }
}

Example -> Create new document:
Following code snippet creates a new document with one company and three employees.

using (var documentStore = new DocumentStore { Url = "http://myurl:8080/" })
{
    documentStore.Initialize();

    using (var session = documentStore.OpenSession("testDB"))
    {
        var company = new Company() { Id = "company/1", Name = "Tvd" };
        company.Employees = new List()
            {
                new Employee()
                {
                    Id = "emp/1",
                    Firstname = "Darko",
                    Lastname = "Micic",
                    Role = Employee.ERole.Developer
                },
                new Employee()
                {
                    Id = "emp/2",
                    Firstname = "Steve",
                    Lastname = "Steven",
                    Role = Employee.ERole.Developer
                },

                new Employee()
                {
                    Id = "emp/3",
                    Firstname = "Max",
                    Lastname = "Min",
                    Role = Employee.ERole.CFO
                },
            };
        session.Store(company);
        session.SaveChanges();
    }

The stored document is structured as shown here:

{
  "Type": "company",
  "Name": "Tvd",
  "Region": null,
  "Employees": [
    {
      "Id": "emp/1",
      "Type": "employee",
      "Firstname": "Darko",
      "Lastname": "Micic",
      "Role": "Developer"
    },
    {
      "Id": "emp/2",
      "Type": "employee",
      "Firstname": "Steve",
      "Lastname": "Steven",
      "Role": "Developer"
    },
    {
      "Id": "emp/3",
      "Type": "employee",
      "Firstname": "Max",
      "Lastname": "Min",
      "Role": "CFO"
    }
  ]
}

Example -> Read document:
Reading documents is quiet easy. Open a new session and run a query. (LINQ or with Lambda Expression).
This code here reads the company with the id “company/1″ and updates the name.

using (var documentStore = new DocumentStore { Url = "http://myurl:8080/" })
{
    using (var session = documentStore.OpenSession("testDB"))
    {
        var company = session.Query().Where(x => x.Id == "company/1").FirstOrDefault();
        company.Name = "TVD";
        session.SaveChanges();
    }
}

Example -> Read childs out of a document:
As you can see in the examples above, the employee (child) isn’t stored in a seperate document. (In a relational database you will create
a table for company and one for employee.)
If you want to retrieve ONLY the employees out of a company document, you have to write following code:

using (var session = documentStore.OpenSession("testDB"))
{
    var emps = session.Query("Employees").Where(x => x.CompanyId == "company/1");
    foreach (var e in emps)
    {
        // do something
    }
}

This query excepts a result of type EmployeeResult. The parameter “Employees” is the name of a index, which is defined in the database.
The Employees index contains a match and a transform query.

Match LINQ:

from c in docs.Companies
select new { CompanyId = c.Id }

Transform LINQ:

from c in results
from e in c.Employees
select new { CompanyId = c.Id, Employee = e }

The class EmployeeResult contains the company id an the employee object. This structure corresponds the result of the transform query.

public class EmployeeResult
{
    public string CompanyId { get; set; }
    public Employee Employee { get; set; }
}

(I’m still not sure if there’s an easier way for retrieving the “childs”/employees.)

Happy coding ;)

When you deal with very dynamic dictionaries, you have always to check if the data exists before accessing it. This can blow up your code. With the dynamic data type (.NET 4.0) you can do this a little bit more elegant.

Example:
Here are my data classes. You see that the Person class has a dictionary which can take every object as a value.

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public int ZIP { get; set; }
}

public class Person
{
    public IDictionary<string, object> Data { get; set; }

    public Person()
    {
        this.Data = new Dictionary<string, object>();
    }
}

When you want to get data out of the dictionary you have to do following:

// Check if key exists. Then read and cast the value.
if(pers.Data.ContainsKey("Something"))
   var val = (int)pers.Data["Something"];

With dynamic data type it could be like this.

if(dynPers.HasSomething)
  var val = dynPers.Something;

None of this code is more or less secure. But the approach with the dynamic data type looks better. :)

How it works:
First you have to create a class which derives from DynamicObject. I added to this (abstract) class a generic type “T”. So the code will be usable for other dynamic classes like “Person” too.

public abstract class DynamicHelper<T> : DynamicObject
{
    public T Data { get; private set; }
    public Func<T, string, bool> Exists { get; private set; }
    public Func<T, string, object> GetData { get; private set; }

    public DynamicHelper(T _dynamicData, Func<T, string, bool> _exists, Func _getData)
    {
        this.Data = _dynamicData;
        this.Exists = _exists;
        this.GetData = _getData;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = false;

        if (this.Data == null)
            return false;

        if (binder.Name.ToLower().StartsWith("has"))
        {
            if (this.Exists(this.Data, binder.Name.Substring(3)))
            {
                result = true;
                return true;
            }
            else
            {
                result = false;
                return true;
            }
        }
        else if (this.Exists(this.Data, binder.Name))
        {
            result = this.GetData(this.Data, binder.Name);
            return true;
        }
        result = null;
        return false;
    }
}

Then you have to create a conrecte class, which derives from DynamicHelper. This class here is for my dynamic/flexible type “Person”.

public class DynamicPerson : DynamicHelper
{
    public DynamicPerson(Person _data) : base(_data,
        new Func<Person, string, bool>((p, b) => { return p.Data.Count(x => x.Key.ToLower() == b.ToLower()) > 0; }),
        new Func<Person,string,object>((p, b) => { return p.Data.First(x => x.Key.ToLower() == b.ToLower()).Value; }))
    { }
}

The constructor passes to the base constructor three parameters:

_data Data object. In this example an object of “Person” class.
_exists A Func<> which checks if the data object contains a specific key/property.
_getData A Func<> which retrieves a value out of the the data object.

This is it. Here is a short example:

class Program
{

    static void Main(string[] args)
    {
        Stopwatch watch = new Stopwatch();

        // Initialize data
        Person pers = new Person();
        pers.Data.Add("HelloWorld", "Hello !!!");
        pers.Data.Add("PersonData", new Address()
            {
                City = "Belgrade",
                Street = "Street 123a",
                ZIP = 1332
            });

        Console.WriteLine("------------");

        // Start watch
        watch.Start();

        // Create dynamic object
        dynamic dynamicPerson = new DynamicPerson(pers);

        // Get helloworld
        if (dynamicPerson.HasHelloWorld)
            Console.WriteLine(dynamicPerson.HelloWorld);

        Console.WriteLine();

        // Get data
        if (dynamicPerson.HasPersonData)
        {
            Console.WriteLine("Street: " + dynamicPerson.PersonData.Street);
            Console.WriteLine("ZIP: " + dynamicPerson.PersonData.ZIP.ToString());
            Console.WriteLine("City: " + dynamicPerson.PersonData.City);
        }

        // Stop watch
        watch.Stop();

        // Time
        Console.WriteLine("Elapsed ms: " + watch.ElapsedMilliseconds.ToString());

        Console.WriteLine();
        Console.WriteLine("------------");
        Console.WriteLine();

        // Restart watch and do the same but without dynamic data type
        watch.Restart();

        if (pers.Data.ContainsKey("HelloWorld"))
            Console.WriteLine(pers.Data["HelloWorld"].ToString());

        Console.WriteLine();

        if (pers.Data.ContainsKey("PersonData"))
        {
            Console.WriteLine("Street: " + ((Address)pers.Data["PersonData"]).Street);
            Console.WriteLine("ZIP: " + ((Address)pers.Data["PersonData"]).ZIP.ToString());
            Console.WriteLine("City: " + ((Address)pers.Data["PersonData"]).City);
        }

        watch.Stop();
        Console.WriteLine("Elapsed ms: " + watch.ElapsedMilliseconds.ToString());

        Console.ReadLine();
    }
}

You see that the code above first reads the data out of the “pers” object the dynamic way. Then it reads the same data but the “normal” way with contains-check and casting.

The output is the same:
Dynamic Object

Looks good or not? The code is a bit clearer when using the dynamic extension. But the performance is poor.
The dynamic extension needs !!187ms!! for reading the data. And the other piece of code is a lot faster.

So, use the dynamic way only when speed isn’t very important for you… or for your customer. ;)

One of the new WCF 4.0 features is routing. Routing can be used for multiple purposes:

- Service versioning
- “Extended” load balacing
- Content-based routing scenario
- Service partitioning
- Protocol bridging
- etc.

In this example, I have two person services. One in London and one in Paris. The client knows only the WCF router.
The router filters the client request and calls the appropriate person service.
London uses http and Paris uses net.tcp binding. The clients and the router are communicating via http.
WCF router

The contract for the both person services contains one method:

[ServiceContract]
public interface IPersonService
{
    [OperationContract]
    Person GetPerson(PersonFilter filter);
}

Implementations (London/Paris):


// London service
public class PersonService : IPersonService
{
    public Person GetPerson(PersonFilter filter)
    {
        if (filter.Location.ToLower() == "london")
            return new Person() {  Firstname = "John", Lastname = "Owen" };
        return null;
    }
}

// Paris service
public class PersonService : IPersonService
{
    public Person GetPerson(PersonFilter filter)
    {
        if (filter.Location.ToLower() == "paris")
            return new Person() { Firstname = "André", Lastname = "Moutiers" };
        return null;
    }
}

The London service uses basicHttpBinding. Here is the configuration.


  
    
      
        
        
          
            
          
        
      
    
  

And the Paris service uses netTcpBinding:



  
    
      
        
        
          
            
          
        
      
    
  

The services are running in console applications. (self-hosted)

// London
class Program
{
    static void Main(string[] args)
    {
        var host = new ServiceHost(typeof(PersonService.PersonService));
        host.Open();
        Console.WriteLine("London PersonService running.");
        Console.ReadLine();
        host.Close();
    }
}

// And paris
class Program
{
    static void Main(string[] args)
    {
        var host = new ServiceHost(typeof(PersonService.PersonService));
        host.Open();
        Console.WriteLine("Paris PersonService running.");
        Console.ReadLine();
        host.Close();
    }
}

The WCF router must know the location of these services. And by filtering the client request, the router has to
decide which service has to be called. The most things are done in the config file. Read the XML comments.


  
    
      
      
        
          
          
          
        
      
    
    
      
      
        
        
        
      
      
        
        
          
          
        
      
    
    
      
      
        
        
          
            
          
        
      
    
    
    
      
      
    
  

WCF router hosting. The “RoutingService” class is a .NET 4.0 class.

class Program
{
    static void Main(string[] args)
    {
        var host = new ServiceHost(typeof(RoutingService));
        host.Open();
        Console.WriteLine("Routing running.");
        Console.ReadLine();
        host.Close();
    }
}

We have now three services:

Name Function Address
WCF router Routing http://localhost:9000/PersonServiceRouter
London service Data service http://localhost:8000/Personservice
Paris service Data service net.tcp://localhost:8500/Personservice

The client has just to know the WCF router.
This code here, calls the service method “GetPerson” with a filter.
The Property “PersonFilter.Location” is important for the WCF router. The configurated filter (see WCF router config)
checks the value of the “Location” and calls the appropriate service (London or Paris).

class Program
{
    static void Main(string[] args)
    {
        // create proxy object
        var binding = new BasicHttpBinding();
        var endpoint = new EndpointAddress("http://localhost:9000/PersonServiceRouter");
        var proxy = ChannelFactory.CreateChannel(binding, endpoint);

        // Call WCF router with param "london". -> London PersonService is called.
        CallService(proxy, "london");
        // Call WCF router with param "paris". -> Paris PersonService is called.
        CallService(proxy, "paris");

        Console.ReadLine();
    }

    static void CallService(IPersonService proxy, string location)
    {
        Console.WriteLine("-------------------------");
        Console.WriteLine("Service URL: http://localhost:9000/PersonServiceRouter");
        Console.WriteLine("Filter: " + location);

        // Set the person filter
        var filter = new PersonFilter() { Location = location };
        var person = proxy.GetPerson(filter);

        Console.WriteLine("Firstname: {0}, Lastname: {1}", person.Firstname, person.Lastname);
        Console.WriteLine("-------------------------");
        Console.WriteLine(string.Empty);
    }
}

This is it.
WCF router example

And here is a printscreen of my VS.NET solution:
WCF router solution

ASP.NET MVC Razor

The new ASP.NET MVC Razor view engine is pretty cool. :)
Here are some examples:

Namespaces:

@using MyProject.Entities

Define model type:

@using MyProject.Entities
@model User

Create functions:

@functions {
    public string GetSomething(User usr)
    {
        return usr.Name;
    }
}

Templating:

// In your template
<html>
...
@RenderSection("MyContent", true) // true = required
<br />
@RenderSection("MyFooter", false) // false = not required
...
</html>

// In your site
@{
    Layout = "~/Views/Shared/YourTemplate.cshtml";
}

@section MyContent {
   <p>hello!</p>
}
@section MyFooter {
   <p>Footer</p>
}

Output model data:

<table>
  <tr>
    <td>Firstname</td>
    <td>@Model.Firstname</td>
  </tr>
  <tr>
    <td>Lastname</td>
    <td>@Model.Lastname</td>
  </tr>
</table>

Input fields with labels:

<table>
   <tr>
      <td>@Html.LabelFor(m => m.Firstname)</td>
      <td>@Html.TextBoxFor(m => m.Firstname)</td>
   </tr>
   <tr>
      <td>@Html.LabelFor(m => m.Lastname)</td>
      <td>@Html.TextBoxFor(m => m.Lastname)</td>
   </tr>
</table>

This is a very small MVVM tutorial. I used the MVVM Light (Galasoft) framework. I like this framework because, it brings a lot of very useful features.
The idea behind MVVM is to seperate the UI from the code. The most things I like are that your application is testable, “blendable” and you don’t have code in the code-behind file.

MVVM in short:
MVVM in short

Example:
First I create a base class for all models, which implements the interfaces INotifyPropertyChanged and INotifyDataErrorInfo.
I like to keep the Models clean (POCO). Sometimes it’s very difficult. You can implement the INotifyPropertyChanged interface in the ViewModel and wrap the model class. But this will lead to code duplication. That’s why I decided to implement the interfaces in the model in this example.

The base class for all models.

public class ModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
{
    #region Property changed
    public event PropertyChangedEventHandler PropertyChanged;

            protected void NotifyPropertyChanged(string propertyName, Action message)
    {
        if (this.PropertyChanged != null)
        {
            // property changed
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            // send app message (mvvm light toolkit)
            if(message != null)
                message(this.IsValid);
        }
    }
    #endregion

    #region Notify data error
    private Dictionary> _errors = new Dictionary>();
    public event EventHandler ErrorsChanged;

    // get errors by property
    public IEnumerable GetErrors(string propertyName)
    {
        if (this._errors.ContainsKey(propertyName))
            return this._errors[propertyName];
        return null;
    }

    // has errors
    public bool HasErrors
    {
        get { return (this._errors.Count > 0); }
    }

    // object is valid
    public bool IsValid
    {
        get { return !this.HasErrors; }

    }

    public void AddError(string propertyName, string error)
    {
        // Add error to list
        this._errors[propertyName] = new List() { error };
        this.NotifyErrorsChanged(propertyName);
    }

    public void RemoveError(string propertyName)
    {
        // remove error
        if (this._errors.ContainsKey(propertyName))
            this._errors.Remove(propertyName);
        this.NotifyErrorsChanged(propertyName);
    }

    public void NotifyErrorsChanged(string propertyName)
    {
        // Notify
        if (this.ErrorsChanged != null)
            this.ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
    }
    #endregion
}

And here my model.

public class Customer : ModelBase
{
    private string _CustomerId;
    public string CustomerId
    {
        get { return this._CustomerId; }
        set
        {
            if (this._CustomerId != value)
            {
                if (value == "abc")
                    base.AddError("CustomerId", "abc not allowed");
                else
                    base.RemoveError("CustomerId");

                this._CustomerId = value;
                base.NotifyPropertyChanged("CustomerId", new Action((valid) => { AppMessages.CustomerIsValid.Send(valid); }));
            }
        }
    }
    public string Name { get; set; }
}

And here is my ViewModel which represents a customer. This class inherits the base class ViewModelBase of the MVVM Light Toolkit. Beside the base class you will find in the following code snippet a second cool feature of MVVM Light framework.
The constructor registers a message. A message can be sent from everywhere and can be registered everywhere. This is very useful, when you don’t want to couple two classes. For instance class A sends a message and the class B can register the message without knowing the sender. In this example, I use this feature for validation. My Models are sending messages. For instance the customer sends the message “CustomerIsValid”. My ViewModel registers this message and executes the RaisePropertyChanged(“IsValid”) method.
Later you will see, that the “IsValid” property is used in the view. You see know that my Model raises the PropertyChanged event and my ViewModel tool. It is possible to do this only from my Model… or only from my ViewModel. But lets say you have a second Model called “Address” which you want to expose in the same ViewModel. And this Model has to be validated too. In my opinion, it’s easier to send message from the Model and register them in the ViewModel. The ViewModel executes the RaisePropertyChanged method and in the View you have only to bind the IsValid property, which returns true when customer and address are valid.

public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        if (IsInDesignMode)
        {
            // Code runs in Blend --> create design time data.
        }
        else
        {
            // Code runs "for real"
            // Register message. (just run the PropertyChanged function. "arg" isn't important here.)
            AppMessages.CustomerIsValid.Register(this,
                new Action((arg) => { this.RaisePropertyChanged("IsValid"); }));

            this.Customer = new Customer();
        }
    }

    private Customer _customer;
    public Customer Customer
    {
        get { return _customer; }
        set { _customer = value; }
    }

    public bool IsValid
    {
        get { return this.Customer.IsValid; }
    }
}

(Sending/registering message is very easy..)

public class AppMessages
{
    public static class CustomerIsValid
    {
        public static void Send(bool argument)
        {
            Messenger.Default.Send(argument);
        }

        public static void Register(object recipient, Action action)
        {
            Messenger.Default.Register(recipient, action);
        }
    }
}

And last but no least.. the view:
Nothing special here. The DataContext “Locator” is another feature of MVVM Light. It is the entry point for bindings.



    
        
            
            
            
        
    

This is it!
Here are two printscreens.

Form is valid:
MVVM Validation OK

Form is not valid (error popup visible and save button is disabled):
MVVM Validation False

After my last post about .NET – Android, I was pretty excited about the possibilities. Therefore, I decided to create a new little “useful” app for my phone.
If your mouse batteries are low and you have to finish something, you can use your phone as a mouse.

How it works on Android:
I created an app which captures the movements on the screen and sends the positions over a socket (UDP) to my PC. My “protocol” supports following commands:

d.click Sending a double click. (Not really necessary.)
click Sending a click. (2x “click” => same as d.click.)
x,y Sending delta x and y. 0,1 or 1,0 etc.
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    	super.onTouchEvent(event);
    	switch(event.getAction()) {
	    	case MotionEvent.ACTION_DOWN: {
	    		final float x = event.getX();
	    		final float y = event.getY();
	    		// last position
	    		this.lastX = x;
	    		this.lastY = y;
	    		// first position
	    		this.firstX = x;
	    		this.firstY = y;
	    		// click time
	    		this.clickDown = new Date();
	    		break;
	    	}
	    	case MotionEvent.ACTION_MOVE: {
	    		// new position
	    		final float x = event.getX();
	    		final float y = event.getY();

	    		//  get delta
	    		final float deltax = x - this.lastX;
	    		final float deltay = y - this.lastY;
	    		// set last position
	    		this.lastX = x;
	    		this.lastY = y;

				try {
					// prepare message -> x,y
					byte[] message = (deltax + "," + deltay).getBytes("UTF-8");
					// package definition. ip of pc and port.
					this.packet = new DatagramPacket(message, message.length,
							InetAddress.getByName("192.168.0.150"), 8000);
					// send package
					this.socket.send(this.packet);
				} catch(Throwable e) {
					e.printStackTrace();
				}
	    		break;
	    	}

	    	case MotionEvent.ACTION_UP: {
	    		// get current position
	    		final float x = event.getX();
	    		final float y = event.getY();
	    		// get delta
	    		final float deltaX = this.firstX - x;
	    		final float deltaY = this.firstY - y;

	    		Date now = new Date();
	    		byte[] message = null;

	    		try {
	    			// when the users clicks and holds over 1 second send a double click to the pc.
		    		if (deltaX < this.tolerance[0] &&
	    				deltaX > this.tolerance[1] &&
	    				deltaY < this.tolerance[0] &&
	    				deltaY > this.tolerance[1] &&
	    				now.getTime() - this.clickDown.getTime() >= 1000) {
		    			message = ("d.click").getBytes("UTF-8");
	    			// When the users clicks (not holding) send a normal click to the pc.
		    		} else if (x == this.firstX && y == this.firstY) {
		    			message = ("click").getBytes("UTF-8");
		    		}
		    		if (message != null) {
		    			// prepare and send package -> d.click or click
		    			this.packet = new DatagramPacket(message, message.length, InetAddress.getByName("192.168.0.150"), 8000);
						this.socket.send(this.packet);
		    		}
				} catch (Throwable e) {
					e.printStackTrace();
	    		}
	    		break;
	    	}
    	}
    	return true;
    }

Application on the PC:
I created an application, which receives the packages and sets the cursor position on the PC:

public partial class MainWindow : Window
{
    // Dll import. -> method mouse_move
    [DllImport("user32.dll")]
    static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

    private EndPoint point;
    private Socket receiveSocket;
    private byte[] recBuffer;
    private int speed = 2;

    // Flags for mouse_event api
    [Flags]
    public enum MouseEventFlagsAPI
    {
        LEFTDOWN = 0x00000002,
        LEFTUP = 0x00000004,
        MIDDLEDOWN = 0x00000020,
        MIDDLEUP = 0x00000040,
        MOVE = 0x00000001,
        ABSOLUTE = 0x00008000,
        RIGHTDOWN = 0x00000008,
        RIGHTUP = 0x00000010
    }

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // initilization and listening
        receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            point = new IPEndPoint(IPAddress.Any, 8000);
        this.recBuffer = new byte[60];
        receiveSocket.Bind(point);
        receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length,
            SocketFlags.None, ref point,
            new AsyncCallback(MessageReceiveCallback), (object)this);

    }
    private void SendClick()
    {
        // Send click to system
        mouse_event((int)MouseEventFlagsAPI.LEFTDOWN, 0, 0, 0, 0);
        mouse_event((int)MouseEventFlagsAPI.LEFTUP, 0, 0, 0, 0);
    }
    private void MessageReceiveCallback(IAsyncResult result)
    {
        EndPoint remote = new IPEndPoint(0, 0);
        string pos = "";

        try
        {
            // get received message.
            pos = Encoding.UTF8.GetString(recBuffer);

            // clicked?
            if (pos.StartsWith("click"))
                this.SendClick();
            // long click = double click
            else if (pos.StartsWith("d.click"))
            {
                this.SendClick();
                this.SendClick();
            }
            // Otherwise move
            else
            {
                // calculate delta
                int deltaX = (int)float.Parse(pos.Substring(0, pos.IndexOf(","))) * this.speed;
                int deltaY = (int)float.Parse(pos.Substring(pos.IndexOf(",") + 1,
                    pos.IndexOf("\0") + 1 - pos.IndexOf(",") + 1)) * this.speed;

                // set new point
                System.Drawing.Point pt = System.Windows.Forms.Cursor.Position;
                System.Windows.Forms.Cursor.Position = new System.Drawing.Point(pt.X + deltaX, pt.Y + deltaY);
            }
        }
        catch (Exception)
        {
            Console.Write(pos);
        }
        // End and "begin" for next package
        this.receiveSocket.EndReceiveFrom(result, ref remote);
        receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length,
            SocketFlags.None, ref point,
            new AsyncCallback(MessageReceiveCallback), (object)this);
    }
}

Watch the video! ;)

I often use my computer as a music player. But I don’t have a remote controller for it. If I want to change the song, I need to do it on my PC.
That’s not cool. Yesterday I decided to build a remote control app for my Samsung Galaxy S (Android 2.0). This should solve my problem forever and ever.

Here is a picture of my new home “infrastructure”. I’ve removed my confidential information.
;)

Home Infrastructure

Description:

The WPF application parses my MP3 playlist (.m3u file) and shows the songs in a datagrid. I created some basic functions like “play”, “pause” etc. Playing media is done with the “MediaElement”.

The WPF application contains a self-hosted WCF service. This service exposes the media player functions (“play”, “pause” etc.).
I decided to create a REST service, because this is more suitable for the Android development than SOAP webservice.

The Android app is easy. It sends via http get the commands to the WCF REST service. Following requests are accepted:

http://…/ Gets the playlist.
http://…/controller/pause Pause song.
http://…/controller/play Play song.
http://…/songs/{songId} Change song by passing the songId.
http://…/controller/next Play the next song.
http://…/controller/previous Play the previous song.

Here are some key functions. If you need the whole code, please let me know.

Computer music player application (WPF/WCF):

WCF contract for REST service.

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/")]
        Song[] GetPlaylist();

        [OperationContract]
        [WebGet(UriTemplate = "/songs/{songId}")]
        void ChangeSong(string songId);

        [OperationContract]
        [WebGet(UriTemplate = "/controller/pause")]
        void Pause();

        [OperationContract]
        [WebGet(UriTemplate = "/controller/play")]
        void Play();

        [OperationContract]
        [WebGet(UriTemplate = "/controller/next")]
        void Next();

        [OperationContract]
        [WebGet(UriTemplate = "/controller/previous")]
        void Previous();
    }

m3u Parser.

    public class Playlist
    {
        public Songs GetPlaylist(string path)
        {
            if (!path.ToLower().EndsWith(".m3u"))
                throw new ArgumentException("Wrong file. Only *.m3u files accepted.", "path");

            if (!File.Exists(path))
                throw new Exception("File doesn't exists.");

            var songList = new Songs();
            string fileRow;
            int id = 0;
            string title;
            using (var reader = new StreamReader(path, Encoding.Default))
            {
                reader.ReadLine();
                while (!reader.EndOfStream)
                {
                    fileRow = reader.ReadLine();
                    if(fileRow.StartsWith("#"))
                    {
                        if(reader.EndOfStream)
                            throw new Exception(string.Format("m3u file format is wrong. Can't find file for song '{0}'", fileRow));

                        title = fileRow.Substring(fileRow.IndexOf(',')+1);
                        songList.Add(new Song(id++, title, reader.ReadLine()));
                    }
                    else
                        throw new Exception("m3u file format is wrong. Check file.");
                }
            }
            return songList;
        }

        public Songs GetPlaylist()
        {
            return this.GetPlaylist(@"E:\MySongs.m3u");
        }
    }

Android mobile app (Java):

I created a class which handles the REST calls.

public class RESTHandler {

	private DefaultHttpClient request;
	private String uri;
	private HttpGet method;

	public RESTHandler(String baseUri)
			throws URISyntaxException, ClientProtocolException, IOException {
    	this.request = new DefaultHttpClient();
    	this.uri = baseUri;
	}

	public void sendRequest(String action)
			throws URISyntaxException, ClientProtocolException, IOException {
		if(this.method == null)
			this.method = new HttpGet(this.uri);

		this.method.setURI(new URI(this.uri + action));
		this.request.execute(this.method);
	}

	public String getUri() {
		return this.uri;
	}
}

The following actions are performed when opening the app:
- Call REST service and get playlist.
- Parse playlist with SAX.
- Register click event.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
    	// Parse playlist with SAX parser
        URL url = new URL(controller.PlayerUrl + "/");
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		PlaylistHandler handler = new PlaylistHandler();
		URLConnection connect = url.openConnection();
		connect.setConnectTimeout(8000);
		parser.parse(connect.getInputStream(), handler);
		// Get the songs
		final List songs = handler.getSongs();

		// Define the adapter
        ListAdapter adapter = new SongListAdapter(this, songs,
		android.R.layout.simple_list_item_2,
		new String[] { Song.KEY_TITLE},
		new int[] { android.R.id.text2 });
        this.setListAdapter(adapter);

        // Click-handler.
        // Click = change song on pc. -> Send REST call http://..../songs/134
        final ListView.OnItemClickListener onItemClickListener = new  ListView.OnItemClickListener() {
            public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
				try {
					request.sendRequest("/songs/" + songs.get(arg2).Id);
				} catch (Throwable e) {
					e.printStackTrace();
				}
            };
        };

        this.getListView().setOnItemClickListener(onItemClickListener);
    } catch(Throwable e) {
    	e.printStackTrace();
    }
}

The listview is defined in the layout/main.xml file.




Music player functions (play, pause, previous and next) are displayed in the menu.
The menu is defined in menu/main.xml:



	
	
	
	

Initialization of the menu happens in the onCreateOptionsMenu.

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
	   super.onCreateOptionsMenu(menu);
	   new MenuInflater(this.getApplication()).inflate(R.menu.main, menu);
	   return true;
   }

The menu click handler calls the REST service.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
	try {
		String action = "";
		switch(item.getItemId()) {
			case R.id.menuPause: action = "/controller/pause"; break;
			case R.id.menuPlay:  action = "/controller/play"; break;
			case R.id.menuPrevious: action = "/controller/previous"; break;
			case R.id.menuNext: action = "/controller/next"; break;
		}
		if(action.length() > 0)
			this.request.sendRequest(action);
	} catch(Throwable e) {
		e.printStackTrace();
	}
	return true;
}

That’s all. ;)
Here is a short video that I made!