TrueView Application Developers Guide

download TrueView Application Developers Guide

of 86

Transcript of TrueView Application Developers Guide

  • 8/14/2019 TrueView Application Developers Guide

    1/86

    Creating applications using

    TrueView for .NET

    2006-2009 Evolving Software Limited. All rights reserved.

    http://www.evolving-software.co.uk/

  • 8/14/2019 TrueView Application Developers Guide

    2/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 2

    2006-2009 Evolving Software Limited. All rights reserved. No part of this document or the related filesmay be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, orotherwise) without the prior written permission of the publisher.

    Conditions of the use of this document and the information within can be found in the associatedEULA. You can also find it online at:

    http://www.evolving-software.co.uk/trueview-eula.html

    Evolving Software Limited is registered in England and Wales. Our Company Registration Number is06024938. Our registered office is 20 Winchcombe Street, Cheltenham. England. GL52 2LY.

    Find us on the web athttp://www.evolving-software.co.uk

    Last revised : 2009-08-20

    http://www.evolving-software.co.uk/http://www.evolving-software.co.uk/http://www.evolving-software.co.uk/
  • 8/14/2019 TrueView Application Developers Guide

    3/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 3

    Contents

    1 Introduction.................................................................................................................................................... 72 Domain Model Design ................................................................................................................................. 8

    2.1 Summary of the Domain Entities ...................................................................................................... 92.2 Design tips ............................................................................................................................................. 9

    2.2.1 Tips for Domain Entity design .................................................................................................... 92.2.2 Tips for agile design ...................................................................................................................... 9

    3 Getting started.............................................................................................................................................. 114 Adding Entity classes .................................................................................................................................. 14

    4.1 A simple Entity class .......................................................................................................................... 144.2 Basic guidelines for creating Entities ............................................................................................... 154.3

    Value types ........................................................................................................................................... 16

    4.4 Enumerations ...................................................................................................................................... 174.5 Nullable types ...................................................................................................................................... 18

    5 Using a TrueView application .................................................................................................................... 195.1 Navigation basics ................................................................................................................................ 195.2 Operation basics ................................................................................................................................. 19

    5.2.1 Creating an entity ......................................................................................................................... 195.2.2 Editing values ............................................................................................................................... 205.2.3 Linking entities ............................................................................................................................. 205.2.4 Copying values and ValueObjects ............................................................................................. 205.2.5 Saving an entity ............................................................................................................................ 20

    5.3 Actions ................................................................................................................................................. 20 5.4 Message View ...................................................................................................................................... 215.5 Preferences and Options ................................................................................................................... 21

    6 Relationships between entities ................................................................................................................... 226.1 One-to-One ......................................................................................................................................... 226.2 One-to-Many ....................................................................................................................................... 256.3 Many-to-Many ..................................................................................................................................... 276.4 The EntityLinker class ....................................................................................................................... 28

    6.4.1 Entities with multiple relationships ........................................................................................... 286.5 Parameterised constructors ............................................................................................................... 296.6 Validation rules ................................................................................................................................... 30

    6.6.1 Validating properties immediately ............................................................................................. 306.6.2 Validating before saving.............................................................................................................. 30

  • 8/14/2019 TrueView Application Developers Guide

    4/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 4

    7 Relationship semantics ................................................................................................................................ 327.1 One-to-One ......................................................................................................................................... 327.2 One-To-Many ..................................................................................................................................... 33

    8 Adding actions ............................................................................................................................................. 358.1 Methods with parameters .................................................................................................................. 358.2 Results from functions ....................................................................................................................... 368.3 Static methods ..................................................................................................................................... 36

    9 Unit testing your code ................................................................................................................................. 3710 Enhancing the user interface ..................................................................................................................... 38

    10.1 Code comments really matter ........................................................................................................... 3810.2 Formatting primitive values .............................................................................................................. 39

    10.2.1

    Text formatting ............................................................................................................................ 39

    10.2.2 Date formatting ............................................................................................................................ 4010.2.3 Boolean formatting ...................................................................................................................... 4010.2.4 Number formatting ..................................................................................................................... 4110.2.5 File and Folder paths ................................................................................................................... 42

    10.3 Dynamic Drop-Down Lists .............................................................................................................. 4310.4 Pre-filtered Search Query dialogs ..................................................................................................... 4410.5 Organising your properties................................................................................................................ 4610.6 Icons ..................................................................................................................................................... 4810.7 Colours and fonts ............................................................................................................................... 4910.8 Custom backgrounds ......................................................................................................................... 5010.9 Custom WinForms ............................................................................................................................. 5110.10 User messages ................................................................................................................................... 52

    10.10.1 Audit logs ............................................................................................................................... 53 10.10.2 Custom Trace hooks ............................................................................................................ 53

    11 Factories, Repositories, and Services ........................................................................................................ 5411.1 Factory classes ..................................................................................................................................... 5411.2 Repository classes ............................................................................................................................... 5511.3 Service classes................................ ...................................................................................................... 56

    12 Dependency Injection & the Service Locator ......................................................................................... 5712.1 Choosing from different dependency implementations ............................................................... 57

    13 Entity Persistence ........................................................................................................................................ 5813.1 Object Relational Mapping ............................................................................................................... 5813.2 Mapping files ....................................................................................................................................... 58

  • 8/14/2019 TrueView Application Developers Guide

    5/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 5

    13.3 Virtual methods .................................................................................................................................. 5813.4 Variable naming standards ................................................................................................................ 5813.5 Record locking .................................................................................................................................... 5913.6 Record auditing ................................................................................................................................... 5913.7 Connection management ................................................................................................................... 5913.8 Loading entities within your code .................................................................................................... 5913.9 Saving entities from within your code ............................................................................................. 6013.10 Quick start: Enabling database persistence for your application .............................................. 61

    14 Reports .......................................................................................................................................................... 6415 Attributes ...................................................................................................................................................... 67

    15.1 Attribute descriptions ........................................................................................................................ 6815.1.1

    AbstractAttribute ......................................................................................................................... 68

    15.1.2 EntityClassAttribute .................................................................................................................... 6815.1.3 MemberAttribute ......................................................................................................................... 6815.1.4 PropertyAttribute ......................................................................................................................... 6915.1.5 AbstractEntityAttribute .............................................................................................................. 6915.1.6 EntityAttribute ............................................................................................................................. 6915.1.7 EntityListAttribute....................................................................................................................... 7015.1.8 DateTimeAttribute ...................................................................................................................... 7015.1.9 BooleanAttribute.......................................................................................................................... 7015.1.10 StringAttribute ....................................................................................................................... 7015.1.11 TextAttribute ......................................................................................................................... 70 15.1.12 PathAttribute ......................................................................................................................... 71

    16 Sample NHibernate mapping files ............................................................................................................ 7216.1 Simple entity ........................................................................................................................................ 7216.2 Entity with One-To-Many relationship ........................................................................................... 7216.3 Entities with Many-To-Many relationships .................................................................................... 73

    17 Advanced development: Custom base classes......................................................................................... 7517.1 Evolving.TrueView.Domain.IEntity ............................................................................................... 7517.2 Evolving.TrueView.Domain.IValueObject .................................................................................... 7617.3 Evolving.TrueView.Persistence.IPersistable .................................................................................. 7717.4 Evolving.TrueView.Domain.IEntityList ......................................................................................... 78

    18 Advanced development: Lists that accept multiple types ...................................................................... 8219 Advanced development: Resolving relationships manually................................................................... 83

    19.1.1 One-to-One relationships ........................................................................................................... 83

  • 8/14/2019 TrueView Application Developers Guide

    6/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 6

    19.1.2 One-to-Many relationships......................................................................................................... 8419.1.3 Many-to-Many relationships ...................................................................................................... 85

    20 Advanced development: Injecting your own dependencies .................................................................. 86

  • 8/14/2019 TrueView Application Developers Guide

    7/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 7

    1 Introduction Thank you for purchasing TrueView. We hope that TrueView will open up a new world of richapplication development. Using the power of Domain Driven Design, you will be building flexible.NET applications faster than ever before!

    TrueViews goal is simple to create applications based directly on .NET entities that you define.TrueView will handle the UI, persistence, and securityleaving you to focus on the aspects that deliverbusiness value.

    Figure 1 : Example of a TrueView application

    As you work through this guide, you will be shown the many features that TrueView has to offer. Thisguide is broken in the following sections:

    How to define Domain Entities How to create relationships between domain entities Customising the user interface Persisting your domain entities Adding reports

  • 8/14/2019 TrueView Application Developers Guide

    8/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 8

    2 Domain Model DesignThe core of any TrueView application is the domain model. For our example well use a simple StudentManagement application. Various examples in this guide will refer to this model:

    Figure 2 : An outline of the Teacher/Course domain model

    If youre a fan ofUML, you may prefer the following representation:

    Figure 3 : A UML view of the domain model

  • 8/14/2019 TrueView Application Developers Guide

    9/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 9

    2.1 Summary of the Domain EntitiesEntity Description

    Course A Course represents the complete syllabus that a Student will take. For example, a

    course could be B.Sc. Computer Science or PhD Biochemistry.Topic Courses are typically divided into many Topics. Students are allowed to choose

    from multiple Topics (as long as the topics belong to the same course, and theschedules do not overlap)

    Teacher A Teacher is responsible for teaching a specific set of Topics. Teachers havespecific experiences, and will teach Topics that are appropriate for their skills.

    Student A Student is an individual that is enrolled on a Course

    Site The campus contains several buildings where Lectures are held. Each of these

    buildings is regarded as a Site, and a Site may contain any number of Locations.

    Location A Location is a room or hall where Lectures are held. Different Lectures fordifferent Courses may be held at a single Location (but not at the same time!)

    Lecture A Lecture is held by a Teacher for a particular Topic, and is presented to a groupof Students. The Lecture is held at a single Location at a given time, and must notoverlap with another Lecture at the same time and Location.

    Note that we havent tried to model every aspect of the domain (as it would take an extremely longtime!). We have only focused on the entities that have a clear responsibility within our business

    problem.2.2 Design tips

    Although designing domain models is beyond the scope of this guide, here are a few tips to keep inmind:

    2.2.1 Tips for Domain Entity design Nouns are usually a good starting point for your entities Identify entities that have clear responsibilities in the domain

    Sometimes actions or events can become entities (e.g. the task ofmaking a payment mighttranslate into a Payment entity)

    Dont create more entities than necessarylet the model evolve naturally Inheritance can make your model over-complicatedconsider using aggregation instead Your entities will be presented directly to your users make sure they are as simple and as

    usable as possible

    2.2.2 Tips for agile design Dont create more entities than necessary let the model evolve naturally

  • 8/14/2019 TrueView Application Developers Guide

    10/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 10

    Leave UI customisations, persistence, and security as late as possible these aspects take thelongest time to modify and may detract you from designing the entities

    Use the best domain experts you can findyour users! Domain Driven Design is an evolving topicstay current to learn how to use it best. TrueView allows you to tweak your entity classes and see the results very quickly. Use this ability

    to make the design phase as agile as possible.

  • 8/14/2019 TrueView Application Developers Guide

    11/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 11

    3 Getting startedAs you follow this guide we will show you various code snippets to help build your application. Youllneed an empty project to work with, so follow these steps inside Microsoft Visual Studio:

    1) Create a newWindows Application project (use a location of your choice):

    2) Add a reference to the TrueView assembly (youll find assembly DLL in the installationlocation):

  • 8/14/2019 TrueView Application Developers Guide

    12/86

  • 8/14/2019 TrueView Application Developers Guide

    13/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 13

    5) Hit F5 and you should see the following TrueView application.

    Its a bit empty, so lets add some entities to our application!

  • 8/14/2019 TrueView Application Developers Guide

    14/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 14

    4 Adding Entity classes Your application needs a .NET class for each domain entity identified in the domain model. Thequickest way to create usable entities is to inherit directly from the base classes provided by TrueView.

    These classes are:

    Evolving.TrueView.Domain.Entity

    This type of entity may be loaded and saved to thepersistence store and will usually be the mostcommonly used base type.

    Evolving.TrueView.Domain.EntityList This type is used to hold lists of entities. TheEntityList has additional events to manage entityassociations (see later).

    Evolving.TrueView.Domain.ValueObject

    This type is used for objects that are always copied(somewhat like .NET structs ). Use it for objectsthat should not be shared between Entities.

    Evolving.TrueView.Domain.TransientEntity A transient entity is one that is not loaded orsaved to any persistence store. Users will not beprompted to save these entities when they areclosed.

    Evolving.TrueView.Domain.TransientEntityList This type is used to hold lists of entities that arenot loaded or saved to any persistence store.Users will not be prompted to save these entities

    when they are closed.

    4.1 A simple Entity classHere is an example of the Course entity:

    using Evolving.TrueView.Domain;using Evolving.TrueView.Domain.Attributes;namespace TeachingCourseSample{

    [Serializable]public class Course : Entity{

    private string _Name = string.Empty;

    ///

    /// The name of the Course/// public string Name{

    get { return _Name; }set { _Name = value; }

    }

    private string _Description;

    /// /// The description of the Course/// public string Description{

    get { return _Description; }set { _Description = value; }

    }

    private EntityList _Topics = new EntityList();

    All entity classes must be

    Serializable

    Use interfaces that are

    recognised by TrueView

  • 8/14/2019 TrueView Application Developers Guide

    15/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 15

    /// /// All topics within the Course/// public EntityList Topics{

    get { return _Topics; }}

    ///

    /// A short summary of the entity/// public override string Summary{

    get{

    if (!string.IsNullOrEmpty(_Name))return _Name;

    elsereturn base.Summary;

    }}

    }}

    This entity will be presented to the user like this (complete with editable properties):

    Figure 4: Presentation of the Course entity

    The rest of your entity classes will be defined in a similar fashion. Easy!

    4.2 Basic guidelines for creating Entities All entity classes must be recognisable by TrueView (i.e. they must implement known

    interfaces)

    OnlyPublic entity classes (and members) are visible to the end user All property backing fields must end with the name of the property (any prefixes are ignored):

    private string _FirstName;public string FirstName(){

    get { return _FirstName; }set { _FirstName = value; }

    }

    private string fName;public string FirstName(){

    get { return fName; }

    set { fName = value; }}

    Summaries make it easier for

    users to identify entities

    BAD - Property and field

    names dont match

    GOOD Property and

    field names match

  • 8/14/2019 TrueView Application Developers Guide

    16/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 16

    Entity classes must be declared as Serializable The guideline for backing fields doesnt apply to C# 3.0 auto-properties, as they are automatically

    handled by TrueView.

    4.3 Value typesMost entities will consist ofvalue properties. These properties are viewed - and edited - by your users.

    TrueView regards the follow .NET types as values:

    Group .NET types

    Integer int, int16, int32, int64, short, byte

    Floating double, decimal, float

    Dates DateTime

    Timespan Timespan

    Boolean bool

    Text String

    File/Folder paths String

    Enumeration Enum

    When the application is run, the user will see the following editors for each type:

    Figure 5 : Presentation of different value types

  • 8/14/2019 TrueView Application Developers Guide

    17/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 17

    4.4 EnumerationsTrueView understands both regular enumerations and bitwise enumerations. Lets take a look at thetwo types of enumerations definitions.

    The regular enumeration is presented as a list, where the user can select from one of the options:

    public enum RegularEnum{

    Mr = 10,Mrs = 20,Ms = 30,Miss = 40,Master = 50

    }

    private RegularEnum _RegularEnumeration;

    /// /// Regular enums are presented as a list of options./// Users may select one value from the list./// public RegularEnum RegularEnumeration{

    get { return _RegularEnumeration; }set { _RegularEnumeration = value; }}

    Figure 6: Presentation of a normal enum

    The bitwise enumeration is presented as a selection of options, where the user can choose anycombination of options.

    [Flags]public enum BitwiseEnum{

    RegularStudent = 1,OverseasStudent = 2,SelfFunded = 4,

    MatureStudent = 8,PartTimeStudent = 16}

    private BitwiseEnum _BitwiseEnumeration = BitwiseEnum.RegularStudent;

    /// /// Bitwise enums are presented as a set of checkboxes./// Users may choose any combination of values./// public BitwiseEnum BitwiseEnumeration{

    get { return _BitwiseEnumeration; }set { _BitwiseEnumeration = value; }

    }

    Use gaps in the numbers to

    allow for additional items in

    the future

  • 8/14/2019 TrueView Application Developers Guide

    18/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 18

    Figure 7: Presentation of a bitwise enum

    4.5 Nullable typesAll value types may be made nullable. Nullable types have the following behaviour:

    They can be cleared completely(i.e. they dont revert to a default value) They are persisted as NULL values within a database Nullable types can be very useful in certain situations, but may make your code more complex.

  • 8/14/2019 TrueView Application Developers Guide

    19/86

  • 8/14/2019 TrueView Application Developers Guide

    20/86

  • 8/14/2019 TrueView Application Developers Guide

    21/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 21

    Any results from an action will be displayed either as a new view, or in the Message View.

    5.4 Message View The Message View is a critical area of the UI. All errors, warnings, and messages generated by theapplication are listed here. Double-clicking on an item will open it in a larger dialog.

    1) Errors are display in red. This quickly draws attention to the fact that something has gonewrong.

    2) Warnings are show in yellow. Again, this is designed to draw attention to the window.3) Informational messages are shown in white. This provides users with a running commentary of

    their session.

    Ensure that youre always working with the latest data (in a multi-user environment) by closing allwindows in the workbench on a regular basis.

    5.5 Preferences and OptionsThere are a variety of options that can be set. ClickTools Options to see them.

  • 8/14/2019 TrueView Application Developers Guide

    22/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 22

    6 Relationships between entitiesThere are three groups of relationships that entities may have with each other:

    One-to-One One-to-Many Many-to-Many

    Establishing and maintaining relationships requires a little bit of extra work (but thankfully not toomuch). The following sections show how.

    6.1 One-to-OneIn our domain model, a Site is associated with an Address (how else could we get to our lectures?). Our

    goal is to make relationships incredibly easy to define through code. For example, it you wanted tocreate a relationship between them, you would write something like this:

    Site site = new Site();Address address = new Address();

    // Link the two together:site.Address = address;

    Figure 8 : Both entities have links to each other

    Our goal is to have bi-directional relationships, so that each entity knows about the other. Creating bi-directional relationships isnt as straightforward as you might thinksimply setting the property valueson each entity would eventually cause a StackOverflowException, as both entities would call each otherendlessly.

    Instead, you would use the property setter to execute some linking logic. We recommend using theprovided EntityLinker classits easy to use and makes code easier to read:

  • 8/14/2019 TrueView Application Developers Guide

    23/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 23

    public class Site : Entity{

    private Address _Address;

    /// /// The Address of this Site/// public Address Address{

    get { return _Address; }set{

    if (value != null){ EntityLinker.Link(this).With(value);}else{ EntityLinker.Unlink(this).From(_Address);}

    }}

    }

    public class Address : Entity{

    private Site _Site;

    /// /// The Site that this Address belongs to/// public Site Site{

    get { return _Site; }set{

    if (value != null){ EntityLinker.Link(this).With(value);}else{ EntityLinker.Unlink(this).From(_Site);}

    }

    }

    }

    Once youve got the linking code in place, you can execute some unit tests:

    Site site = new Site();Address address = new Address();

    // Link the two together:site.Address = address;Assert.AreEqual(site.Address, address);Assert.AreEqual(address.Site, site);

    The EntityLinker knows how to

    resolve relationships for both

    entities

  • 8/14/2019 TrueView Application Developers Guide

    24/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 24

    Performing the operation from the other entity yields the same result:

    Site site = new Site();Address address = new Address();

    // Link the two together:address.Site = site;Assert.AreEqual(address.Site, site);Assert.AreEqual(site.Address, address);

    And the relationship can be broken by setting the property to null:

    Site site = new Site();Address address = new Address();

    // Unlink the two:site.Address = null;Assert.IsNull(site.Address);Assert.IsNull(address.Site);

  • 8/14/2019 TrueView Application Developers Guide

    25/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 25

    6.2 One-to-ManyThis describes the relationship where one entity holds a reference to a list of other entities. TrueViewsbase EntityList class has a handful of events that are used to invoke the scaffolding code.

    In this example you can see howTopics are added to a Course. To create the relationships, our code

    should look like this:

    Course course = new Course();Topic topic = new Topic();

    // Link the two together:course.Topics.Add(topic);

    Figure 9 : Child entities must have a reference back to their parents

    The EntityList conveniently provides AddItem and RemoveItem events, which allow you to executelogic before items are added (or removed) from the list. Use these to execute your linking logic:

    public class Course : Entity{

    public Course(){

    _Topics.AddItem += new AddItemEventHandler(_Topics_AddItem);_Topics.RemoveItem += new RemoveItemEventHandler(_Topics_RemoveItem);

    }

    void _Topics_AddItem(object sender, Topic item, OperationEventArgs args){ EntityLinker.Link(this).With(item, e);}

    void _Topics_RemoveItem(object sender, Topic item, OperationEventArgs args){ EntityLinker.Unlink(this).From(item, e);}

    private EntityList _Topics = new EntityList();

    [EntityList(Relationship = EntityListAttribute.RelationshipType.Composition)]public EntityList Topics{

    get { return _Topics; }}

    }

    Dont forget to pass the

    OperationEventArgs

    Dont forget to hook up the

    event handlers

  • 8/14/2019 TrueView Application Developers Guide

    26/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 26

    The other entity in the relationship uses a property, so its linking logic looks like this:

    public class Topic : Entity{

    private Course _Course;

    /// /// The course that this Topic belongs to/// [Entity(Relationship = EntityAttribute.RelationshipType.Parent)]public Course Course{

    get { return _Course; }set{

    if (value != null){ EntityLinker.Link(this).With(value);}else{ EntityLinker.Unlink(this).From(_Course);}

    }}

    }

    Once the linking code is in place, you can add a Topic to a Course like this:

    Course course = new Course();Topic topic = new Topic();

    // Link the two together:course.Topics.Add(topic);Assert.AreEqual(topic.Course, course);

    // Removing the Topic from the collection will cancel the relationship:// Unlink the two:course.Topics.Remove(topic);Assert.IsNull(topic.Course);Assert.That(course.Topics.Count == 0);

    Child entities should always have a property that refers back to its parent. This will become arequirement when you persist your entities to a database.

    Remember the Relationship = EntityAttribute.RelationshipType.Parent attribute, otherwiseTrueView might include unwanted entities while saving.

    Parent relationships tell TrueView

    how to navigate object graphs

  • 8/14/2019 TrueView Application Developers Guide

    27/86

  • 8/14/2019 TrueView Application Developers Guide

    28/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 28

    EntityLinker.Link(this).With(item, e);}

    void _Students_RemoveItem(object sender, Student item, OperationEventArgs e){ EntityLinker.Unlink(this).From(item, e);}

    }

    Heres some code to test it:

    Student student = new Student();Topic topic1 = new Topic();Topic topic2 = new Topic();

    // Link student1 and topic1 together:student.Topics.Add(topic1);Assert.That(topic1.Students.Contains(student));Assert.That(student.Topics.Contains(topic1));

    // Link topic2 and student1 together:topic2.Students.Add(student);Assert.That(topic2.Students.Contains(student));

    Assert.That(student.Topics.Contains(topic2));

    Developers from a database background may question this approach. As we are working only withentities classes, we must define the relationships without depending on any persistence store.Remember: a relational modelhas different semantics to an entity model.

    6.4 The EntityLinker classThe EntityLinker manages relationships with little effort. As youve seen from the previous examples,

    it keeps the code concise and readable - we recommend that you use it wherever possible.

    Importantly, the EntityLinker accesses the backing fields directly, so its crucial that the property andfield names match (see section 4.2 Basic guidelines).

    6.4.1 Entities with multiple relationshipsSometimes you will have the two entities that have multiple relationships with each other. If this is thecase, you will need to specify the property names so that the EntityLinker knows which relationship touse:

    public class Student : Entity{

    public Student(){_Topics.AddItem += new AddItemEventHandler(_Topics_AddItem);_Topics.RemoveItem += new RemoveItemEventHandler(_Topics_RemoveItem);

    }

    void _Topics_AddItem(object sender, Topic item, OperationEventArgs e){

    EntityLinker.Link(this, Topics).With(item, Students, e);}

    void _Topics_RemoveItem(object sender, Topic item, OperationEventArgs e){

    EntityLinker.Unlink(this, Topics).From(item, Students, e);}

    }

  • 8/14/2019 TrueView Application Developers Guide

    29/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 29

    public class Topic : Entity{

    public Topic(){

    _Students.AddItem += new AddItemEventHandler(_Students_AddItem);_Students.RemoveItem += new RemoveItemEventHandler(_Students_RemoveItem);

    }

    void _Students_AddItem(object sender, Student item, OperationEventArgs e)

    { EntityLinker.Link(this, Students).With(item, Topics, e);}

    void _Students_RemoveItem(object sender, Student item, OperationEventArgs e){

    EntityLinker.Unlink(this, Students).From(item, Topics, e);}

    }

    For high performance situations, you may find the EntityLinker to be a little slow. If you wantcomplete control over the linking process, refer to section 19 Advanced development: Resolvingrelationships manually

    6.5 Parameterised constructors You know that a Course contains many Topics, so you might want to associate them using aconstructor:

    public class Topic : Entity{

    public Topic(){

    // Default ctor}

    public Topic(Course parentCourse): this(){ _Course = parentCourse;}

    }

    Topic myTopic = new Topic(myCourse);

    When a user creates a new entity within the UI, TrueView will look for a constructor that accepts theparent entity as an argument. If it finds a matching constructor it will use that instead of the defaultone.

    TrueView only supports constructors that accept a single Entity as a parameter

  • 8/14/2019 TrueView Application Developers Guide

    30/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 30

    6.6 Validation rulesIn many cases youll need to execute some validation on your entities. When you consider that there isno UI code, where are these validation rules supposed to go?

    The domain entity itself is responsible for any validation logic on its properties or members. Initially

    this may seem odd, but the major benefit is that validation logic will be executed regardless of whetherit was invoked by a user action or directly from code.

    The two most common options are to (a) validate a property as soon as its changed, or (b) validate theappropriate values just before the entity is saved. You may even find it necessary to use bothtechniques for your entities.

    6.6.1 Validating properties immediatelyThis technique will notify users immediately of an invalid entry they have made.

    using System.Diagnostics;public class Site : Entity{

    virtual public string Name{

    get { return _Name; }set{ if (string.IsNullOrEmpty(_Name))Trace.TraceError("Please provide a Name for this Site");

    else_Name = value;

    }}

    private string _Description;

    virtual public string Description

    {get { return _Description; }set{ if (string.IsNullOrEmpty(_Description))Trace.TraceError("Please provide a Description for this Site");

    else_Description = value;

    }}

    }

    If you intend on setting properties through code, you might want to throw exceptions instead.

    6.6.2 Validating before saving This option lets you defer all validation until the entity is saved. At this point theOnBeforeSave()method is called, and this is where you can execute your logic:

    using System.Diagnostics;

    public class Site : Entity{

    /// /// Performs validation just before the entity is persisted/// public override bool OnBeforeSave(){

    bool okToSave = true;

    if (string.IsNullOrEmpty(_Name))

  • 8/14/2019 TrueView Application Developers Guide

    31/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 31

    {Trace.TraceError("Please provide a Name for this Site");okToSave = false;

    }

    if (string.IsNullOrEmpty(_Description)){

    Trace.TraceError("Please provide a Description for this Site");okToSave = false;

    }

    // These are a non-fatal messages for the user:if (_Address == null)

    Trace.TraceWarning("No Address has been associated with this Site");

    if (_Locations.Count == 0)Trace.TraceWarning("No Locations have been provided for this Site");

    if (!okToSave)Trace.TraceError("Please correct the above errors before saving");return okToSave;

    }

    }

    If your rules become complex over time, consider refactoring them into separate objects toenhance readability and re-usability. In DDD, these are known as Invariants.

  • 8/14/2019 TrueView Application Developers Guide

    32/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 32

    7 Relationship semanticsDefining relationships between entities is only part of the solutionTrueView needs to understand thesemanticsof those relationships. This information allows TrueView to provide specific UI behaviour

    when linking and unlinking entities. It also provides a richer understanding of the domain when you

    read the code.7.1 One-to-OneLets consider the relationship between a Site and an Address:

    using Evolving.TrueView.Domain.Attributes;public class Site : Entity{

    private Address _Address;

    /// /// The Address of this Site/// [Entity(Relationship = EntityAttribute.RelationshipType.Association)]public Address Address{

    get { return _Address; }set{

    if (value != null){

    EntityLinker.Link(this).With(value);}else{

    EntityLinker.Unlink(this).From(_Site);}

    }}

    }

    This particular relationship has been declared as an Association the simplest option. Use theEntityAttribute.Relationship attribute to define the type of relationship. The possible values are:

    Relationship Type Semantic meaning

    Aggregation The property value is a part of the entity (e.g. Address would be considered a partof Site)

    Composition The property value is owned by the entity (e.g. Site would be considered as the ownerofAddress). Only the owner may delete the entity.

    Component This has the same semantics as Composition. It means that the property value is stored in thesame physical space as the owner (e.g. Site and Address would be stored in the same rowin arelational database). In DDD, this is also known as a Value Object.

    Parent The property value is the parent of the entity (e.g. Course would be considered as the parentof Topic).

    Association This is the loosest form of relationship and has no semantics (e.g. Address is related to the Site,but has none of the semantics in the other types)

    Be sure to apply the Parent relationship when applicable. This will ensure that Entities arecorrectly identified within an object graph.

    Relationships are defined

    using the appropriate value

  • 8/14/2019 TrueView Application Developers Guide

    33/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 33

    7.2 One-To-ManyLets look at the Course and Topic entities. In our domain model you can see that a CourseownsTopic

    entities, and needs to be declared as such:

    using Evolving.TrueView.Domain.Attributes;

    public class Course : Entity{

    private EntityList _Topics = new EntityList();

    /// /// All topics within the Course/// [EntityList(Relationship = EntityListAttribute.RelationshipType.Composition)]public EntityList Topics{

    get { return _Topics; }}

    }

    The domain model shows that a Student also has a one-to-many relationship with Topic. However,because a Student is not an owner of a Topic, its marked as an Aggregation relationship instead.

    Relationship Type Semantic meaning

    Composition The lists contents are owned by the entity (e.g. Course would be considered as the ownerforall Topic entities within the list). Only the owner may delete the entities within the list.

    Aggregation The contents of the list are part of the entity (e.g. All Topic entities witihn the list would beconsidered as a partof Course)

    So what does this actually mean for the resulting application? Because of the Composite relationship, auser will only be able to create newTopics beneath a Course, but will not be able to add existingTopics toa Course (if a Topic already exists, it mustalready have an owner, and therefore cannot be owned by thisCourse as well).

    Figure 11 : Composite relationships allow new entities to be added, but not existing ones

  • 8/14/2019 TrueView Application Developers Guide

    34/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 34

    Similarly, a user will notbe able to create newTopics beneath a Student (Studentsdont own Topics), buttheywillbe able to add existingTopics.

    Figure 12 : Aggregate relationships only allow existing entities to be added, but not new ones

  • 8/14/2019 TrueView Application Developers Guide

    35/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 35

    8 Adding actionsYou can add actions to your entities by adding public methods to them. For example, you might add aShowDoubleBookings() method to the Location class.

    All public methods for an entity will be shown as buttons in the UI. If the method doesnt accept any

    arguments, the button will show a green icon and can be invoked immediately:

    Figure 13 : Methods with no parameters can be invoked immediately

    8.1 Methods with parametersIf the method accepts arguments, the button will show a yellow icon. This icon will only turn greenafter the user has provided all of the parameters for the method. Parameters can be edited andmodified in the same way as normal properties:

    Figure 14 : Methods that need parameters will reveal a parameter editor

  • 8/14/2019 TrueView Application Developers Guide

    36/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 36

    Figure 15 : The button is activated when all parameters are provided

    Try to use methods that have zero parameterstheyre easier and quicker to use.8.2 Results from functions

    Any results returned from a method are automatically displayed to the end user. Entities (or lists ofentities) will appear in a new explorer window, whereas values are displayed in the message view.

    8.3 Static methodsOccasionally you may want users to invoke actions without having to create (or load) an entity first.

    You can do this usingstatic methods. As static methods are defined at a class level rather than an entity,

    users access them by right-clicking on the class within the Library pane.

    Figure 16 : Static methods are accessible from the Class Library

  • 8/14/2019 TrueView Application Developers Guide

    37/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 37

    9 Unit testing your codeAll unit tests require a mandatory initialisation step. Here is an example using NUnit:

    using Evolving.TrueView;using Evolving.TrueView.Domain;using NUnit.Framework;

    namespace StudentManagementUnitTests{

    [TestFixture]public class LinkingTests{

    [TestFixtureSetUp]public void Setup(){ MyApplication.Initialise();MyApplication.RegisterAssembly(typeof(Course).Assembly);}

    [Test]public void ShouldLinkAddressToSite(){

    Site site = new Site();Address address = new Address();

    // Link the entities:address.Site = site;

    Assert.AreEqual(site.Address, address);Assert.AreEqual(address.Site, site);

    }

    [Test]public void ShouldUnlinkAddressFromSite(){

    Site site = new Site();Address address = new Address();

    // Link the entities:address.Site = site;

    // And now unlink them:site.Address = null;

    Assert.IsNull(site.Address);Assert.IsNull(address.Site);

    }

    }

    This tells TrueView to parse the

    correct assembly

  • 8/14/2019 TrueView Application Developers Guide

    38/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 38

    10Enhancing the user interface10.1 Code comments really matter

    TrueView uses native code comments to provide active help to your end users.

    Comments are rendered beneath their respective properties. For other widgets on the screen, thecomments will appear as tool tips. The beauty of this feature is that the code and the documentationstay together. If the comments get out of sync, your users will let you know!

    TrueView will parse and render comments for the following code items:

    Classes Properties Methods and method parameters Enumerations and enumeration items

    Here is an example of how code comments are used:

    public class Course : Entity{

    /// /// A brief description of this Course/// virtual public string Description

    /// /// All Topics within this Course/// virtual public EntityList Topics

    }

    Figure 17 : Example of help comments

    Ensure that your Visual Studio project creates the XML documentation file on each build Comments should be targeted towards your end-users, so try to keep them concise

  • 8/14/2019 TrueView Application Developers Guide

    39/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 39

    10.2 Formatting primitive valuesEach type of primitive value can be formatted in different ways using attributes in theEvolving.TrueView.Domain.Attributes namespace (section 15 Attributes has a list of all available

    options).

    10.2.1 Text formattingpublic char NormalChar { }

    public string NormalText { }

    public string ReadOnlyText { get { } internal set { } }public string WriteOnlyText { internal get { } set { } }[Text(IsVisible = false)]public string HiddenText { }

    [Text(IsMultiLine = true)]public string MultiLineText { }

    [Text(IsPassword = true)]public string PasswordText { }

    [Text(MaxLength = 16)]public string TextWithMaximumSize { }

    [Text(EditMask = "(###)##-##-####")]public string EditMaskText { }

    Figure 18 : Examples of string formatting

  • 8/14/2019 TrueView Application Developers Guide

    40/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 40

    10.2.2 Date formattingpublic DateTime NormalDate { }

    [DateTime(CustomFormat = "T")]public DateTime TimeFormat { }

    [DateTime(CustomFormat = "D")]public DateTime DateFormat { }

    [DateTime(CustomFormat = "yyyy MMMM dd (dddd) h:mm tt")]public DateTime CustomDateFormat { }

    Figure 19 : Examples of Date formatting10.2.3 Boolean formatting

    public bool NormalBoolean { }

    [Boolean(TrueValue = "Clockwise", FalseValue = "Anti-clockwise")]public bool Orientation { }

    Figure 20 : Examples of Boolean formatting

  • 8/14/2019 TrueView Application Developers Guide

    41/86

  • 8/14/2019 TrueView Application Developers Guide

    42/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 42

    10.2.5 File and Folder paths[Path(DialogAppearance = PathAttribute.DialogType.None)]public string NormalPath { }

    [Path(DialogAppearance = PathAttribute.DialogType.OpenFile)]public string OpenFilePath { }

    [Path(DialogAppearance = PathAttribute.DialogType.SaveFile)]public string SaveFilePath { }

    [Path(DialogAppearance = PathAttribute.DialogType.FolderBrowser)]public string FolderPath { }

    [Path(DialogAppearance = PathAttribute.DialogType.OpenFile, IsImage = true)]public string ImagePath { }

    [Path(DialogAppearance = PathAttribute.DialogType.OpenFile,Filter = "DOC files|*.doc|All files (*.*)|*.*"))]public string FileWithFilter { }

    Figure 22 : Example of file paths

  • 8/14/2019 TrueView Application Developers Guide

    43/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 43

    10.3 Dynamic Drop-Down ListsUsers may find it easier to make selections using drop-down lists instead of using drag-and-drop. Thisfeature can be enabled for Entity properties.

    First, define a Query Specification that returns the items to display in the drop-down list:

    /// /// Returns Locations that a Lecture may be held at/// public class StudentCourseSpecification : IQuerySpecification{

    public IEntityList GetResults(Student sender){

    // We don't have a specific criteria to meet, so simply fetch all Courses:string hql = "From Course";IEntityList results = MyApplication.Load(hql, null);return results;

    }

    public Location GetResult(Course sender)

    public void Dispose()

    }

    Then modify the property to use the new filter class:

    public class Lecture : Entity{

    [Entity(LookupListFilter = typeof(LectureLocationSpecification))]virtual public Location Location{

    get { ... }set { ... }

    }

    }

    Restart the application, and you should see a drop-down list appear for the Course property:

    Figure 23 : Providing drop-down lists using IQuerySpecification

    The drop-down list uses the Summary value for each item. Ensure that the Summary value allowsusers to quickly and uniquely identify items within the list.

  • 8/14/2019 TrueView Application Developers Guide

    44/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 44

    10.4 Pre-filtered Search Query dialogsFor all Entity and EntityList properties, users can add or replace the contents using a pop-up SearchDialog:

    Figure 24 : Users can open search dialogs for the immediate property

    By default an empty search dialog will appear, so the user has to enter some search criteria. However,you can use a Query Specification to pre-load the results, making it quicker for users to choose the

    correct item.

    Define a Query Specification that will return the items to display:

    /// /// Returns Topics that are allowed for a given Student///

    public class StudentTopicSpecification : IQuerySpecification{

    public IEntityList GetResults(Student sender){if (sender.Course == null)

    return null;

    // Fetch only those Topics that belong to the Course that the Student is on:string hql = "From Topic As t Where t.Course=:course";Dictionary parameters = new Dictionary();parameters.Add("course", sender.Course);

    IEntityList results = MyApplication.Load(hql, parameters);return results;

    }

    public Location GetResult(Course sender)

    public void Dispose()

    }

  • 8/14/2019 TrueView Application Developers Guide

    45/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 45

    Then modify the property to use the new filter class:

    public class Student : Entity{

    [EntityList(Relationship = EntityListAttribute.RelationshipType.Aggregation,SearchQueryFilter=typeof(StudentTopicSpecification))]public virtual EntityList Topics{

    get { ... }set { ... }

    }

    }

    When users use the Add existing menu item, users will see a Search Dialog containing the results of

    the filter:

    Figure 25 : Users can choose from a pre-defined list, or run their own query

  • 8/14/2019 TrueView Application Developers Guide

    46/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 46

    10.5 Organising your propertiesBy default all properties are displayed in the order that they are defined within the code. If you want tochange the order of the properties, simply reposition the property within the code. Alternatively youmay use EntityClass.MemberDisplayOrder attribute:

    [EntityClass(MemberDisplayOrder = "ThirdProperty, SecondProperty, FirstProperty")]public class ExampleClass : Entity{

    public string FirstProperty { }

    public string SecondProperty { }

    public string ThirdProperty { }

    }

    Figure 26 : Properties presented in custom order

    You can also create groups of properties with different sub-headings using the Member.Categoryattribute. Any properties without a specific category are automatically assigned to a default categorycalled Main:

    public class ExampleClass : Entity{

    public string Property_1 { }

    public string Property_2 { }

    public string Property_3 { }

    [Property(Category = "Category B")]public string Property_B1 { }

    [Property(Category = "Category B")]public string Property_B2 { }

    [Property(Category = "Category B")]public string Property_B3 { }

    [Property(Category = "Reordered properties")]public string Property_C3 { }

    [Property(Category = "Reordered properties")]public string Property_C2 { }

    [Property(Category = "Reordered properties")]public string Property_C1 { }

    }

  • 8/14/2019 TrueView Application Developers Guide

    47/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 47

    Figure 27 : Use of the 'Category' attribute

  • 8/14/2019 TrueView Application Developers Guide

    48/86

  • 8/14/2019 TrueView Application Developers Guide

    49/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 49

    The next time you compile and run your application, you will see the new icons appear beside yourentities:

    Figure 28: Entities showing custom icons

    10.7 Colours and fontsYou may want to show some values using different colours or fonts based on some business logic.TrueView provides a simple way to achieve this.

    1) Implement the Evolving.TrueView.UI.IStylable interface on your entity class2) Modify the ApplyStyle() method to update the style for the appropriate member:public class Lecture : Entity, Evolving.TrueView.UI.IStylable {

    public void ApplyStyle(string memberName, Evolving.TrueView.UI.IStyleArgs memberStyle){

    switch (memberName){

    case "Name":break;

    case "Description":break;

    case "Duration":// Highlight if the lecture is long-running:if (this.Duration > 120)

    { memberStyle.ForeColour = System.Drawing.Colour.DarkRed; memberStyle.BackColour = System.Drawing.Colour.Yellow;}break;

    }}

    public void ApplyStyle(Evolving.TrueView.UI.IStyleArgs entityStyle){

    if (this.HasClashesWithOtherLectures()){ entityStyle.ForeColour = System.Drawing.Colour.White;entityStyle.BackColour = System.Drawing.Colour.Red;}

    }}

    Use the memberName to

    identify which member

    is being rendered

    This is used to apply a

    style to the entity itself

  • 8/14/2019 TrueView Application Developers Guide

    50/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 50

    10.8 Custom backgroundsYou can brand your TrueView application using a custom backdrop on the Workbench.

    Figure 29 : Workbench with a custom background

    1) Create your background image and save it in PNG format with the title Background.png2) Place the image in the same folder as your executable

    You can also use a custom splash logo when the application starts up:

    1) Create your splash image and save it in PNG format with the title ApplicationLogo.png2) Place the image in the same folder as your executable

  • 8/14/2019 TrueView Application Developers Guide

    51/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 51

    10.9 Custom WinFormsAlthough TrueView produces a consistent and powerful interface for your domain entities, there willbe situations where a truly customised UI is needed. TrueView lets you replace the default GUI with acustom GUI for any entity you wish.

    In this example youll create a custom WinForm for the Address entity:

    1) Add a new form to your project:

    2) Design your customised form:

  • 8/14/2019 TrueView Application Developers Guide

    52/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 52

    3) Modify your entity class to use the new form:public class Address : Entity, Evolving.TrueView.UI.ICustomForm{

    public System.Windows.Forms.Form GetCustomForm(){

    AddressForm form = new AddressForm();

    // Give the form the entity to work with:form.Address = this;

    // Return the form back to TrueView:return form;

    }

    }

    TrueView is unable to detect modifications to entities inside custom forms, so youll have toprovide the necessary logic to load, display, edit, and save entities.

    10.10User messagesAny exceptions, errors, warnings, or informational messages will appear in the System Messages View

    within the Workbench. You can write your own messages here using the .NET Trace object.

    Message Type Usage

    Informational System.Diagnostics.Trace.TraceInformation()

    Warning System.Diagnostics.Trace.TraceWarning()

    Error/Exception System.Diagnostics.Trace.TraceException()

    Figure 30 : Messages appearing in the System Messages View

    Here is an example of howits used:

    using System.Diagnostics.Trace;

    private void _Topics_AddItem(object sender, Topic item, OperationEventArgs args){

    if (this.Topics.Contains(item)){ Trace.TraceError(item.Name + " already belongs to " + this.Summary);}else{

    item.Course = this;Trace.TraceInformation(item.Name + " was added to " + this.Summary);}

    }

    Consider using the Trace object to keep your users informed of long running processes.

  • 8/14/2019 TrueView Application Developers Guide

    53/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 53

    10.10.1 Audit logsThe contents of the System Messages View are saved to log files within the users temporary directory.These files may be used for tracking issues in a live environment, or simply for understanding how yourapplications are being used.

    TrueView may prompt the user to send any errors to a support email address. This email address canbe configured within the app.config file:

    ...

    [email protected]

    ...

    The XML audit files are saved in a compressed format, but keep an eye on overall disk space usage.10.10.2 Custom Trace hooksIf you need to use a custom logging solution, you can hook into the Trace events that TrueViewprovides. Here are the steps:

    1. Setup the handler to intercept all Trace messages:MyApplication.OnTrace += new MyApplication.OnTraceEventHandler(MyApplication_OnTrace);

    2. Add your custom code to deal with the event:Using Evolving.TrueView.Auditing;using Microsoft.Practices.EnterpriseLibrary.Logging;

    void MyApplication_OnTrace(object sender, TraceMessage traceMessage){

    Logger.Write(string.Format(traceMessage.format, traceMessage.args));}

    Change this to send logs

    to another address

  • 8/14/2019 TrueView Application Developers Guide

    54/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 54

    11Factories, Repositories, and Services11.1 Factory classesInstead of using multiple public constructors on your entity classes, you can encapsulate the creationinto a completely separate factory class:

    using Evolving.TrueView.Domain;

    public class CourseFactory : IFactory{

    IServiceLocator IServiceDependent.ServiceLocator { get; set; }

    /// /// Creates a new Course/// /// public Course CreateNew(){

    return new Course();}

    /// /// Creates a new Course with 5 empty Topics/// /// public Course CreateWithEmptyTopics(){

    Course newCourse = new Course();newCourse.Name = "New Course";

    for (int i = 0; i < 5; i++){

    Topic newTopic = new Topic(c);newTopic.Name = "Empty topic " + i.ToString();

    newCourse.Topics.Add(t);}

    return newCourse;}

    }

    Users will see these methods when they right-click on the class within the Library pane:

    Figure 31 : Accessing Factory methods from the Library pane

    Consider using Factories when users need to create entities with different configurations.

    Use the IFactory interface

    to define factory classes

    Additional methods are made

    available to the user

    This is used for accessing the

    ServiceLocator (described later)

  • 8/14/2019 TrueView Application Developers Guide

    55/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 55

    11.2 Repository classesIn a similar fashion to Factory classes, any logic that queries the persistence store can be encapsulatedin a separate repository class:

    /// /// A repository for Course entities.

    /// public class CourseRepository : IRepository{

    IServiceLocator IServiceDependent.ServiceLocator { get; set; }

    /// /// Finds all Courses that contain the word 'Science'/// /// [Method(IsThreadSafe = false)]public IEntityList FindAllScienceCourses(){

    string query = "From Course As c Where c.Name like :name";Dictionary values = new Dictionary();values.Add("name", "%Science%");

    bool showResultsInUI = true;return Evolving.TrueView.MyApplication.Load(query, values, showResultsInUI);

    }

    }

    TrueView will expose public methods that can be seen by right-clicking on the class within the Library

    pane:

    Figure 32 : Accessing Repository methods from the Library pane

    Use Repositories when you need to supply many pre-defined queries to your users.

    Use IRepository interface to

    define Repository classes

  • 8/14/2019 TrueView Application Developers Guide

    56/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 56

    11.3 Service classesSome operations dont comfortably sit within any one Entityseveral entities may be needed for theoperation to make sense. In these cases, use a Service class to expose the actions:

    /// /// A set of actions for booking available rooms & locations

    /// public class RoomBookingService : IService{

    public IServiceLocator ServiceLocator { get; set; }

    /// /// Book a room for a given Lecture/// /// /// public void Book(Lecture lecture, Location location){

    ...}

    }

    Notice that he interface doesnt accept a generic parameter, because no single entity owns the actions.All public methods within this class will be presented in the Class Library under the Services node:

    Figure 33 : Accessing Service methods from the Library pane

    Use Services when actions/methods cannot be associated with a single Entity class.

    Use IService interface to define

    Service classes

  • 8/14/2019 TrueView Application Developers Guide

    57/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 57

    12Dependency Injection & the Service LocatorAs your domain models become richer and more expressive, you will need to access other factories,repositories, or services from within your entities.

    To help you access these easily, TrueView uses dependency injection to pass a Service Locator to each

    Entity object. The Service Locator can then be used to access any of the dependencies:

    public virtual void ShowLectures(string nameMatch){

    ICourseRepository courseRepository =(ICourseRepository)this.ServiceLocator.GetRepositoryFor();

    courseRepository.FindAllCoursesCalled(nameMatch);}

    We used a ServiceLocator to reduce clutter in the Entities. This may not be to everyones taste,so refer to 20 Advanced development: Injecting your own dependenciesto implement your own

    mechanism

    12.1 Choosing from different dependency implementations You can use the MyApplication.ApplicationInitialised event to choose a preferred dependency.This example shows how to choose the factory used for all Course entities:

    static class Program{

    /// /// The main entry point for the application.///

    [STAThread]static void Main(){

    Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);

    MyApplication.ApplicationInitialised += new EventHandler(ApplicationInitialised);Application.Run(MyApplication.Workbench);

    }

    static void ApplicationInitialised(object sender, EventArgs e){ MyApplication.ServiceLocator.SetRepositoryFor(new CourseRepository());}

    }

    You can do this for all Factory, Repository, and Service classes.

    The ServiceLocator automatically creates a single instance of each Factory, Repository, and Serviceclass, and keeps them for the lifetime of the application. Ensure that the class has a default publicconstructor.

  • 8/14/2019 TrueView Application Developers Guide

    58/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 58

    13Entity Persistence13.1 Object Relational Mapping

    TrueView handles all data persistence using a third-party Object Relational Mapper (ORM). Currently itusesNHibernate, a popular and powerful ORM designed for .NET. ORMs can be a deep subject, andare only covered lightly within this guide. Fortunately TrueView makes the learning curve extremelylow, allowing you to get started very quickly.

    Here are some of the main features that an ORM provides:

    Keep persistence code separate from your domain logic Lazy-loading prevents entire object graphs being read into memory Allows you to focus on the domain logic

    13.2 Mapping filesNHibernate uses a set of mapping files to know how to load and save your entities to a database. Westrongly suggest using the DataBridge utility to create these files, as it can generate them (and database

    creation scripts) in seconds. If you want to create these files manually, refer to the sample mappingfiles in section 16 Sample NHibernate mapping files.

    13.3 Virtual methods All non-private members within your domain classes must be marked as virtual. This allowsNHibernate to intercept access to the members and perform the necessary database operations. Dont

    worry if you initially forget to do this warning messages will appear the next time you run theapplication.

    13.4 Variable naming standardsPrivate field names must use one naming strategy known to NHibernate. These are:

    Naming strategy Example

    Camel Case The property FirstName uses the private field firstName

    Underscore camel case The property FirstName uses the private field _firstName

    Underscore lowercase The property FirstName uses the private field _firstname

    Underscore Pascal case The property FirstName uses the private field _FirstName

    m underscore Pascal case The property FirstName uses the private field m_FirstName

    private string m_FirstName;virtual public string FirstName(){

    get { return m_FirstName; }set { m_FirstName = value; }

    }

    private string fName;virtual public string FirstName(){

    get { return fName; }set { fName = value; }}

    GOOD the field name

    uses a known standard

    BAD the field naming

    style is unknown

  • 8/14/2019 TrueView Application Developers Guide

    59/86

  • 8/14/2019 TrueView Application Developers Guide

    60/86

  • 8/14/2019 TrueView Application Developers Guide

    61/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 61

    13.10Quick start: Enabling database persistence for your application This section will require database administration skills

    1) Make sure youve followed the coding rules (from earlier) for all of your entities2) Create a folder called HBM within your project (this is where the NHibernate mapping files will

    go)

    3) Build you project to create an assembly file4) Run the DataBridge tool5) Set the Assembly File Path to the location of your domain entity assembly6) Set the Output File Location to the HBM folder you just created7) ClickGenerate mapping files8) ClickGenerate SQL script If you hit any errors during this process, correct your domain entities and try again.

  • 8/14/2019 TrueView Application Developers Guide

    62/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 62

    Figure 34 : The DataBridge utility

    At this stage the HBM folder should have a set of mapping files within it. The next step is to create thedatabase and to enable persistence within your assembly:

    1) Create an empty database using SQL Server2) Find the SQL script within the HBM folder and execute it against the empty database3) Add all of the .hbm files to the HBM folder and set each files Build Action to Embedded

    Resource

  • 8/14/2019 TrueView Application Developers Guide

    63/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 63

    4) Add the following settings to your project:

    Modify the connection string to use your own server, database, and user credentials.

    5) Rebuild your projectRun your application again, and it will use your newly created database.

    The value in PersistenceProviderData contains a NHibernate specific configuration. Refer to theNHibernate documentation to find other settings that you may wish to use.

  • 8/14/2019 TrueView Application Developers Guide

    64/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 64

    14Reports TrueView uses Microsoft Reporting Services to generate and display reports. The steps to create a

    report are as follows:

    1. Add the Microsoft.ReportViewer.Common and Microsoft.ReportViewer.WinForms assemblies toyour application:

    2. Add a newReport (.rdlc extension) to your assembly:

  • 8/14/2019 TrueView Application Developers Guide

    65/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 65

    3. Add a Data Source for the entities that your report will contain:

  • 8/14/2019 TrueView Application Developers Guide

    66/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 66

    4. Design the report to your specification using the data source created in the previous step:

    5. Finally you can add the code to use the report. For this example, add a static method togenerate a report of all known Sites:

    using Evolving.TrueView;using Evolving.TrueView.Printing;public class Site : Entity{

    static public Report ShowAllSites(){

    // Fetch all Sites (we don't need any parameters):string hql = "Select from Site";Dictionary parameters = new Dictionary();IEntityList sites = MyApplication.Load(hql, parameters);

    // Specify the location of the embedded report:Report rpt = new Report("StudentManagement.Reports.AllSites.rdlc");// Provide the report data:rpt.DataSources.Add("StudentManagement_Site", sites);return rpt;

    }

    }

    All done! Users can select the Show All Sites option from the Site class, and the report will bedisplayed.

    The data-source name

    can be found inside the

    report definition.

  • 8/14/2019 TrueView Application Developers Guide

    67/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 67

    15Attributes As you have already gathered, TrueViews various behaviours are controlled through the use ofAttributes. The remaining sections in this chapter describe the different types of attributes, what theycan be applied to, and their various behaviours.

    Figure 35 : Attribute inheritance diagram

  • 8/14/2019 TrueView Application Developers Guide

    68/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 68

    15.1 Attribute descriptions15.1.1 AbstractAttribute

    This attribute can be applied to anyEntity class or member.

    Property Type Default Description

    Name string An alternative class name to display to the user

    IsVisible bool True Determines if the entity is visible to the end user

    15.1.2 EntityClassAttributeThis attribute can be applied to anyEntity or EntityList class.

    Property Type Default Description

    IsCreatable bool True Determines if the entity can be created by the end user

    IsLazyLoaded bool True Determines whether all non-value properties are loaded when

    explicitly requested by the user. Note that this only takes effect onproperties that contain Entities or EntityLists.

    If set to FALSE, all entity/list properties are eager-loaded.

    IsCached bool False Determines whether the entity remains in memory for the lifetimeof the session.

    Use this with entities that are highly requested and immutable.

    HiddenMembers string A comma delimited list of members that should not be displayed tothe end user

    HideAllProperties bool False Determines whether all Properties are hidden from the end user

    HideAllMethods bool False Determines whether all Methods are hidden from the end user

    IsMutable bool True Determines whether the persistant Entity can be modified

    IsThreadSafe bool True Determines whether access to this member can be executed on aseparate thread.

    Set this value to FALSE if the Entity accesses a resource that is notthread safe (e.g. Windows controls).

    MemberDisplayOrder string A comma delimited list of members in the order they should bedisplayed to the end user

    15.1.3 MemberAttributeThe attribute can be applied to anyproperty or method.

    Property Type Default Description

    Category string The category under which this member will appear

    IsThreadSafe bool True Determines whether access to this member can be executed on aseparate thread. Set this value to FALSE if the member accesses aresource that is not thread safe (e.g. Windows controls).

    RequiresConfirmation bool True Determines if the user is prompted when changing or invoking thismember

  • 8/14/2019 TrueView Application Developers Guide

    69/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 69

    15.1.4 PropertyAttributeThe attribute can be applied to anyproperty.

    Property Type Default Description

    BackingField String The name of the private backing field of the property.CanRead bool True Determines if the value can be read in the UI.

    This is usually used to override the scope of the Property.

    CanWrite bool True Determines if the value can be updated in the UI.

    This is usually used to override the scope of the Property.

    CanPersist bool True Determines whether the property value can be saved to theunderlying persistence store.

    Any property that isn't persisted should set this value as False.

    IsGeneratedBy_PersistenceStore

    bool False Determines whether this property is generated by the persistencestore (eg auto-incrementing or computed values). This will alsomark the property as read-only.

    UseOptimisticLock bool True Determines if optimistic locking is use on the parent Entity whenthis property is modified.

    WriteOnce bool False Determines if the Property can be modified only once (forinitialisation purposes).

    This is similar to the "ReadOnly" variable declaration.

    15.1.5 AbstractEntityAttributeThis attribute can be applied to anyproperty that is an Entity or EntityList.

    Property Type Default Description

    CanCreate Determines if entities can be created and set directly in theproperty via the UI.

    CanModifyContents bool True Determines whether the user is allowed to modify the property'scontents. A value of FALSE means that the properties contentsmust be edited from another Entity Root.

    This supports the "Aggregate Root" constraint in DDD.

    IsLazyLoaded bool True Determines if the property contents should be loaded from thepersistence store on first access. Setting the value to FALSE willforce the value to be loaded at the same time as the parent entity.

    SearchQueryFilter Type Refers to an IQuerySpecification class that returns a list ofEntities to pre-populate the Search Results dialog, specifically usingAdd existing or Replace with existing context menu items.

    15.1.6 EntityAttributeThis attribute can be applied to anyEntity property.

    Property Type Default Description

    LookupListFilter Type Refers to an IQuerySpecification class that returns a list ofEntities to populate a lookup (drop-down) list.

    Relationship RelationshipType Aggregation Determines how add/remove operations are handled within the UI.

    Aggregation, Association, and Parent only allow existingentities to be linked to the property.

    Composition and Component allows new entities to be createdand linked to the property.

    Component is persistence related, and means that the entity is

  • 8/14/2019 TrueView Application Developers Guide

    70/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 70

    eager-loaded (as opposed to lazy-loaded).

    15.1.7 EntityListAttributeThis attribute can be applied to anyEntityList property.

    Property Type Default Description

    CanAdd bool Determines if entities may be added to the EntityList by the enduser. Use this to prevent entities being added in the wrongoperational context.

    CanRemove bool Determines if entities may be removed from the EntityList by theend user. Use this to prevent entities being removed in the wrongoperational context.

    Relationship RelationshipType Aggregation Determines how add and remove operations are handled within theUI.

    Aggregation imposes no restrictions on how entities are added orremoved from the list.

    Composition prevents existing entities from being added to the

    list (an existing entity should already be owned by another entity)

    HasUniqueItems bool True Determines if the EntityList should only contain unique items

    15.1.8 DateTimeAttributeThis attribute can be applied to anyDateTime property.

    Property Type Default Description

    CustomFormat bool True The format to be used to display the date value.

    This value also supports the patterns fromSystem.Globalization.DateTimeFormatInfo.

    15.1.9 BooleanAttributeThis attribute can be applied to any Boolean property. This attribute allows the TRUE and FALSEvalues to be overridden with custom text values.

    Property Type Default Description

    TrueValue string Yes The textual value that represents TRUE

    FalseValue string No The textual value that represents FALSE

    15.1.10 StringAttributeThis attribute can be applied to anyString property.

    Property Type Default Description

    MinLength int 0 The minimum length of the string

    MaxLength int 80 The maximum length of the string

    15.1.11 TextAttributeThis attribute can be applied to anyString property.

    Property Type Default Description

    IsMultiLine bool True Determines if the string is rendered over multiple lines. Useful for

    large string values (e.g. notes)

  • 8/14/2019 TrueView Application Developers Guide

    71/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 71

    IsRichText bool True Determines if the string is displayed within a Rich Text editor. Thisallows basic formatting to be embedded within the string value.

    IsPassword bool True Determines if the string is shown as a series of asterisks

    EditMask bool False Specifies the mask to use when edited by the end user. The formatis the same as that used by the

    System.Windows.Forms.MaskedTextBox control.

    15.1.12 PathAttributeThis attribute can be applied to anyString property that represents a file or a path.

    Property Type Default Description

    MaxLength int 260 The maximum length of the string

    DialogAppearance DialogType None Determines what type of Dialog box should be used when this valueis edited in the UI.

    Possible values are None, OpenFile, SaveFile, and FolderBrowser

    IsImage bool False Determines if the file is an image, and displays the image in the UI

    (instead of the filepath). The image format may be one of thefollowing: BMP, JPG, GIF, PNG, TIF, WMF, or EMF.

    DefaultExtension string The default extension to be used for saving files. This can be used incombination with a DialogAppearance of SaveFile.

    Filter string The filter string to be used in the file dialog. The format is the sameas that used by the System.Windows.Forms.FileDialog control

  • 8/14/2019 TrueView Application Developers Guide

    72/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 72

    16Sample NHibernate mapping filesThis section shows a few sample NHibernate mapping files generated by the DataBridge utility.

    16.1 Simple entityStudentManagement.Address.hbm.xml

    16.2 Entity with One-To-Many relationshipStudentManagement.Site.hbm.xml

  • 8/14/2019 TrueView Application Developers Guide

    73/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 73

    16.3 Entities with Many-To-Many relationshipsStudentManagement.Student.hbm.xml

  • 8/14/2019 TrueView Application Developers Guide

    74/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 74

    StudentManagement.Topic.hbm.xml

  • 8/14/2019 TrueView Application Developers Guide

    75/86

    TrueView Application Developers Guide

    2009 Evolving Software Ltd Page 75

    17Advanced development: Custom base classesThere may be caseswhen you cant inherit from the default Entity and EntityList base classes (forinstance, you might need to inherit from classes in another framework).

    For your entity clas