# XpoBuilderGenerator - Introduction

A generator that helps you using the builder pattern with XPO Objects when dealing with complicated object models and UnitTests.

# Intent

When writing XPO/XAF code we need to deal object creation all the time. Most of the time this is an easy task by using ObjectSpace.CreateObject<T>() or just creating the class manually by using the constructor new MyBusinessObject(session). When the business model grows and the internals of the class structure we can use the BuilderPattern (opens new window) to decouple the creation of (complex) objects from the actual domain logic and reduce possible bugs when requirements change over time. This may often result in a works here, but not here scenario. With the flexibility XAF provides, this can lead to hard to grasp bugs. Writing the builder code can be tedious and error prone. This source generator tries to minimize this weakness.

# Usage





 













 













using DevExpress.Xpo;

namespace Acme.Module
{
    [Xenial.XenialXpoBuilder]
    public class Person : XPObject
    {
        public Person(Session session) : base(session) { }

        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person Manager { get; set; }

        [Association]
        public XPCollection<Task> Tasks => GetCollection<Task>(nameof(Tasks));
    }

    [Xenial.XenialXpoBuilder]
    public class Task : XPObject
    {
        public Task(Session session) : base(session) { }

        [Association]
        public Person Person { get; set; }
    
        public string Description { get; set; }
    
        public TimeSpan Duration { get; set; }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# Generated-Code

// <auto-generated />

using System;
using System.Runtime.CompilerServices;

namespace Acme.Module.BusinessObjects
{
    [CompilerGenerated]
    internal partial class PersonBuilder : PersonBuilder<Acme.Module.BusinessObjects.Person, PersonBuilder> { }
    
    [CompilerGenerated]
    internal abstract partial class PersonBuilder<TClass, TBuilder>
        where TClass : Acme.Module.BusinessObjects.Person
        where TBuilder : PersonBuilder<TClass, TBuilder>
    {
        protected DevExpress.Xpo.Session Session { get; set; }
        protected bool WasSessionSet { get; private set; }
        
        public TBuilder WithSession(DevExpress.Xpo.Session session)
        {
            this.Session = session;
            this.WasSessionSet = true;
            return This;
        }
        
        protected DevExpress.ExpressApp.IObjectSpace ObjectSpace { get; set; }
        protected bool WasObjectSpaceSet { get; private set; }
        
        public TBuilder WithObjectSpace(DevExpress.ExpressApp.IObjectSpace objectSpace)
        {
            this.ObjectSpace = objectSpace;
            this.WasObjectSpaceSet = true;
            return This;
        }
        
        protected TBuilder This
        {
            get
            {
                return (TBuilder)this;
            }
        }
        
        protected virtual TClass CreateTarget()
        {
            if(this.WasObjectSpaceSet)
            {
                return this.ObjectSpace.CreateObject<TClass>();
            }
            
            if(this.WasSessionSet)
            {
                return (TClass)new Acme.Module.BusinessObjects.Person(this.Session);
            }
            
            throw new System.InvalidOperationException($"Could not create instance of type [Acme.Module.BusinessObjects.Person] without a Session or ObjectSpace.{System.Environment.NewLine}Make sure to use the [WithSession] or [WithObjectSpace] methods when using the [{this.GetType().FullName}] type.");
        }
        
        protected string FirstName { get; set; }
        protected bool WasFirstNameCalled { get; private set; }
        
        public TBuilder WithFirstName(string firstName)
        {
            this.FirstName = firstName;
            this.WasFirstNameCalled = true;
            return This;
        }
        
        protected string LastName { get; set; }
        protected bool WasLastNameCalled { get; private set; }
        
        public TBuilder WithLastName(string lastName)
        {
            this.LastName = lastName;
            this.WasLastNameCalled = true;
            return This;
        }
        
        protected Acme.Module.BusinessObjects.Person Manager { get; set; }
        protected bool WasManagerCalled { get; private set; }
        
        public TBuilder WithManager(Acme.Module.BusinessObjects.Person manager)
        {
            this.Manager = manager;
            this.WasManagerCalled = true;
            return This;
        }
        
        protected Acme.Module.BusinessObjects.PersonBuilder ManagerBuilder { get; set; }
        protected bool WasManagerBuilderCalled { get; private set; }
        
        public TBuilder WithManager(Action<Acme.Module.BusinessObjects.PersonBuilder> managerBuilder)
        {
            if(managerBuilder != null)
            {
                Acme.Module.BusinessObjects.PersonBuilder builder = new Acme.Module.BusinessObjects.PersonBuilder();
                this.WithManager(builder);
                managerBuilder.Invoke(builder);
            }
            return This;
        }
        
        public TBuilder WithManager(Acme.Module.BusinessObjects.PersonBuilder managerBuilder)
        {
            this.ManagerBuilder = managerBuilder;
            this.WasManagerBuilderCalled = true;
            if(this.WasSessionSet)
            {
                this.ManagerBuilder.WithSession(this.Session);
            }
            if(this.WasObjectSpaceSet)
            {
                this.ManagerBuilder.WithObjectSpace(this.ObjectSpace);
            }
            return This;
        }
        
        private System.Collections.Generic.IList<Acme.Module.BusinessObjects.TaskBuilder> _TasksBuildersCollection = new System.Collections.Generic.List<Acme.Module.BusinessObjects.TaskBuilder>();
        protected System.Collections.Generic.IList<Acme.Module.BusinessObjects.TaskBuilder> TasksBuildersCollection { get { return _TasksBuildersCollection; } }
        
        public TBuilder WithTasks(Action<Acme.Module.BusinessObjects.TaskBuilder> tasksBuilder)
        {
            if(tasksBuilder != null)
            {
                Acme.Module.BusinessObjects.TaskBuilder builder = new Acme.Module.BusinessObjects.TaskBuilder();
                this.WithTasks(builder);
                tasksBuilder.Invoke(builder);
            }
            return This;
        }
        
        public TBuilder WithTasks(Acme.Module.BusinessObjects.TaskBuilder tasks)
        {
            if(this.WasSessionSet)
            {
                tasks.WithSession(this.Session);
            }
            if(this.WasObjectSpaceSet)
            {
                tasks.WithObjectSpace(this.ObjectSpace);
            }
            this.TasksBuildersCollection.Add(tasks);
            return This;
        }
        
        private System.Collections.Generic.IList<Acme.Module.BusinessObjects.Task> _TasksCollection = new System.Collections.Generic.List<Acme.Module.BusinessObjects.Task>();
        protected System.Collections.Generic.IList<Acme.Module.BusinessObjects.Task> TasksCollection { get { return _TasksCollection; } }
        
        public TBuilder WithTasks(Acme.Module.BusinessObjects.Task tasks)
        {
            this.TasksCollection.Add(tasks);
            return This;
        }
        
        public virtual TClass Build()
        {
            TClass target = this.CreateTarget();
            
            if(this.WasFirstNameCalled)
            {
                target.FirstName = this.FirstName;
            }
            
            if(this.WasLastNameCalled)
            {
                target.LastName = this.LastName;
            }
            
            if(this.WasManagerBuilderCalled)
            {
                this.WithManager(this.ManagerBuilder.Build());
            }
            
            if(this.WasManagerCalled)
            {
                target.Manager = this.Manager;
            }
            
            foreach(Acme.Module.BusinessObjects.TaskBuilder item in this.TasksBuildersCollection)
            {
                this.WithTasks(item.Build());
            }
            
            foreach(Acme.Module.BusinessObjects.Task item in this.TasksCollection)
            {
                target.Tasks.Add(item);
            }
            
            return target;
        }
    }

    [CompilerGenerated]
    internal partial class TaskBuilder : TaskBuilder<Acme.Module.BusinessObjects.Task, TaskBuilder> { }
    
    [CompilerGenerated]
    internal abstract partial class TaskBuilder<TClass, TBuilder>
        where TClass : Acme.Module.BusinessObjects.Task
        where TBuilder : TaskBuilder<TClass, TBuilder>
    {
        protected DevExpress.Xpo.Session Session { get; set; }
        protected bool WasSessionSet { get; private set; }
        
        public TBuilder WithSession(DevExpress.Xpo.Session session)
        {
            this.Session = session;
            this.WasSessionSet = true;
            return This;
        }
        
        protected DevExpress.ExpressApp.IObjectSpace ObjectSpace { get; set; }
        protected bool WasObjectSpaceSet { get; private set; }
        
        public TBuilder WithObjectSpace(DevExpress.ExpressApp.IObjectSpace objectSpace)
        {
            this.ObjectSpace = objectSpace;
            this.WasObjectSpaceSet = true;
            return This;
        }
        
        protected TBuilder This
        {
            get
            {
                return (TBuilder)this;
            }
        }
        
        protected virtual TClass CreateTarget()
        {
            if(this.WasObjectSpaceSet)
            {
                return this.ObjectSpace.CreateObject<TClass>();
            }
            
            if(this.WasSessionSet)
            {
                return (TClass)new Acme.Module.BusinessObjects.Task(this.Session);
            }
            
            throw new System.InvalidOperationException($"Could not create instance of type [Acme.Module.BusinessObjects.Task] without a Session or ObjectSpace.{System.Environment.NewLine}Make sure to use the [WithSession] or [WithObjectSpace] methods when using the [{this.GetType().FullName}] type.");
        }
        
        protected Acme.Module.BusinessObjects.Person Person { get; set; }
        protected bool WasPersonCalled { get; private set; }
        
        public TBuilder WithPerson(Acme.Module.BusinessObjects.Person person)
        {
            this.Person = person;
            this.WasPersonCalled = true;
            return This;
        }
        
        protected Acme.Module.BusinessObjects.PersonBuilder PersonBuilder { get; set; }
        protected bool WasPersonBuilderCalled { get; private set; }
        
        public TBuilder WithPerson(Action<Acme.Module.BusinessObjects.PersonBuilder> personBuilder)
        {
            if(personBuilder != null)
            {
                Acme.Module.BusinessObjects.PersonBuilder builder = new Acme.Module.BusinessObjects.PersonBuilder();
                this.WithPerson(builder);
                personBuilder.Invoke(builder);
            }
            return This;
        }
        
        public TBuilder WithPerson(Acme.Module.BusinessObjects.PersonBuilder personBuilder)
        {
            this.PersonBuilder = personBuilder;
            this.WasPersonBuilderCalled = true;
            if(this.WasSessionSet)
            {
                this.PersonBuilder.WithSession(this.Session);
            }
            if(this.WasObjectSpaceSet)
            {
                this.PersonBuilder.WithObjectSpace(this.ObjectSpace);
            }
            return This;
        }
        
        protected string Description { get; set; }
        protected bool WasDescriptionCalled { get; private set; }
        
        public TBuilder WithDescription(string description)
        {
            this.Description = description;
            this.WasDescriptionCalled = true;
            return This;
        }
        
        protected System.TimeSpan Duration { get; set; }
        protected bool WasDurationCalled { get; private set; }
        
        public TBuilder WithDuration(System.TimeSpan duration)
        {
            this.Duration = duration;
            this.WasDurationCalled = true;
            return This;
        }
        
        public virtual TClass Build()
        {
            TClass target = this.CreateTarget();
            
            if(this.WasPersonBuilderCalled)
            {
                this.WithPerson(this.PersonBuilder.Build());
            }
            
            if(this.WasPersonCalled)
            {
                target.Person = this.Person;
            }
            
            if(this.WasDescriptionCalled)
            {
                target.Description = this.Description;
            }
            
            if(this.WasDurationCalled)
            {
                target.Duration = this.Duration;
            }
            
            return target;
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

# Advantage

  • Centralized creation of complex business objects
  • Deferred/Lazy execution (until Build is called, everything is held in memory)
  • Improved maintainability
  • Code is less prone to errors
  • Will follow inheritance

# Drawbacks/Issues

  • We need attributes on the target classes to work, yet
  • No custom naming conventions, yet
  • No good interception points, yet
  • No custom validation, yet
  • No way to configure the visibility of the builder, yet
  • Due to compiler limitations we need to create generic types, hence edit & continue / HotReload may be impossible
  • No automatic generation of IBuilder<T> interfaces, yet

# API-surface

A class marked with the Xenial.XenialXpoBuilder will follow the rules:

  • All public properties of the target type will be generate a corresponding WithXXX method
    • If the parent type also defines an Xenial.XenialXpoBuilder attribute, it will follow the inheritance, so duplicated code will be avoided
    • If a property is an object that defines an Xenial.XenialXpoBuilder attribute additional code for automatic passing the Session/ObjectSpace to the child builder
    • If a property is an object that defines an Xenial.XenialXpoBuilder attribute additional code that accepts the concrete builder will be generated
    • If a property is an object that defines an Xenial.XenialXpoBuilder attribute additional code that accepts an Action<TBuilder> will be generated (so you don't need to create the builder by hand)
    • If a property is a collection type System.Collections.ICollection/System.Collections.IList it will follow the same rules as an object, but will collect them accordingly
    • All properties that define an DevExpress.Xpo.KeyAttribute which is autogenerated, will be omitted

# Usage-Demo

using System;

using Acme.Module.BusinessObjects;

using DevExpress.Xpo;

using static Acme.Module.Helpers.DemoHelper;

var session = CreateSession();

var person = new PersonBuilder()
    .WithSession(session)
    .WithFirstName("John")
    .WithLastName("Doe")

    .WithManager(new PersonBuilder()
            .WithFirstName("Mary")
            .WithLastName("Major")

    ).WithTasks(new TaskBuilder()
        .WithDescription("Install Xenial.Framework")
        .WithDuration(TimeSpan.FromSeconds(30))

    ).WithTasks(new TaskBuilder()
        .WithDescription("Use Xenial.Framework.Generators")
        .WithDuration(TimeSpan.FromSeconds(10))

    ).Build();

session.Save(person);

WriteXPObjectToConsole(person);
/*
{
  "FirstName": "John",
  "LastName": "Doe",
  "Manager": {
    "FirstName": "Mary",
    "LastName": "Major",
    "Manager": null,
    "Tasks": [],
    "Oid": 1
  },
  "Tasks": [
    {
      "Description": "Use Xenial.Framework.Generators",
      "Duration": "00:00:10",
      "Oid": 2
    },
    {
      "Description": "Install Xenial.Framework",
      "Duration": "00:00:30",
      "Oid": 1
    }
  ],
  "Oid": 2
}
*/

var manuel = new ManuelGrundnerPersonBuilder(session)
    .WithManager(person)
    .Build();

session.Save(manuel);

WriteXPObjectToConsole(manuel);
/*
{
  "FirstName": "Manuel",
  "LastName": "Grundner",
  "Manager": {
    "FirstName": "John",
    "LastName": "Doe",
    "Manager": {
      "FirstName": "Mary",
      "LastName": "Major",
      "Manager": null,
      "Tasks": [],
      "Oid": 1
    },
    "Tasks": [
      {
        "Description": "Use Xenial.Framework.Generators",
        "Duration": "00:00:10",
        "Oid": 2
      },
      {
        "Description": "Install Xenial.Framework",
        "Duration": "00:00:30",
        "Oid": 1
      }
    ],
    "Oid": 2
  },
  "Tasks": [
    {
      "Description": "Implement SourceGenerators",
      "Duration": "10675199.02:48:05.4775807",
      "Oid": 3
    },
    {
      "Description": "Test SourceGenerators",
      "Duration": "10675199.02:48:05.4775807",
      "Oid": 4
    },
    {
      "Description": "Deploy SourceGenerators",
      "Duration": "10675199.02:48:05.4775807",
      "Oid": 5
    }
  ],
  "Oid": 3
}
*/

Console.ReadLine();

internal class ManuelGrundnerPersonBuilder : PersonBuilder
{
    public ManuelGrundnerPersonBuilder(Session session)
    {
        WithSession(session);
        WithFirstName("Manuel");
        WithLastName("Grundner");
        WithTasks(b => b
            .WithDescription("Implement SourceGenerators")
            .WithDuration(TimeSpan.MaxValue)
        );
        WithTasks(b => b
            .WithDescription("Test SourceGenerators")
            .WithDuration(TimeSpan.MaxValue)
        );
        WithTasks(b => b
            .WithDescription("Deploy SourceGenerators")
            .WithDuration(TimeSpan.MaxValue)
        );
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

# Options

# MSBuild

  • <GenerateXenialXpoBuilderAttribute> - Control if XenialXpoBuilderAttribute will be emitted
  • <XenialAttributesVisibility> (global) - Control's XenialXpoBuilderAttribute visibility modifier (public/internal)
  • <EmitCompilerGeneratedFiles> (global) - Code will be flushed to disk (debug)
  • <XenialDebugSourceGenerators> (global) - Debugger will launch on code generation (debug)

# Code

None.

CAUTION

When updating from an older Xenial to a newer Xenial version, it's necessary to restart VisualStudio/VSCode after the upgrade, so Intellisense can reload the new SourceGenerator. So it may come to false positive warnings if they don't match.

# Diagnostics

ID Severity Message Reason
XENGEN0010 Error Could not parse boolean MSBUILD variable <GenerateXenialXpoBuilderAttribute> MsBuild variable needs to be in boolean parsable format: true/false/True/False
XENGEN0101 Error The class using the [XenialXpoBuilderAttribute] needs to be in a namespace We can not generate code in the global namespace

# Demo-Source

You can find demo sources in the Xenial.Framework repository for in depth usage information.