How to set a dto session key when calling WCF proxy

The power of the following method is avoid implementing the WCF contract client in the client side and duplicate the code for each call. Using Reflections and Expression Lambda to handle each message before send it. The follwing code has 3 steps specified by regions :

  • Update the DTO.
  • Initilialize the proxy if the channel is in status Faulted.
  • Invoke the contract operation
public static Task<RequestResponse> SendRequestAsync(Expression<Func<IUiContract, Task<RequestResponse>>> expression)
            #region Set Session Key

            var call = expression.Body as MethodCallExpression;
            if (call != null)
                var argument = call.Arguments[0];
                if (argument != null)
                    LambdaExpression lambda = Expression.Lambda(argument, expression.Parameters);
                    Delegate d = lambda.Compile();
                    var dto = d.DynamicInvoke(new object[1]) as RequestDTO;
                    if (dto != null)
                        dto.SessionKey = ClientSession.GetSessionKey();


            #region Initialize Proxy if Faulted

            // ReSharper disable once PossibleNullReferenceException
            if ((Instance._proxy as ICommunicationObject).State == CommunicationState.Faulted)


            var func = expression.Compile();
            return func.Invoke(Instance._proxy);

Call the method from another class code:

  ServiceClient.SendRequestAsync(contract => contract.AddUserAsync(dto));

Prism: View Model Locator => Custom Convention

I was working on a modular/composite application using Prism and MEF. One of the most issues i encountered, was using the Prism ViewModelLocator to bind the view context to the right view model instance. After googling, I had to write my own convention basing on Prism default convention. the new custom convention allows me to bind view models not necessary having the same namespace as the view namespace. also makes it possible to bind these view models event if are in another separated assembly.


I started by creating an interface named IMvvmTypeLocator :

public interface IMvvmTypeLocator
	/// <summary>
	/// Gets the type of the view model from view type.
	/// </summary>
	/// <param name="viewType">Type of the view.</param>
	/// <returns>The view model type if located; otherwise null</returns>
	Type GetViewModelTypeFromViewType(Type viewType);

The interface above has initially 3 methods, i will focus-on and share only the first one (GetViewModelTypeFromViewType(Type viewType)) to acheive my goal. the 2 other methods are helpful for me to do the same but to locate the view type from a gived view model type or a given view name.

Implement the interface :

I created a class to implement the interface IMvvmTypeLocator, this class has the AggregateCatalog as constructor argument.

Note that we are going to create a custom convention to locate the target view models in all registered assembly catalogs

What the method GetViewModelTypeFromViewType does ?

This method starts by applying the default PRISM convention (GetDefaultViewModelTypeFromViewType method) to locate the target view model, if no view model located, then apply the custom one.

1st step:
  • Get the loaded assemblies from the aggregate catalog:
    • All the assemblies added to the aggregate catalog in the BootStrapper.
2nd step:
  • Locate all non-abstracte classes inheriting from BindableBase class of PRISM (supposed to be a view models).
3rd step:
  • The type name ends with the extension ‘ViewModel’
  • If the view type name ends with the extesnion ‘View’:
    • Locate the type name without the extension ‘ViewModel’ equals to the view type name without the extension ‘View’.
  • If the view type name doesn’t end with the extension ‘View’:
    • Locate the type name without the extension ‘ViewModel’ equals the view type name.


If you added the assembly MyAssembly1.dll (contains the view models inside whatever their namespaces) to the assembly catalog. This custom convention will search inside this assembly for the target view model. If your view named MainView or Main: The convention will look for all the non-abstract classes ineheriting from BindableBase class, and named MainViewModel.


public class MvvmTypeLocator: IMvvmTypeLocator
	/// <summary>
	/// The aggregate catalog
	/// </summary>
	private AggregateCatalog AggregateCatalog { get; set; }

	public MvvmTypeLocator(AggregateCatalog aggregateCatalog)
		this.AggregateCatalog = aggregateCatalog;

	public Type GetViewModelTypeFromViewType(Type sourceType)
		// The default prism view model type resolver as Priority 
		Type targetType = this.GetDefaultViewModelTypeFromViewType(sourceType);
		if (targetType != null)
			return targetType;

		// Get assembly catalogs
		var assemblyCatalogs = this.AggregateCatalog.Catalogs.Where(c => c is AssemblyCatalog);

		// Get all exported types inherit from BindableBase prism class
		var bindableBases =
				c =>
					.Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(BindableBase)))
					.Select(t => t)).SelectMany(b =>
						var types = b as IList<Type> ?? b.ToList();
						return types;

		// Get the type where the delegate is applied
		var customConvention = new Func<Type, bool>(
			(Type t) =>
				const string TargetTypeSuffix = "ViewModel";
				var isTypeWithTargetTypeSuffix = t.Name.EndsWith(TargetTypeSuffix);
				return (isTypeWithTargetTypeSuffix)
					   && ((sourceType.Name.EndsWith("View") && sourceType.Name + "Model" == t.Name)
						   || (sourceType.Name + "ViewModel" == t.Name));

		var resolvedTargetType = bindableBases.FirstOrDefault(customConvention);
		return resolvedTargetType;

	private Type GetDefaultViewModelTypeFromViewType(Type viewType)
		var viewName = viewType.FullName;
		viewName = viewName.Replace(".Views.", ".ViewModels.");
		var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
		var suffix = viewName.EndsWith("View") ? "Model" : "ViewModel";
		var viewModelName = String.Format(
			"{0}{1}, {2}",
		return Type.GetType(viewModelName);

Use the custom convention

To use the custom convention, I created a new instance of IMvvmTypeLocator on the application BootStrapper. then i overrided the method ConfigureViewModelLocator.

1st step:

Create field in the bootstrapper :

private IMvvmTypeLocator mvvmTypeLocator;
2nd step:

Create new instance of the class MvvmTypeLocator once the AggregateCatalog is configured:

 protected override void ConfigureAggregateCatalog()
            this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
			// Here i add the assembly containing all my view models. 
            this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(MainViewModel).Assembly));
			// Create the new instnace of MvvmTypeLocator.
            this.mvvmTypeLocator = new MvvmTypeLocator(this.AggregateCatalog);
3rd step:

Apply the new convention to the ViewModelLocatorProvider:

protected override void ConfigureViewModelLocator()

                viewType => this.mvvmTypeLocator.GetViewModelTypeFromViewType(viewType));

Note that you are responsible of the view model naming, because this convention will allow the view model locator returning the first found occurence, then ensure that this view model type name is unique.

Observable Concurrent Queue


I was working with the classic ConcurrentQueue in .Net, It’s a good practice to schedule tasks execution asynchronously, however, getting notified when my ConcurrentQueue content is changed was the problem! How can i know if an element has been enqueued, peeked or dequeued? Also how can i be notified when the queue is empty after last element has been dequeued?

To solve the problem of notification, i’ve developed my custom ConcurrentQueue named ObservableConcurrentQueue inherit from System.Collections.Concurrent.ConcurrentQueue to raise events once the content is changed.

If you are not familiar with the ConcurrentQueue, Please read more about it on MSDN

Syntax & Example:

var observableConcurrentQueue = new ObservableConcurrentQueue<int>();
observableConcurrentQueue.ContentChanged += OnObservableConcurrentQueueContentChanged;

The handleMethod ContentChanged event looks as the follwoing:

private static void OnObservableConcurrentQueueContentChanged(
            object sender, 
            NotifyConcurrentQueueChangedEventArgs<int> args)
            if (args.Action == NotifyConcurrentQueueChangedAction.Enqueue)
                Console.BackgroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("New Item added: {0}", args.ChangedItem);

            if (args.Action == NotifyConcurrentQueueChangedAction.Dequeue)
                Console.BackgroundColor = ConsoleColor.Red;
                Console.WriteLine("New Item deleted: {0}", args.ChangedItem);

            if (args.Action == NotifyConcurrentQueueChangedAction.Peek)
                Console.BackgroundColor = ConsoleColor.DarkBlue;
                Console.WriteLine("Item peeked: {0}", args.ChangedItem);

            if (args.Action == NotifyConcurrentQueueChangedAction.Empty)
                Console.BackgroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("Queue is empty");


Then, Once the handler is defined, we can start adding, deleting or getting elements from the concurrentQueue, and after each operation an event will be raised and handled by the method above.

Event Args:

The EventArgs object sent by the event contains 2 properties:


  • Enqueue: If a new item has been enqueued.
  • Dequeue: an item has been dequeued.
  • Peek: an item has been peeked.
  • Empty: The last element in the queue has been dequeued and the queue is empty.

T ChangedItem

The item which the changes applied on. can be null if the notification action is NotifyConcurrentQueueChangedAction.Empty.


PM> Install-Package ObservableConcurrentQueue

Termcolor Library

TermColor Is a C library used for ANSII Color formatting for Linux/Mac terminal output.

Termcolor Library


There are two ways to install termcolor.h library:

1. Install into gcc includes folder :

need root permissions

curl | sh 

include it in your code:

#include <termcolor.h>

2. download termcolor.h in your project folder:

get termcolor.h file:

curl -O 

include it in your code then start use the libray :)

#include "termcolor.h"

Termcolor users documentation:

cprint() function facilitates the use of the termcolor library, the programer needs to know just some tags to get a good results. So to get a good results you must be OK to use cprint() instead of printf() :P

  • Example 1:
cprint("${bd}Hello world!${/bd}\n");

In this example, the ${bd} tag tells the program to START showing text in bold and the ${/bd} tag tells the program to STOP showing text in bold.

  • Example 2:
cprint("${ul}Hello world!${/ul}\n");

In the second example, the ${ul} tag tells the program to START underlining text and the ${/ul} tag tells the program to STOP underlining the text.

Easy to use?

The principle of using this function is roughly the principle of html tag, every time you open a tag you must close it after inserting a code. Except it is not quite the same, as you will see in the following examples…


Text decoration

Tag Name: What it does:


Start Bold


Stop Bold


Start Underline


Stop underline


Start blink


Stop blink


Tag name:What it does:


reverse colors


stop reversing colors


use high intensity for background color


stop using high intensity for background color


use high intensity for foreground color


stop using high intensity for foreground color

Foreground and Background colors:
Background color tags:
Tag name:What it does:


Black background


Red background


Green background


Yellow background


Blue background


Magenta background


Cyan background


White background


Stop using background

Foreground color tags:
Tag name:What it does:


Black foreground


Red foreground


Green foreground


Yellow foreground


Blue foreground


Magenta foreground


Cyan foreground


White foreground


Stop using foreground


This function has one BOOLEAN argument, when it take the TRUE variable, you need to restart all effects and decoration you did in the previous cprint(). Otherwise, if you forget to close the tags in the previous cprint() , the next one continue applying all the effects and decorations that you have forgot to close.

  • Example:

  • auto reset :

cprint("${bd}Hello ");

this will display Hello in bold and world in normal weight.

  • don’t auto reset :
cprint("${bd}Hello ");

this will display both Hello and world in bold

cprint() and variables:

Currently, cprint() must exactly take one arguments (char *) takes more than one argument, however it takes only the int %d , char %c and strings char * %s , it may prints anything wrong if you give a long or float argument. in the next versions may be developed to take all the data types possible which is the case of printf() .

So to print a variable of another data type using effects, you must disable auto reset by doing : autoResetStyle(FALSE); then put the printf(args) between tow cprint()s.


long a=10, b=10;
cprint("a = ${bd} }
cprint("${/bd} b= ${bd}");
printf("%ld, b);

Termcolor developers documentation:

Available Colors:



By including termcolor library in your code, you don’t need to include the stdbool library. However you need to write the boolean keywords in uppercase characters: TRUE and FALSE



  • bgColor(COLOR) : set the background color using the available colors.

  • fgColor(COLOR) : set the foreground color using the available colors.

for bgColor(COLOR) and fgColor(COLOR) functions use the variable DEFAULTas parameter to reset the default color:


Text decorations:

  • textBold(BOOLEAN) : enable or disable text bolding for the next output:
  • textBlink(BOOLEAN) : enable or disable text blinking for the next output:
  • colorReverse(BOOLEAN): enable or disable colors reversing for the next output:
  • textUnderline(BOOLEAN): underline text

  • highFgIntensity(BOOLEAN) : Use High Intensity for foreground colors.

  • highBgIntensity(BOOLEAN) : Use High Intensity for background colors.

  • setStyle() : Usually the programer don’t need to invoke this function, it will be invoked automatically by the other functions each time you change the style.

  • resetStyle() : Reset all colors and decorations by default!, i suggest to invoke this function at the end of your main to restore all as default.


Red Background:
printf("text with RED Background");

######Result: termcolor red background -

Default background + Red foreground:
printf("text with RED Foreground");

######Result: termcolor red foreground -

Yellow text on red background:
printf("YELLOW text in RED Background");

######Result: Yellow text on red background -

Yellow Bold text on red background:
printf("YELLOW and BOLD text in RED Background");

######Result: termcolor Yellow Bold text on red background -

Yellow, Bold and underlined text on red background:
printf("YELLOW and BOLD text in RED Background");

######Result: termcolor Yellow, Bold and underlined text on red background -

High Intensity: Yellow Bold text on red background:
printf("YELLOW and BOLD text in RED Background");

######Result: termcolor High Intensity: Yellow Bold text on red background -

Reversed colors:
printf("REVERSED test with default foreground and default background :)");

######Result: termcolor Reversed colors -

Main Example:
#include <stdio.h>
#include "termcolor.h"

int main() {

	printf("Hi, Thanks for trying termcolor library :) \n" );
	printf("Using this library allow the developer to decorate \
the output of its console application.\n\n");
	printf("Some Examples: \n\n");
	bgColor(RED); // Background RED and not "RED" !
	printf("text with RED Background\n\n");
	bgColor(DEFAULT); // Default Background Color
	fgColor(RED); // RED Foreground color 
	printf("text with RED Foreground\n\n");
	printf("YELLOW text in RED Background\n\n");
	textBold(TRUE); // Bold Text
	printf("YELLOW and BOLD text in RED Background\n\n");
	textUnderline(TRUE); // Underlined text 
	printf("YELLOW and BOLD and Underlined text\n\n");
	printf("REVERSED test with default foreground and default background :)\n\n");
	printf("BLINKING text with default foreground and default background\n\n");
	resetStyle(); // Reset all as default 
	printf("Now Examples using High Intensity\n\n");
	printf("text with RED Background\n\n");
	printf("text with RED Foreground\n\n");
	printf("YELLOW text in RED Background\n\n");
	printf("YELLOW and BOLD text in RED Background\n\n");
	printf("Simple Text :D \n\n");
    return 0;

######Result: termcolor Reversed colors -


  • insert horizontal line with specified color.
  • Text align : [Left ; Center ; Right ].
  • Text Border.
  • add availability to cprint() to take more than one argument.

Fork me on GitHub:

I’ll be very happy to take pull requests from others, Go ahead and fork me.

Walletix Python API

A Python API for Walletix online payment service (Closed)

Walletix Java API

Java API for Walletix online payment service (Closed)

alsac Command Line Sound Controller

When i’ve installed ubuntu with openbox window manager, there were no task bars and no menus. that was a problem for me to control the sound using command line.

alsac To solve this i wrote some lines quickly to create a simple and easy command line tool allows me to control sound volume.

alsac works only with alsa devices and tested only on Ubuntu 12.10, based on alsa command and its parmeters.


curl | sh 


$ alsac [-|+] [value]
$ alsac [value] 
$ alsac [mute | unmute]



  • alsac - 10 : decrease sound of 10%

  • alsac + 18 : increase sound of 18%

  • alsac 45 : set sound to 45%

  • alsac mute : mute sound

  • alsac unmute: unmute sound

Github page:

How to use JFileChooser properly

How to use JFileChooser on Java/Swing properly to open/save file -I'm not developing in Java anymore!-

Basicmenu Library

Basicmenu is a an open source library coded in C, allows the programmer to create and display a menu easily in his/her console application on linux and mac os x, works with C/C++ programs.

Screenshoot example:

BasicMenu Library


There is no installation required, you need just to download the basicmenu.h file, include it in your code then start use the libray :)

#include "basicmenu.h"

Essential functions:

To use this library , you have just to learn about some basic functions

1. Start the basic menu library :

First you need to tell the program that uses the library to do this, invoke startBasicMenu() function in the beginning of the main.

2. Create and initialize a new menu:

To create a new menu you need to declare it with its type:

custom_Menu* mymenu; 

To initialize it with the init_new_menu() function:

init_new_menu (&mymenu);
3. Add a new item to the menu:

Any menu, needs to have at least tow items, to add a new item to the menu use the addNewItem() function:

addNewItem (&mymenu , "Choice number one!");
addNewItem (&mymenu , "Choice number tow!");

You can add unlimited number of items, but be careful to don't exceed the console size :)

see the TODO list.

4. Put and display a menu into the program:

To display the menu you need to invoke the put_menu() function. example: Link


  • Allow the programmer to add unlimited items to the menu.
  • Add a scroll menu option.
  • Add the maximum of items to shown on the menu.

for more functions and examples please visit the documentation

Are you a developer? Fork me on GitHub

I'll be very happy to take pull requests from others, Go ahead and fork me.


for code documentation please visit Documentation page

Java Micro Blogging System

Java Micro Blogging System, open source application
Currently allows to create a mini platform for a local social network -Not maintained anymore-.