Pablo Galiano : How do I create a ModelElement via API

Subscriptions

<September 2010>
SuMoTuWeThFrSa
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

News

Subscribe to Pablo Galiano by Email

Post Categories

How do I create a ModelElement via API

My eighteenth How do I is up.

Scenario

Let's say that we start from the Minimal Language DSL template and we have an ExampleElement domain class that has a Name domain property with the Is Element Name flag set to true.

Because it has the IsElementName flag, every time that we create a ExampleElement with the UI (toolbox or model explorer) the element is created with a default name. This default name is composed of the type name of the concept plus an index. Example : ElementName1, ElementName2, etc.

The focus of this How do I shows how to create the model element programmatically.

 

Interfaces and classes needed

 

Code snippet

Wrong way:

private void CreateElement(Store store)

{

    using(Transaction tx = store.TransactionManager.BeginTransaction("Add ExampleElement"))

    {

        ExampleModel root = store.ElementDirectory.FindElements<ExampleModel>().First() as ExampleModel;

 

        ExampleElement element =

            this.Store.ElementFactory.CreateElement(ExampleElement.DomainClassId) as ExampleElement;

 

        root.Elements.Add(element);

 

        tx.Commit();

    }

}

 

Right way:

 

private void CreateElement(Store store)

{

    using(Transaction tx = store.TransactionManager.BeginTransaction("Add ExampleElement"))

    {

        ExampleModel root = store.ElementDirectory.FindElements<ExampleModel>().First() as ExampleModel;

 

        ExampleElement element =

            store.ElementFactory.CreateElement(ExampleElement.DomainClassId) as ExampleElement;

 

        ElementOperations elementOperations =

            new ElementOperations(store as IServiceProvider, store);

 

        ElementGroup elementGroup = new ElementGroup(store);

        elementGroup.Add(element);

        elementGroup.MarkAsRoot(element);

        elementOperations.MergeElementGroup(root, elementGroup);

 

        tx.Commit();

    }

}

 

 

Assemblies needed

  • Microsoft.VisualStudio.Shell.Interop
  • Microsoft.VisualStudio.Modeling.Sdk.Shell
  • Microsoft.VisualStudio.Modeling.Sdk.Diagrams

 

Stay tuned,

Pablo

posted on Tuesday, September 30, 2008 8:17 AM by pga

What do you think?

(required) 
required 
optional
required