Index: trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/dialogs/NOT_USED_SelectValueClientOrProviderDialog.java
===================================================================
--- trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/dialogs/NOT_USED_SelectValueClientOrProviderDialog.java	(revision 811)
+++ trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/dialogs/NOT_USED_SelectValueClientOrProviderDialog.java	(revision 811)
@@ -0,0 +1,658 @@
+package org.openmodelica.modelicaml.view.valuebindings.dialogs;
+
+import java.util.HashMap;
+import java.util.List;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.emf.common.command.Command;
+import org.eclipse.emf.common.command.CompoundCommand;
+import org.eclipse.emf.common.util.BasicEList;
+import org.eclipse.emf.common.util.EList;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.impl.DynamicEObjectImpl;
+import org.eclipse.emf.transaction.RecordingCommand;
+import org.eclipse.emf.transaction.TransactionalEditingDomain;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.papyrus.core.utils.BusinessModelResolver;
+import org.eclipse.papyrus.core.utils.EditorUtils;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.uml2.uml.Element;
+import org.eclipse.uml2.uml.NamedElement;
+import org.eclipse.uml2.uml.Property;
+import org.eclipse.uml2.uml.Stereotype;
+import org.eclipse.uml2.uml.Type;
+import org.eclipse.uml2.uml.util.UMLUtil;
+import org.openmodelica.modelicaml.common.constants.Constants;
+import org.openmodelica.modelicaml.common.instantiation.TreeObject;
+import org.openmodelica.modelicaml.common.instantiation.TreeUtls;
+import org.openmodelica.modelicaml.common.utls.SWTResourceManager;
+import org.eclipse.swt.layout.GridData;
+
+public class NOT_USED_SelectValueClientOrProviderDialog extends Dialog {
+	protected Shell sShell; 
+	protected Button bttOK = null;
+	protected Button bttCancel = null;
+
+	private int value = 0;
+	protected Label message;
+	
+	private Group groupSelectedElement;
+	private Label selectedElementIcon;
+	private Label selectedElementIconName;
+	private Group grpValueMediator;
+	private Label lblValueMediatorName;
+	private Label lblValueMediatorIcon;
+	private Group groupElementToBeAdded;
+	private Label lblElementToBeAddedIconName;
+	private Label lblElementToBeAddedIcon;
+	private CCombo comboValueMediator;
+	
+	// Constants 
+	protected static final Image errorIcon = SWTResourceManager.getImage(NOT_USED_SelectValueClientOrProviderDialog.class, "/org/eclipse/jface/dialogs/images/message_error.gif");
+	protected static final Image propertyIcon = SWTResourceManager.getImage(NOT_USED_SelectValueClientOrProviderDialog.class, "/icons/Property.gif");
+	protected static final Image valueMediatorIcon = SWTResourceManager.getImage(NOT_USED_SelectValueClientOrProviderDialog.class, "/icons/valueMediator.png");
+
+	protected EObject selectedElement = null;
+
+//	private List<String> listOfAllowedMetaClassNames = new ArrayList<String>();
+	protected String title = "";
+	protected Image image = null;
+	protected int mode;
+	private TreeViewer viewer;
+	private TreeObject selectedItem;
+	
+	EList<Element> valueMediators = new BasicEList<Element>(); 
+	private EObject selectedValueMediator = null;
+	private HashMap<String,Object> valueMediatorComboSelectionToUMLElementMap = new HashMap<String,Object>(); 
+
+	public final static int MODE_ADD_CLIENT = 0;
+	public final static int MODE_ADD_PROVIDER = 1;
+	
+	private Action actionEditModification;
+	private Action actionLinkWithEditor;
+	
+	private boolean actionLinkWithEditorLastStatus;
+	
+	public NOT_USED_SelectValueClientOrProviderDialog(	Shell parent, 
+									Image image,
+									String title, 
+									String message, 
+									List<String> listOfAllowedMetaClassNames, 
+									TreeObject selectedItem, 
+									TreeViewer viewer, 
+									int mode,
+									Action actionEditModification,
+									Action actionLinkWithEditor) {
+		super(parent);
+
+//		this.listOfAllowedMetaClassNames = listOfAllowedMetaClassNames;
+		
+		this.viewer = viewer;
+		
+		this.actionEditModification = actionEditModification;  // used to start the edit modification dialog after element selection
+		this.actionLinkWithEditor = actionLinkWithEditor;
+		// remember the last status of the action
+		actionLinkWithEditorLastStatus = this.actionLinkWithEditor.isChecked();
+		// uncheck the link with editor action in order to avoid that the components tree changes because while the user selects an element
+		actionLinkWithEditor.setChecked(false);
+		
+		this.selectedItem = selectedItem;
+		if (this.selectedItem != null) {
+			this.selectedElement = selectedItem.getUmlElement();
+		}
+		
+		this.mode = mode;
+		this.title = title;
+		this.image = image;
+		
+		// create shell
+		createSShell();
+		
+		// set the message text
+		this.message.setText(message);
+		
+		// collect data
+		setData();
+		
+		// set labels and icons
+		setTextAndIcons();
+		
+		// add the selection listener
+		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().addSelectionListener(selectionListener);
+
+	}
+	private void setData(){
+		if (selectedElement instanceof Element) {
+			// a provider should be added to added to the client then get the mediators from client
+			if (mode == MODE_ADD_PROVIDER) { 
+//				valueMediators.addAll(TreeUtls.getValueMediators((Element)selectedElement, Constants.stereotypeQName_ValueClient, Constants.stereotypeQName_ValueClient_obtainsValueFrom));
+			}
+			// a client should be added to added to the provider then get the mediators from provider
+			else if (mode == MODE_ADD_CLIENT) {
+//				valueMediators.addAll(TreeUtls.getValueMediators((Element)selectedElement, Constants.stereotypeQName_ValueProvider, Constants.stereotypeQName_ValueProvider_providesValueFor));	
+			}
+			
+			// set the selected valueMediator by default to the first one
+			if (valueMediators.size() > 0 ) {
+				selectedValueMediator = valueMediators.get(0); 
+			}
+		}
+		else {
+			System.err.println("Cannot adopt the selected item to an UML Element");
+		}
+	}
+
+	
+	private void setTextAndIcons(){
+		// set groups
+		if (mode == MODE_ADD_PROVIDER) {
+			groupSelectedElement.setText("Value Client");
+			groupElementToBeAdded.setText("Value Provider");
+		}
+		else if (mode == MODE_ADD_CLIENT) {
+			groupSelectedElement.setText("Value Provider");
+			groupElementToBeAdded.setText("Value Client");
+		}
+		else {
+			groupSelectedElement.setText("???");
+		}
+
+		
+		// set the selected element icon and text. 
+		String nameString;
+		String typeString;
+		String ownerString;
+		
+		nameString = getNameString(selectedItem.getUmlElement());
+		typeString = getTypeString(selectedItem.getUmlElement());
+		ownerString = getOwnerString(selectedItem.getUmlElement());
+		selectedElementIconName.setText( getNameString(nameString, typeString, ownerString) );
+		selectedElementIcon.setImage( getValueClientOrProviderIcon() );
+		
+		// value mediator icon
+		if (valueMediators.size() > 0 ) { // there must be a mediator for the selected element 
+			if (valueMediators.size() > 1 ) {
+				
+				// hide the lable
+				lblValueMediatorName.setVisible(false);
+				
+				// set the combo items
+				EList<String> valueMediatorItems = new BasicEList<String>();
+				for (int i = 0; i < valueMediators.size(); i++) {
+					Element element = valueMediators.get(i);
+					if (element instanceof NamedElement) {
+						
+						nameString = getNameString(element);
+						typeString = getTypeString(element);
+						ownerString = getOwnerString(element);
+						
+						String key = getNameString(nameString, typeString, ownerString);
+						valueMediatorItems.add(key);
+						valueMediatorComboSelectionToUMLElementMap.put(key, element);
+					}
+				}
+				comboValueMediator.setItems(valueMediatorItems.toArray(new String[valueMediators.size()]));
+				comboValueMediator.setText(comboValueMediator.getItems()[0]);
+				
+			}
+			else{
+				Element firstMediator = valueMediators.get(0);
+				selectedValueMediator = firstMediator;
+				if (firstMediator instanceof NamedElement) {
+					
+					// get type and owner 
+					nameString = getNameString(firstMediator);
+					typeString = getTypeString(firstMediator);
+					ownerString = getOwnerString(firstMediator);
+					lblValueMediatorName.setText(getNameString( nameString, typeString, ownerString));
+				}
+				
+				// hide the combo 
+				comboValueMediator.setVisible(false);
+			}
+			lblValueMediatorIcon.setImage(valueMediatorIcon);
+		}
+		
+		// set default values for element selection
+		lblElementToBeAddedIconName.setText("Click on a model element ...");
+		lblElementToBeAddedIcon.setImage(errorIcon);
+
+	}
+	
+	
+	
+	/**
+	 * This method initializes sShell
+	 */
+	private void createSShell() {
+		// SWT.APPLICATION_MODAL, SWT.SYSTEM_MODAL do not work, 
+		// SWT.PRIMARY_MODAL, SWT.MODELESS work
+		sShell = new Shell(getParentShell(), SWT.DIALOG_TRIM | SWT.PRIMARY_MODAL | SWT.ON_TOP | SWT.SHELL_TRIM);
+		
+		sShell.setText(this.title);
+		sShell.setImage(this.image); 
+		
+//		sShell.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
+		sShell.setSize(543, 295);
+		sShell.addDisposeListener(new DisposeListener() {
+			@Override
+			public void widgetDisposed(DisposeEvent e) {
+				PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().removeSelectionListener(selectionListener);
+			}
+		});
+		GridLayout gl_sShell_1 = new GridLayout(1, false);
+		gl_sShell_1.marginHeight = 0;
+		gl_sShell_1.marginWidth = 0;
+		sShell.setLayout(gl_sShell_1);
+
+		Composite messageBg = new Composite(sShell, SWT.NONE);
+		GridData gd_messageBg = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
+		gd_messageBg.heightHint = 35;
+		gd_messageBg.widthHint = 537;
+		messageBg.setLayoutData(gd_messageBg);
+		messageBg.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
+		messageBg.setBounds(0, 0, 537, 34);
+		
+		message = new Label(messageBg, SWT.NONE);
+		message.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
+		message.setBounds(10, 10, 511, 13);
+		message.setText("Click on the element to be associated.");
+		
+		Composite groupsComposite = new Composite(sShell, SWT.NONE);
+		groupsComposite.setLayout(new GridLayout(1, false));
+		groupsComposite.setBounds(0, 35, 544, 274);
+		
+		groupSelectedElement = new Group(groupsComposite, SWT.NONE);
+		groupSelectedElement.setText("Value Client or Provider");
+		
+		selectedElementIconName = new Label(groupSelectedElement, SWT.NONE);
+		selectedElementIconName.setText("asdfasdf");
+		selectedElementIconName.setBounds(32, 23, 486, 13);
+		
+		selectedElementIcon = new Label(groupSelectedElement, SWT.NONE);
+//		selectedElementIcon.setImage(SWTResourceManager.getImage(ValueClientOrProviderSelectionDialog.class, "/icons/full/etool16/delete.gif"));
+		selectedElementIcon.setBounds(10, 23, 16, 16);
+		
+		grpValueMediator = new Group(groupsComposite, SWT.NONE);
+		grpValueMediator.setText("Value Mediator");
+		
+		lblValueMediatorName = new Label(grpValueMediator, SWT.NONE);
+		lblValueMediatorName.setBounds(32, 23, 486, 13);
+		lblValueMediatorName.setText("asdfasdf");
+		
+		lblValueMediatorIcon = new Label(grpValueMediator, SWT.NONE);
+		lblValueMediatorIcon.setBounds(10, 23, 16, 16);
+		
+		comboValueMediator = new CCombo(grpValueMediator, SWT.NONE);
+		comboValueMediator.setEditable(false);
+		comboValueMediator.setBackground(new Color(null, new RGB(255,255,255)));
+		comboValueMediator.setBounds(32, 20, 486, 20);
+		
+		groupElementToBeAdded = new Group(groupsComposite, SWT.NONE);
+		groupElementToBeAdded.setText("Value Client or Provider");
+		
+		lblElementToBeAddedIconName = new Label(groupElementToBeAdded, SWT.NONE);
+		lblElementToBeAddedIconName.setText("asdfasdf");
+		lblElementToBeAddedIconName.setBounds(32, 23, 486, 13);
+		
+		lblElementToBeAddedIcon = new Label(groupElementToBeAdded, SWT.NONE);
+//		lblElementToBeAddedIcon.setImage(SWTResourceManager.getImage(ValueClientOrProviderSelectionDialog.class, "/icons/full/etool16/delete.gif"));
+		lblElementToBeAddedIcon.setBounds(10, 23, 16, 16);
+
+		comboValueMediator.addSelectionListener(new SelectionAdapter() {
+			@Override
+			public void widgetSelected(SelectionEvent e) {
+				int index = comboValueMediator.getSelectionIndex();
+				String key = comboValueMediator.getItem(index);
+				selectedValueMediator = (EObject) valueMediatorComboSelectionToUMLElementMap.get(key);
+			}
+		});
+		
+		Composite composite = new Composite(sShell, SWT.NONE);
+		GridData gd_composite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
+		gd_composite.widthHint = 533;
+		composite.setLayoutData(gd_composite);
+		
+		bttOK = new Button(composite, SWT.NONE);
+		bttOK.setBounds(388, 0, 71, 23);
+		bttOK.setText("OK");
+		
+		bttCancel = new Button(composite, SWT.NONE);
+		bttCancel.setBounds(467, 0, 66, 23);
+		bttCancel.setText("Cancel");
+		bttCancel.addMouseListener(new org.eclipse.swt.events.MouseAdapter() {
+			public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
+
+				setValue(SWT.CANCEL);
+				
+//				sShell.dispose();
+				close(sShell);
+				
+				viewer.setSelection(new StructuredSelection(selectedItem));
+				
+			}
+		});
+		
+		bttOK.addMouseListener(new org.eclipse.swt.events.MouseAdapter() {
+			public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
+				
+				setValue(SWT.OK);
+				
+				if (elementToBeSet instanceof NamedElement) {
+					addValueToStereotypeProperty_List();
+				}
+//				sShell.dispose();
+				close(sShell);
+				
+//				viewer.refresh();
+//				viewer.expandToLevel(2);
+
+				// set selection and open Edit modification dialog
+				if (mode == MODE_ADD_PROVIDER) {
+					// check if the selection was successful and open the edit modification dialog
+					ISelection selection = viewer.getSelection();
+					Object obj = ((IStructuredSelection) selection).getFirstElement();
+					if (obj instanceof TreeObject) {
+						TreeObject item = (TreeObject)obj;
+						if (item == selectedItem) {
+							actionEditModification.run();
+						}
+					}
+				}
+			}
+		});
+		
+	}
+	
+	
+	private void close(Shell shell){
+		shell.dispose();
+
+		// set the last status of the action
+		actionLinkWithEditor.setChecked(actionLinkWithEditorLastStatus);
+		
+		// set the selection to the item that was selected in the beginning  
+		viewer.setSelection(new StructuredSelection(selectedItem));
+		
+	}
+	
+	private Image getValueClientOrProviderIcon(){
+		if (mode == MODE_ADD_CLIENT) {
+			return SWTResourceManager.getImage(NOT_USED_SelectValueClientOrProviderDialog.class, "/icons/addValueClient.png");
+		}
+		if (mode == MODE_ADD_PROVIDER) {
+			return SWTResourceManager.getImage(NOT_USED_SelectValueClientOrProviderDialog.class, "/icons/addValueProviders.png");
+		}
+		return null;
+	}
+	
+	
+	protected ISelectionListener selectionListener = new ISelectionListener() {
+	        public void selectionChanged(IWorkbenchPart sourcepart, ISelection selection) {
+	        if (sourcepart != NOT_USED_SelectValueClientOrProviderDialog.this &&
+	            selection instanceof IStructuredSelection) {
+	
+	        	if (getCurrentSelections() != null && getCurrentSelections().size() > 0 ) {
+	        		elementToBeSet = (EObject) adaptSelectedElement(getCurrentSelections().get(0));
+				}
+	        	
+				if (	elementToBeSet instanceof Property
+						&& ((Property)elementToBeSet).getAppliedStereotype(Constants.stereotypeQName_ValueMediator) == null
+						&& elementToBeSet != selectedElement
+						) {
+
+					String nameString  = getNameString((Element) elementToBeSet);
+					String typeString = getTypeString((Element) elementToBeSet);
+					String ownerString = getOwnerString((Element) elementToBeSet);
+					lblElementToBeAddedIconName.setText( getNameString(nameString, typeString, ownerString) );
+					lblElementToBeAddedIcon.setImage(propertyIcon);
+
+					// enable the OK button
+					bttOK.setEnabled(true);
+					
+				} else {
+					// reset  
+					lblElementToBeAddedIconName.setText("");
+					lblElementToBeAddedIcon.setImage(errorIcon);
+					
+					if (elementToBeSet == selectedElement) { // link to its self
+						String text = "It is not allowed to link an element with itself.";
+						lblElementToBeAddedIconName.setText(text);
+					}
+					else if ( elementToBeSet instanceof Property
+							&& ((Property)elementToBeSet).getAppliedStereotype(Constants.stereotypeQName_ValueMediator) != null){
+						String text = "It is not allowed to link a Value Mediator to another Value Mediator.";
+						lblElementToBeAddedIconName.setText(text);
+					}
+					else if (elementToBeSet != null) {
+						String text = elementToBeSet.eClass().getName() + " is not allowed!";
+						lblElementToBeAddedIconName.setText(text);
+					}
+					else {
+						String text = "Not a valid selection";
+						lblElementToBeAddedIconName.setText(text);
+					}
+
+					// disable the OK button
+					bttOK.setEnabled(false);
+				}
+	        }
+	    }
+	};
+	private EObject elementToBeSet;
+	
+	private Stereotype getStereotype(){
+		String stereotypeQName = "";
+		Stereotype stereotype = null;
+		
+		if (this.mode == MODE_ADD_CLIENT) {
+			stereotypeQName = Constants.stereotypeQName_ValueClient;
+		}
+		else if (this.mode == MODE_ADD_PROVIDER) {
+			stereotypeQName = Constants.stereotypeQName_ValueProvider;
+		}
+		
+		if (this.elementToBeSet instanceof NamedElement) {
+			// get stereotype
+			stereotype = ((NamedElement)this.elementToBeSet).getAppliedStereotype(stereotypeQName);
+			
+			// apply stereotype if not yet applied
+			if (stereotype == null) {
+				final Stereotype s = ((NamedElement)this.elementToBeSet).getApplicableStereotype(stereotypeQName);
+				if (s != null) {
+					
+					//########## storing start
+					TransactionalEditingDomain editingDomain = EditorUtils.getTransactionalEditingDomain();
+					CompoundCommand cc = new CompoundCommand();
+					Command command = new RecordingCommand(editingDomain) {
+						@Override
+						protected void doExecute() {
+							((NamedElement)elementToBeSet).applyStereotype(s);
+						}
+					};
+					cc.append(command);
+					editingDomain.getCommandStack().execute(cc);
+					
+					
+					// get stereotype
+					stereotype = ((NamedElement)this.elementToBeSet).getAppliedStereotype(stereotypeQName); 
+				}
+			}
+		}
+		return stereotype;
+	}
+
+	private String getStereotypePropertyName(){
+		String stereotypeProperty_name = null;
+		if (this.mode == MODE_ADD_CLIENT) {
+			stereotypeProperty_name = Constants.stereotypeQName_ValueClient_obtainsValueFrom;
+		}
+		else if (this.mode == MODE_ADD_PROVIDER) {
+			stereotypeProperty_name = Constants.stereotypeQName_ValueProvider_providesValueFor;
+		}
+		return stereotypeProperty_name;
+	}
+	
+	@SuppressWarnings("rawtypes")
+	private boolean containsObject(EList list, EObject eObject){
+		if (list instanceof EList) {
+			for (Object object : (EList)list) {
+				if (object instanceof EObject) {
+//					if (((EObject)object).eCrossReferences().get(0) == eObject) {
+					if (UMLUtil.getBaseElement((EObject)object) == eObject) {
+						return true;
+					}
+				}	
+			}
+		}
+		return false;
+	}
+	
+	void addValueToStereotypeProperty_List(){
+		
+		if (this.selectedValueMediator != null && this.elementToBeSet instanceof NamedElement) {
+			// get stereotype
+			final Stereotype stereotype = getStereotype();
+			final String stereotypeProperty_name = getStereotypePropertyName();
+			if ( stereotype != null && stereotypeProperty_name != null) {
+				
+				final Object list = ((NamedElement)this.elementToBeSet).getValue(stereotype, stereotypeProperty_name);
+				
+				if (list instanceof EList) {
+//					########## storing start
+					TransactionalEditingDomain editingDomain = EditorUtils.getTransactionalEditingDomain();
+					CompoundCommand cc = new CompoundCommand("Add value mediator reference");
+					Command command = new RecordingCommand(editingDomain) {
+						@SuppressWarnings({ "unchecked", "rawtypes" })
+						@Override
+						protected void doExecute() {
+							if (!containsObject((EList) list, selectedValueMediator)) {
+								
+								// get the value mediator stereotype
+								Stereotype valueMediatorStereotype = ((Element)selectedValueMediator).getAppliedStereotype(Constants.stereotypeQName_ValueMediator);
+								
+								// Important: use the getStereotypeApplication to get an EObject! 
+								DynamicEObjectImpl eObject =(DynamicEObjectImpl) ((Element)selectedValueMediator).getStereotypeApplication(valueMediatorStereotype);
+								
+								// add value to the list
+								((EList)list).add(eObject);
+							}
+						}
+					};
+					cc.append(command);
+					editingDomain.getCommandStack().execute(cc);
+				}
+			}
+		}
+		else {
+			MessageDialog.openError(new Shell(), "Error", "Could not finish the operation. No updates were performed.");
+		}
+	}
+	
+	
+	
+	public int open() {
+		this.sShell.open();
+		return getValue();
+	}
+
+	
+	@SuppressWarnings("unchecked")
+	private List<Object> getCurrentSelections() {
+		ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
+		if(selection instanceof IStructuredSelection) {
+			IStructuredSelection structuredSelection = (IStructuredSelection)selection;
+			return structuredSelection.toList();
+		}
+		return null;
+	}
+	
+	
+	protected EObject adaptSelectedElement( Object selection) {
+		EObject eObject = null;
+		if(selection != null) {
+			
+			if (selection instanceof org.openmodelica.modelicaml.common.instantiation.TreeParent) { // this is an object from components tree view plugin
+				return ((org.openmodelica.modelicaml.common.instantiation.TreeParent)selection).getProperty();
+			}
+			
+			if(selection instanceof IAdaptable) {
+				selection = ((IAdaptable)selection).getAdapter(EObject.class);
+			}
+			Object businessObject = BusinessModelResolver.getInstance().getBusinessModel(selection);
+			if(businessObject instanceof EObject) {
+				eObject = (EObject)businessObject;
+			}
+		}
+		return eObject;
+	}
+	
+	public int getValue() {
+		return value;
+	}
+
+	public void setValue(int value) {
+		this.value = value;
+	}
+	
+	public EObject getSelectedElement() {
+		return selectedElement;
+	}
+
+	public void setSelectedElement(EObject selectedElement) {
+		this.selectedElement = selectedElement;
+	}
+	
+	private String getNameString(String nameString, String typeString, String ownerString) {
+		return nameString + "   -   " + typeString + ", " + ownerString;
+	}
+	
+	private String getTypeString(Element element){
+		if (element instanceof Property) {
+			Type pType = ((Property)element).getType();
+			if (pType != null) {
+				return "type(" + pType.getName().replaceFirst("Modelica", "") + ")";
+			} 
+		}
+		return "ERROR: No type is defined!";
+	}
+	
+	private String getNameString(Element element){
+		if (element instanceof NamedElement) {
+			return  ((NamedElement)element ).getName();
+		} 
+		return "";
+	}
+	
+	private String getOwnerString(Element element){
+		Element owner = element.getOwner();
+		if (owner instanceof NamedElement) {
+				return  "owner(" + ((NamedElement)owner).getName() + ")";
+		} 
+		return "";
+	}
+}
Index: trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/dialogs/SelectValueProviderDialog.java
===================================================================
--- trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/dialogs/SelectValueProviderDialog.java	(revision 807)
+++ trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/dialogs/SelectValueProviderDialog.java	(revision 811)
@@ -32,25 +32,45 @@
 import org.openmodelica.modelicaml.view.valuebindings.helpers.ValueBindingsDataCollector;
 import org.openmodelica.modelicaml.view.valuebindings.model.TreeUtls;
-import org.eclipse.swt.widgets.Label;
 
 public class SelectValueProviderDialog extends Dialog {
 
 	private String title;
-	private List<TreeObject> elementsForSelection;
-	
-	private Element mediatorElement;
-	private String toolTipTextValueMediator;
-	
 	private String groupTitle;
 	private String messageText;
-	
+
+	
+	// providers list
+	private List<TreeObject> elementsForSelection;
+	
+	// the mediator
+	private Element mediatorElement;
+	
+	// deduced client instantiation tree item
+	private TreeObject clientTreeObject; 
+	
+	// data collection for getting information about the mediator and providers 
 	private ValueBindingsDataCollector dataCollection;
 	
-	private TreeObject selectedElement = null;
+	// provider selected by the user
+	private TreeObject selectedProvider = null;
+
+	// preferred providers option
+	private boolean addToPrefferedProviders = false;
+	private String selectedProviderPath = "";
+	
+	private String preferredProvidersSelectionOptionToolTipText = "This action will remember " +
+					"your selection decision by storing the client and selected provider pair as follows:";
+
+	private String preferredProvidersSelectionOptionToolTipTextExplanation = 
+			"\nThis information will be used to pre-select providers in this diaolog. " +
+			"\nMoreover, the 'Update binding' feature will use this information to " +
+			"\nautomatically select one provider if there are multiple.";
+
+	
 	
 	public SelectValueProviderDialog(Shell parentShell, 
 			String title, 
+			TreeObject clientTreeObject,
 			Element mediatorElement,
-			String toolTipTextValueMediator,
 			String groupTitle,
 			String messageText,
@@ -62,6 +82,7 @@
 		
 		this.title = title;
+		this.clientTreeObject = clientTreeObject;
 		this.mediatorElement = mediatorElement;
-		this.toolTipTextValueMediator = toolTipTextValueMediator;
+//		this.toolTipTextValueMediator = toolTipTextValueMediator;
 		this.groupTitle = groupTitle;
 		this.messageText = messageText;
@@ -152,6 +173,10 @@
 		
 		final Button btnAddtoPreferredProviders = new Button(composite, SWT.CHECK);
-		btnAddtoPreferredProviders.setToolTipText("This action will remember the selection decision by storing the qualified names pair of the client and the selected provider.");
-		btnAddtoPreferredProviders.setText("remember this selction (i.e., add to preferred providers)");
+		btnAddtoPreferredProviders.setEnabled(false);
+		btnAddtoPreferredProviders.setToolTipText("This action will remember " +
+				"the selection decision by storing the client and the selected provider pair as follows:" +
+				"\n" + clientTreeObject.getDotPath() + " --> " +  selectedProviderPath
+				+ "\n");
+		btnAddtoPreferredProviders.setText("Remember this selection (i.e., add to preferred providers)");
 		
 		btnAddtoPreferredProviders.addSelectionListener(new SelectionListener() {
@@ -171,4 +196,6 @@
 			}
 		});
+		
+		EList<String> preferredProviders = TreeUtls.getStringListPropertyFromElement(mediatorElement, Constants.stereotypeQName_ValueMediator, Constants.propertyName_preferredProviders);
 		
 		for (TreeObject provider : elementsForSelection) {
@@ -217,14 +244,22 @@
 				rb.setText(provider.getDotPath());
 				rb.setData(provider);
+				
+				
+				// preselect the radio button if this provider is a preferred provider for the client.
+				if (TreeUtls.isPreferredProviderForClient(preferredProviders, clientTreeObject.getDotPath(), provider.getDotPath())) {
+					rb.setSelection(true);
+					setSelectedElement(provider);
+				}
+				
 				rb.addSelectionListener(new SelectionListener() {
 					
 					@Override
 					public void widgetSelected(SelectionEvent e) {
-						setSelectedElement((TreeObject) rb.getData());
+						providerSelectionAction((TreeObject) rb.getData(), btnAddtoPreferredProviders);
 					}
 					
 					@Override
 					public void widgetDefaultSelected(SelectionEvent e) {
-						setSelectedElement((TreeObject) rb.getData());
+						providerSelectionAction((TreeObject) rb.getData(), btnAddtoPreferredProviders);
 					}
 				});
@@ -236,12 +271,35 @@
 
 	
-	private boolean addToPrefferedProviders = false;
+	private void providerSelectionAction(TreeObject selectedProvider, Button btnAddtoPreferredProviders){
+		
+		// set the selected provider
+		setSelectedElement(selectedProvider);
+		
+		//enable the remember button and set its tool tip text
+		if (getSelectedElement() != null) {
+			btnAddtoPreferredProviders.setEnabled(true);
+			selectedProviderPath = getSelectedElement().getDotPath();
+			btnAddtoPreferredProviders.setToolTipText(preferredProvidersSelectionOptionToolTipText 
+					+ "\n\n" + TreeUtls.getPreferredProviderAssignmentString(clientTreeObject.getDotPath(), selectedProviderPath) + "\n"
+					+ preferredProvidersSelectionOptionToolTipTextExplanation + "\n");
+			
+		}
+		// disable the remember button and set its tool tip text
+		else {
+			btnAddtoPreferredProviders.setEnabled(false);
+			selectedProviderPath = "";
+			btnAddtoPreferredProviders.setToolTipText(preferredProvidersSelectionOptionToolTipText
+					+ "\n\n" + TreeUtls.getPreferredProviderAssignmentString(clientTreeObject.getDotPath(), selectedProviderPath) + "\n"
+					+ preferredProvidersSelectionOptionToolTipTextExplanation + "\n");
+		}
+	}
+	
 	
 	public void setSelectedElement(TreeObject selectedElement) {
-		this.selectedElement = selectedElement;
+		this.selectedProvider = selectedElement;
 	}
 
 	public TreeObject getSelectedElement() {
-		return selectedElement;
+		return selectedProvider;
 	}
 
Index: trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/filters/PropertySectionFilter_MediatorPreferredProviders.java
===================================================================
--- trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/filters/PropertySectionFilter_MediatorPreferredProviders.java	(revision 811)
+++ trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/filters/PropertySectionFilter_MediatorPreferredProviders.java	(revision 811)
@@ -0,0 +1,22 @@
+package org.openmodelica.modelicaml.view.valuebindings.filters;
+import org.eclipse.jface.viewers.IFilter;
+import org.openmodelica.modelicaml.common.constants.Constants;
+import org.openmodelica.modelicaml.view.valuebindings.model.TreeObject;
+import org.openmodelica.modelicaml.view.valuebindings.model.TreeUtls;
+
+
+public class PropertySectionFilter_MediatorPreferredProviders implements IFilter {
+
+	@Override
+	public boolean select(Object toTest) {
+		if (toTest instanceof TreeObject) {
+			TreeObject item = (TreeObject)toTest;
+			if (item.isValueMediator() && !item.isReadOnly()) {
+				if (TreeUtls.getStringListPropertyFromElement(item.getUmlElement(), Constants.stereotypeQName_ValueMediator, Constants.propertyName_preferredProviders) != null) {
+					return true;
+				}
+			}
+		}
+		return false;
+	}
+}
Index: trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/helpers/DeriveValueBindingCodeHelper.java
===================================================================
--- trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/helpers/DeriveValueBindingCodeHelper.java	(revision 807)
+++ trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/helpers/DeriveValueBindingCodeHelper.java	(revision 811)
@@ -49,4 +49,6 @@
 	private String errorString = null; // result of validation
 	private Boolean errorsDetected = false; // indicates if an error was detected.
+	
+	private Boolean userSelectionRequired = false; // indicates if an error was detected.
 
 	
@@ -112,5 +114,5 @@
 	
 	
-	public void deriveBindingCodeForClient(TreeObject selectedTreeItem, boolean isUserGuided){
+	public void deriveBindingCodeForClient(TreeObject selectedTreeItem, boolean isUserGuided, boolean isAutomaticSelectionOfPreferredProvidersEnabled){
 
 		// clear all in order to delete data from the previous call
@@ -143,5 +145,5 @@
 				
 					// find providers
-					findProviders(mediatorElement, isUserGuided);
+					findProviders(mediatorElement, isUserGuided, isAutomaticSelectionOfPreferredProvidersEnabled);
 					if ( (mediatorOperation != null && !DeriveValueBindingCodeUtls.hasMediatorBindingScriptFunctions(mediatorOperation)) 
 							|| (providers != null && providers.size() > 0)) {
@@ -296,5 +298,5 @@
 	}
 	
-	public void findProviders(Element mediator, boolean isUserGuided){
+	public void findProviders(Element mediator, boolean isUserGuided, boolean isAutomaticSelectionOfPreferredProvidersEnabled){
 		// clear the list
 		providersForSelection.clear();
@@ -321,23 +323,34 @@
 			}
 			else if ( providerInstances.size() > 1 ) {
-				// if the operation is compatible then add all providers
+				
+				// if the operation handles multiple providers then add all providers to the final list
 				if (DeriveValueBindingCodeUtls.isValidMediatorMultipleItemsScript(mediatorOperation)) {
 					providers.addAll(providerInstances);
 				}
-				else { // Select provider
+				else { // Provider selection: User selection or automatic selection
+					
+					// indicate that a manual selection should be done by the user
+					setUserSelectionRequired(true);
+					
 					// Catch the fact that there were multiple providers that were used for user selection
 					providersForSelection.addAll(providerInstances);
+					
+					//***** USER Selection
 					if (isUserGuided) {
 						String title = "Value Provider Selection";
-						String toolTipTextSourceTreeItem = "Element: " + ((NamedElement)mediatorElement).getQualifiedName();
 						String messageText = "There are multiple providers for the mediator and no operation is defined to handle multiple items. " +
 								"\nYou can select one provider that should be used to derive the code for the selected Value Mediator. " +
 								"\r\nNote, you can hover the elements to get more information. \r\n";
+
 						String groupTitle = "Value Providers";
 						
-						SelectValueProviderDialog dialog = new SelectValueProviderDialog(new Shell(), 
-								title, mediatorElement, 
-								toolTipTextSourceTreeItem, 
-								groupTitle, messageText, 
+						SelectValueProviderDialog dialog = new SelectValueProviderDialog(
+								new Shell(), 
+								title, 
+								clientTreeItem,
+								mediatorElement,
+//								toolTipTextSourceTreeItem, 
+								groupTitle, 
+								messageText, 
 								getSortedList(providerInstances),
 								dataCollection); 
@@ -359,6 +372,15 @@
 						}
 					}
-				}
-			}
+					
+					// *** AUTOMATIC Selection based on preferred providers
+					// if there is a preferred provider -> select it automatically
+					else if (isAutomaticSelectionOfPreferredProvidersEnabled) {
+						if (clientTreeItem != null && TreeUtls.getPreferredProviderForClient(mediator, providerInstances, clientTreeItem.getDotPath()) != null) {
+							providers.add(TreeUtls.getPreferredProviderForClient(mediator, providerInstances, clientTreeItem.getDotPath()));
+						}
+					}
+				}
+			}
+			// no providers were found
 			else {
 				String mediatorQName = ((NamedElement)mediator).getQualifiedName();
@@ -373,10 +395,5 @@
 	private void storePreferredProvider(Element mediator, TreeObject client, TreeObject provider) {
 		if (mediator != null && client != null && provider != null) {
-			String pair = client.getDotPath() + " = " + provider.getDotPath();
-			System.err.println("add to preferredProviders: " + pair);
-			// TODO: get the preferredProviders from the mediator
-			// if there exists a pair that starts witht the client.dotPath -> remove it from the list
-			// add the new pair to the list
-			// sore the new list in mediator preferredProviders 
+			boolean result = TreeUtls.addToPreferredProvider(mediator, client.getDotPath(), provider.getDotPath());
 		}
 		else {
@@ -408,10 +425,10 @@
 //		}
 		
-		// if a search for the client was done before and there is an upper level client found that has references to the mediators
-		// -> use this list of mediators
+		// if a search for the client was done before and there is an upper level client was found that has references to the mediators
+		// -> use this list of mediators, otherwise get the mediators from the client UML element.
 		if (mediatorsContainingClientOperationScript.size() == 0) { 
 			mediatorsForClient = dataCollection.getClientToMediators().get(client);
 		}
-		else { // get the mediators from the client
+		else { 
 			mediatorsForClient = mediatorsContainingClientOperationScript;
 		}
@@ -425,5 +442,5 @@
 					
 					// NOTE: 	Reducing the mediator selection by checking the type compatibility is 
-					// 			NOT useful because type checking needs expression evaluation.
+					// 			NOT useful because type checking needs expression evaluation which is hard to do at ModelicaML level.
 
 					// TODO: Implement check for variability compatibility between client and mediator?
@@ -480,4 +497,5 @@
 					}
 					
+					// NOTE: the code below is not useful because there it may be on purpose in order to let the user select.
 //					// if there are more then 1 provider instances 
 //					// -> select the mediator if it has binding operation functions to handle multiple providers.
@@ -504,9 +522,13 @@
 		}
 		
-		// Store the information when there are multiple mediators. This not used in this class but by other ...
-		mediatorsForSelection.addAll(mediators);
 		
 		if (mediators.size() > 1 ) { // too many -> let the user select
 
+			// indicate that a manual selection should be done by the user
+			setUserSelectionRequired(true);
+
+			// Store the information when there are multiple mediators. This not used in this class but by other ...
+			mediatorsForSelection.addAll(mediators);
+			
 			String clientName = ((NamedElement)client).getQualifiedName();
 			String message = "NOT VALID: Multiple mediators ("+ getItemsAsStringList(new BasicEList<Element>(mediators))+") are found for the client '"+clientName+"'." +
@@ -515,4 +537,5 @@
 			addToLog(message);
 			
+			//*** USER Selection
 			if (isUserGuided) {
 				
@@ -545,4 +568,6 @@
 				}
 			}
+			// TODO: is a preferred mediators feature sensible, similar to preferred providres? 
+			// The qualified name of the mediator UML property could be used for storing the user selections for clients.  
 		}
 		else if (mediators.size() == 1) { // ok, set the mediator element and its operation
@@ -783,5 +808,5 @@
 		}
 		
-		String message = "EMPTY: No Value Mediators were found for the Value Client '" + clientName + "'."; 
+		String message = "EMPTY: No Value Mediators were found or selected for the Value Client '" + clientName + "'."; 
 		setError(message);
 		addToLog(message);
@@ -798,5 +823,5 @@
 		}
 		
-		String message = "EMPTY: No Value Providers were found for the Value Mediator '" + mediatorName + "'."; 
+		String message = "EMPTY: No Value Providers were found or selected for the Value Mediator '" + mediatorName + "'."; 
 		setError(message);
 //		addToLog(message);
@@ -914,4 +939,14 @@
 		return string;
 	}
+
+
+	public void setUserSelectionRequired(Boolean userSelectionRequired) {
+		this.userSelectionRequired = userSelectionRequired;
+	}
+
+
+	public Boolean isUserSelectionRequired() {
+		return userSelectionRequired;
+	}
 	
 }
Index: trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/helpers/ValueBindingsDataCollector.java
===================================================================
--- trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/helpers/ValueBindingsDataCollector.java	(revision 807)
+++ trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/helpers/ValueBindingsDataCollector.java	(revision 811)
@@ -33,4 +33,5 @@
 	private HashMap<Element,HashSet<TreeObject>> elementToInstantiationTreeObjects = new HashMap<Element,HashSet<TreeObject>>();
 	private HashMap<Element,HashSet<Element>> clientToMediators = new HashMap<Element,HashSet<Element>>();
+	private HashMap<Element,HashSet<Element>> mediatorToClients = new HashMap<Element,HashSet<Element>>();
 	private HashMap<Element,HashSet<Element>> mediatorToProviders = new HashMap<Element,HashSet<Element>>();
 
@@ -60,7 +61,28 @@
 			addToLog("Collecting data from the UML Model '" + ((NamedElement)umlRootModel).getQualifiedName() + "'... \n");
 			collectMeditorsDataFromUmlModel(umlRootModel, umlElementsInInstantiationTree);
+			
+			// remove all mediators that have not clients in the instantiation tree.
+			 removeMediatorsWithNoClientsInInstantiationTree();
 		}
 		else {
 			addToLog("ERROR: Was not able to collect data ...");
+		}
+	}
+	
+	public void removeMediatorsWithNoClientsInInstantiationTree(){
+		HashSet<Element> usedMediatorsCopy = new HashSet<Element>();
+		usedMediatorsCopy.addAll(usedMediators);
+		
+		for (Element mediator : usedMediatorsCopy) {
+			if (mediatorToClients.get(mediator) != null && mediatorToClients.get(mediator).size() > 0) {
+				// ok, do nothing
+			}
+			else {
+				usedMediators.remove(mediator);
+				
+				// TODO: keep the information that mediators exist with providers even if they are not used because 
+				// there are are clients in the instantiated tree or not.
+				//mediatorToProviders.remove(mediator);
+			}
 		}
 	}
@@ -100,5 +122,5 @@
 					for (Dependency dependency : depList) {
 						
-						// reference to a clients
+						// reference to clients
 						if (dependency.getAppliedStereotype(Constants.stereotypeQName_ProvidesValueFor) != null ) { 
 							EList<Element> targets = dependency.getTargets();
@@ -107,11 +129,17 @@
 									// add only mediators and referenced elements if they are used in the instantiation tree
 									if (umlElementsInInstantiationTree.contains(element)) {
+										
 										// Add to referenced client elements
 										referencedClients.add(element);
+										
 										// Add to referenced client tree items
 										if (elementToInstantiationTreeObjects.get(element) != null) {
 											referencedClientTreeItems.addAll(elementToInstantiationTreeObjects.get(element));	
 										}
+										
 										addToClientToMediatorsMap(element, mediator);
+										
+										addToMediatorToClientsMap(mediator, element);
+										
 										usedMediators.add(mediator);
 									}
@@ -223,4 +251,21 @@
 	}
 	
+	
+	private void addToMediatorToClientsMap(Element mediator, Element client){
+		HashSet<Element> set = mediatorToClients.get(mediator);
+		HashSet<Element> updatedSet = new HashSet<Element>();
+		
+		if (set != null && set.size() > 0 ) {
+			updatedSet.addAll(set);
+			updatedSet.add(client);
+			mediatorToClients.put(mediator, updatedSet);
+		}
+		else {
+			updatedSet.add(client);
+			mediatorToClients.put(mediator, updatedSet);
+		}
+	}
+	
+	
 	private void addToMediatorToProvidersMap(Element mediator, Element provider){
 		HashSet<Element> set = mediatorToProviders.get(mediator);
Index: trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/model/TreeUtls.java
===================================================================
--- trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/model/TreeUtls.java	(revision 807)
+++ trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/model/TreeUtls.java	(revision 811)
@@ -29,43 +29,8 @@
 public class TreeUtls {
 
-	public static EList<Element> getAllValueProviders(List<Element> mediators){
-		EList<Element> providers = new BasicEList<Element>();
-		for (Element mediator : mediators) {
-			if (mediator instanceof NamedElement) {
-				EList<Dependency> dependencies = ((NamedElement)mediator).getClientDependencies();
-				for (Dependency dependency : dependencies) {
-					if (dependency.getAppliedStereotype(Constants.stereotypeQName_ObtainsValueFrom) != null) {
-						EList<Element> targets = dependency.getTargets();
-						providers.addAll(targets);
-					}
-				}
-			}
-		}
-		return providers;
-	}
-	
-	public static EList<Element> getValueProvidersFromTree(List<Element> mediators, org.openmodelica.modelicaml.common.instantiation.TreeObject treeRoot){
-		EList<Element> providers = new BasicEList<Element>();
-
-		return providers;
-	}
-	
-	
-	public static EList<Element> getMeditorsFromUmlModel(EObject umlRootElement){
-		EList<Element> mediators = new BasicEList<Element>();
-		if (umlRootElement != null) {
-			Iterator<EObject> i = umlRootElement.eAllContents();
-			while (i.hasNext()) {
-				EObject object = i.next() ;
-				if (object instanceof Property && ((Element)object).getAppliedStereotype(Constants.stereotypeQName_ValueMediator) != null) {
-					mediators.add((Property) object);
-				}
-			}
-		}
-		else {
-			System.err.println("Cannot access the root ModelicaML model to search for Value Mediators.");
-		}
-		return mediators;
-	}
+	
+	
+	
+
 	
 	public static String getStringPropertyFromElement(Element element, String stereotypeQName, String propertyName) {
@@ -81,4 +46,17 @@
 		
 		return stringProperty;
+	}
+	
+	public static EList<String> getStringListPropertyFromElement(Element element, String stereotypeQName, String propertyName) {
+		EList<String> stringPropertyList = null;
+		
+		Stereotype stereotype = element.getAppliedStereotype(stereotypeQName);
+		if (stereotype != null) {
+			Object o = element.getValue(stereotype, propertyName);
+			if (o instanceof EList<?>) {
+				stringPropertyList = (EList<String>)o;
+			}
+		}
+		return stringPropertyList;
 	}
 	
@@ -136,4 +114,6 @@
 	
 	
+	//###################################### Store and Delete
+	
 	public static boolean storeMediatorReference(final Element valueMediatorElement, final EObject valueClientOrProviderElement, final int mode){
 
@@ -142,22 +122,49 @@
 			boolean targetAlreadyExists = false;
 			
+			List<Dependency> exisitingDepToClient = new ArrayList<Dependency>();
+			List<Dependency> exisitingDepToProvider = new ArrayList<Dependency>();
+			
 			for (Dependency dep : mediatorDependencies) {
-				for (Element element : dep.getTargets()) {
-					if (element == valueClientOrProviderElement) {
-						
-						// set the indicator 
-						targetAlreadyExists = true;
-						
-						// inform the user
-						MessageDialog.openError(new Shell(SWT.ON_TOP), "Error", 
-								"'" + ((NamedElement)valueMediatorElement).getQualifiedName() + "' \n"
-								+ " already has a reference to the element \n" +
-										"'" + ((NamedElement)valueClientOrProviderElement).getQualifiedName() + "'\n"
-								+ "\n\nNo reference was stored or updated."); 
-						return false;
-					}
-				}
-			}
-				
+				for (Element target : dep.getTargets()) {
+					
+					// dep to a provider or other mediator
+					Stereotype depStereotype = dep.getAppliedStereotype(Constants.stereotypeQName_ObtainsValueFrom);
+					if (depStereotype == null) {
+						depStereotype = dep.getAppliedStereotype(Constants.stereotypeQName_ProvidesValueFor);
+					}
+					
+					if (target == valueClientOrProviderElement) {
+						if (dep.getAppliedStereotype(Constants.stereotypeQName_ProvidesValueFor) != null) {
+							exisitingDepToClient.add(dep);
+						}
+						if (dep.getAppliedStereotype(Constants.stereotypeQName_ObtainsValueFrom) != null) {
+							exisitingDepToProvider.add(dep);
+						}
+					}
+				}
+			}
+			
+			String modeName = "";
+			if (mode == Constants.MODE_ADD_CLIENT && exisitingDepToClient.size() > 0) {
+				// set the indicator 
+				targetAlreadyExists = true;
+				modeName = "client reference";
+			}
+			else if (mode == Constants.MODE_ADD_PROVIDER && exisitingDepToProvider.size() > 0) {
+				// set the indicator 
+				targetAlreadyExists = true;
+				modeName = "provider reference";
+			}
+
+			if (targetAlreadyExists) {
+				// inform the user
+				MessageDialog.openError(new Shell(SWT.ON_TOP), "Error", 
+						"'" + ((NamedElement)valueMediatorElement).getQualifiedName() + "' \n"
+						+ " already has a " + modeName + " to the element \n" +
+								"'" + ((NamedElement)valueClientOrProviderElement).getQualifiedName() + "'\n"
+						+ "\n\nNo reference was stored or updated."); 
+				return false;
+			}
+			
 			if ( !targetAlreadyExists ) {
 				TransactionalEditingDomain editingDomain = getTransactionalEditingDomain();
@@ -218,6 +225,4 @@
 		return null;
 	}
-	
-	
 	
 	
@@ -283,5 +288,106 @@
 	
 	
-	
+	//############################## Preferred Providers Handling
+	public static String getPreferredProviderAssignmentString(String clientPath, String providerPath){
+		if (clientPath != null  && !clientPath.equals("") && providerPath != null && !providerPath.equals("") ) {
+			return clientPath + Constants.preferredProvidersAssignmentSeparator + providerPath;
+		}
+		return null;
+	}
+
+	public static boolean addToPreferredProvider(final Element mediator, String clientPath, String providerPath){
+		
+		if (mediator != null && !clientPath.isEmpty() && !providerPath.isEmpty()) {
+			
+			EList<String> tempList = null; // working list
+			
+			EList<String> preferredPoviders = getStringListPropertyFromElement(mediator, Constants.stereotypeQName_ValueMediator, Constants.propertyName_preferredProviders);
+
+			if (preferredPoviders != null) { // if a list exists
+				
+				// create the final list
+				tempList = new BasicEList<String>();
+				
+				// collect only items that do not start with client path
+				for (String string : preferredPoviders) {
+					if ( !startsWithPath(string, clientPath) ) {
+						tempList.add(string);
+					}
+				}
+				
+				// add the new assigment to the final list
+				tempList.add(getPreferredProviderAssignmentString(clientPath, providerPath));
+			}
+			else {
+				// add new list
+				tempList = new BasicEList<String>();
+				tempList.add(getPreferredProviderAssignmentString(clientPath, providerPath));
+			}
+			
+			// if the list was created -> store it in the mediator
+			if (tempList != null) {
+
+				final EList<String> finalList = tempList;
+				
+				TransactionalEditingDomain editingDomain = getTransactionalEditingDomain();
+				CompoundCommand cc = new CompoundCommand("Add preferred providers to the mediator.");
+				Command command = new RecordingCommand(editingDomain) {
+					@Override
+					protected void doExecute() {
+						Stereotype stereotype = mediator.getAppliedStereotype(Constants.stereotypeQName_ValueMediator);
+						if (stereotype != null) {
+							mediator.setValue(stereotype, Constants.propertyName_preferredProviders, finalList);
+						}
+					}
+				};
+				cc.append(command);
+				editingDomain.getCommandStack().execute(cc);
+				
+				return true;
+			}
+			
+		}
+		return false;
+	}
+
+	
+	private static boolean startsWithPath(String preferredProviderAssignment, String path){
+		String[] splitted = preferredProviderAssignment.split(Constants.preferredProvidersAssignmentSeparator);
+		if (splitted.length == 2 ) { // if there is a pair with the separator
+			if (splitted[0].trim().equals(path)) {
+				return true;
+			}
+		}
+		return false;
+	}
+	
+	public static boolean isPreferredProviderForClient(EList<String> preferredProviders, String clientPath, String providerPath){
+		if (preferredProviders != null) {
+			for (String preferredProviderAssignment : preferredProviders) {
+				String[] splitted = preferredProviderAssignment.split(Constants.preferredProvidersAssignmentSeparator);
+				if (splitted.length == 2 ) { // if there is a pair with the separator
+					if (splitted[0].trim().equals(clientPath) && splitted[1].trim().equals(providerPath)) {
+						return true;
+					}
+				}
+			}
+		}
+		return false;
+	}
+	
+	
+	public static org.openmodelica.modelicaml.common.instantiation.TreeObject getPreferredProviderForClient(Element mediator, 
+			HashSet<org.openmodelica.modelicaml.common.instantiation.TreeObject> providers, 
+			String clientPath ){
+		if (mediator != null && providers != null) {
+			EList<String> preferredProviders = TreeUtls.getStringListPropertyFromElement(mediator, Constants.stereotypeQName_ValueMediator, Constants.propertyName_preferredProviders);
+			for ( org.openmodelica.modelicaml.common.instantiation.TreeObject treeObject : providers) {
+				if (isPreferredProviderForClient(preferredProviders, clientPath, treeObject.getDotPath())) {
+					return treeObject;
+				}
+			}
+		}
+		return null;
+	}
 	
 	// #############################	TreeViewer management
@@ -380,3 +486,51 @@
 
 	
+	
+	
+	
+	
+	
+	
+	//#################### OBSOLETE
+	
+//	public static EList<Element> getAllValueProviders(List<Element> mediators){
+//	EList<Element> providers = new BasicEList<Element>();
+//	for (Element mediator : mediators) {
+//		if (mediator instanceof NamedElement) {
+//			EList<Dependency> dependencies = ((NamedElement)mediator).getClientDependencies();
+//			for (Dependency dependency : dependencies) {
+//				if (dependency.getAppliedStereotype(Constants.stereotypeQName_ObtainsValueFrom) != null) {
+//					EList<Element> targets = dependency.getTargets();
+//					providers.addAll(targets);
+//				}
+//			}
+//		}
+//	}
+//	return providers;
+//}
+
+//public static EList<Element> getValueProvidersFromTree(List<Element> mediators, org.openmodelica.modelicaml.common.instantiation.TreeObject treeRoot){
+//	EList<Element> providers = new BasicEList<Element>();
+//
+//	return providers;
+//}
+
+
+//public static EList<Element> getMeditorsFromUmlModel(EObject umlRootElement){
+//	EList<Element> mediators = new BasicEList<Element>();
+//	if (umlRootElement != null) {
+//		Iterator<EObject> i = umlRootElement.eAllContents();
+//		while (i.hasNext()) {
+//			EObject object = i.next() ;
+//			if (object instanceof Property && ((Element)object).getAppliedStereotype(Constants.stereotypeQName_ValueMediator) != null) {
+//				mediators.add((Property) object);
+//			}
+//		}
+//	}
+//	else {
+//		System.err.println("Cannot access the root ModelicaML model to search for Value Mediators.");
+//	}
+//	return mediators;
+//}
+	
 }
Index: trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/sections/PropertySection_MediatorPreferredProviders.java
===================================================================
--- trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/sections/PropertySection_MediatorPreferredProviders.java	(revision 811)
+++ trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/sections/PropertySection_MediatorPreferredProviders.java	(revision 811)
@@ -0,0 +1,113 @@
+/*
+ * This file is part of OpenModelica.
+ *
+ * Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC),
+ * c/o Linköpings universitet, Department of Computer and Information Science,
+ * SE-58183 Linköping, Sweden.
+ *
+ * All rights reserved.
+ *
+ * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR 
+ * THIS OSMC PUBLIC LICENSE (OSMC-PL). 
+ * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE
+ * OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. 
+ *
+ * The OpenModelica software and the Open Source Modelica
+ * Consortium (OSMC) Public License (OSMC-PL) are obtained
+ * from OSMC, either from the above address,
+ * from the URLs: http://www.ida.liu.se/projects/OpenModelica or  
+ * http://www.openmodelica.org, and in the OpenModelica distribution. 
+ * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
+ *
+ * This program is distributed WITHOUT ANY WARRANTY; without
+ * even the implied warranty of  MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
+ * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
+ *
+ * See the full OSMC Public License conditions for more details.
+ *
+ * Contributors: 
+ *   Wladimir Schamai, EADS Innovation Works 2009-2011
+ *   Uwe Pohlmann, University of Paderborn 2009-2010
+ *   Parham Vasaiely, EADS Innovation Works / Hamburg University of Applied Sciences 2009-2011
+ */
+package org.openmodelica.modelicaml.view.valuebindings.sections;
+
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.papyrus.profile.ImageManager;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.FormAttachment;
+import org.eclipse.swt.layout.FormData;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
+import org.openmodelica.modelicaml.common.constants.Constants;
+import org.openmodelica.modelicaml.tabbedproperties.editors.sections.AbstractMultiStringSection;
+import org.openmodelica.modelicaml.view.valuebindings.model.TreeObject;
+
+// TODO: Auto-generated Javadoc
+/**
+ * The Class InstanceModificationsSection.
+ */
+public class PropertySection_MediatorPreferredProviders extends AbstractMultiStringSection {
+
+	/**
+	 * Instantiates a new instance modifications section.
+	 */
+	public PropertySection_MediatorPreferredProviders() {
+		super();
+		stereotypPropertieName = Constants.propertyName_preferredProviders; 
+	}
+
+	/* (non-Javadoc)
+	 * @see org.openmodelica.modelicaml.tabbedproperties.editors.sections.AbstractMultiStringSection#createControls(org.eclipse.swt.widgets.Composite, org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage)
+	 */
+	@Override
+	public void createControls(Composite parent,
+			TabbedPropertySheetPage tabbedPropertySheetPage) {
+		// TODO Auto-generated method stub
+		super.createControls(parent, tabbedPropertySheetPage);
+		FormData data;
+		data = new FormData();
+		data.left = new FormAttachment(0, 0);
+		data.width = 400;
+		data.top = new FormAttachment(overviewLabel, 5);
+		data.height = 150;
+		modificationList.setLayoutData(data);
+		
+		// remove the edit listener
+		modificationList.removeMouseListener(listlistener);
+
+	}
+
+	protected void addButtons(Composite composite, FormData data){
+		// ///////////////////////////////////////////////////////////////////////////
+		// Create and place button vertically on the left side
+		// Button Delete Element
+		
+		removeButton = new Button(composite, SWT.PUSH);
+		removeButton.setVisible(true);
+		removeButton.setImage(ImageManager.IMG_DELETE);
+		removeButton.setToolTipText("Delete selected element(s)");
+		data = new FormData();
+		data.left = new FormAttachment(modificationList, 5);
+		data.top = new FormAttachment(overviewLabel, 0);
+		removeButton.setLayoutData(data);
+		removeButton.addMouseListener(deleteButtonlistener);
+	}
+	
+	
+	@Override
+	public void setInput(IWorkbenchPart part, ISelection selection) {
+		// get the selectedUmlElement
+		Object input = ((IStructuredSelection) selection).getFirstElement();
+		if (input instanceof TreeObject) {
+			this.selectedUmlElement = ((TreeObject)input).getUmlElement();	
+		}
+		super.setInput(part, selection);
+	}
+
+
+}
Index: trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/views/ValueBindingsView.java
===================================================================
--- trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/views/ValueBindingsView.java	(revision 807)
+++ trunk/modelicaml/org.openmodelica.modelicaml.view.valuebindings/src/org/openmodelica/modelicaml/view/valuebindings/views/ValueBindingsView.java	(revision 811)
@@ -394,6 +394,6 @@
 			}
 		};
-		actionShowClientPerspective.setText("Show Client Perspective");
-		actionShowClientPerspective.setToolTipText("Show Client Perspective");
+		actionShowClientPerspective.setText("Show Client Perspective (read-only)");
+		actionShowClientPerspective.setToolTipText("Show Client Perspective (read-only)");
 //		actionShowClientPerspective.setImageDescriptor(ImageDescriptor.createFromFile(ValueBindingsView.class, "/icons/reload.png"));
 		
@@ -414,6 +414,6 @@
 			}
 		};
-		actionShowProviderPerspective.setText("Show Provider Perspective");
-		actionShowProviderPerspective.setToolTipText("Show Provider Perspective");
+		actionShowProviderPerspective.setText("Show Provider Perspective (read-only)");
+		actionShowProviderPerspective.setToolTipText("Show Provider Perspective (read-only)");
 //		actionShowProviderPerspective.setImageDescriptor(ImageDescriptor.createFromFile(ValueBindingsView.class, "/icons/reload.png"));
 		
