forked from extnet/Ext.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.cs
More file actions
670 lines (620 loc) · 22.6 KB
/
Model.cs
File metadata and controls
670 lines (620 loc) · 22.6 KB
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/********
* @version : 2.1.1 - Ext.NET Pro License
* @author : Ext.NET, Inc. http://www.ext.net/
* @date : 2012-12-10
* @copyright : Copyright (c) 2007-2012, Ext.NET, Inc. (http://www.ext.net/). All rights reserved.
* @license : See license.txt and http://www.ext.net/license/.
********/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using Ext.Net.Utilities;
using Newtonsoft.Json.Linq;
namespace Ext.Net
{
/// <summary>
/// A Model represents some object that your application manages. For example, one might define a Model for Users, Products, Cars, or any other real-world object that we want to model in the system. Models are registered via the model manager, and are used by stores, which are in turn used by many of the data-bound components in Ext.
///
/// Models are defined as a set of fields and any arbitrary methods and properties relevant to the model. For example:
///
/// Ext.regModel('User', {
/// fields: [
/// {name: 'name', type: 'string'},
/// {name: 'age', type: 'int'},
/// {name: 'phone', type: 'string'},
/// {name: 'alive', type: 'boolean', defaultValue: true}
/// ],
///
/// changeName: function() {
/// var oldName = this.get('name'),
/// newName = oldName + " The Barbarian";
///
/// this.set('name', newName);
/// }
/// });
/// The fields array is turned into a MixedCollection automatically by the ModelManager, and all other functions and properties are copied to the new Model's prototype.
///
/// Now we can create instances of our User model and call any model logic we defined:
///
/// var user = Ext.ModelManager.create({
/// name : 'Conan',
/// age : 24,
/// phone: '555-555-5555'
/// }, 'User');
///
/// user.changeName();
/// user.get('name'); //returns "Conan The Barbarian"
/// Validations
///
/// Models have built-in support for validations, which are executed against the validator functions in Ext.data.validations (see all validation functions). Validations are easy to add to models:
///
/// Ext.regModel('User', {
/// fields: [
/// {name: 'name', type: 'string'},
/// {name: 'age', type: 'int'},
/// {name: 'phone', type: 'string'},
/// {name: 'gender', type: 'string'},
/// {name: 'username', type: 'string'},
/// {name: 'alive', type: 'boolean', defaultValue: true}
/// ],
///
/// validations: [
/// {type: 'presence', field: 'age'},
/// {type: 'length', field: 'name', min: 2},
/// {type: 'inclusion', field: 'gender', list: ['Male', 'Female']},
/// {type: 'exclusion', field: 'username', list: ['Admin', 'Operator']},
/// {type: 'format', field: 'username', matcher: /([a-z]+)[0-9]{2,3}/}
/// ]
/// });
/// The validations can be run by simply calling the validate function, which returns a Ext.data.Errors object:
///
/// var instance = Ext.ModelManager.create({
/// name: 'Ed',
/// gender: 'Male',
/// username: 'edspencer'
/// }, 'User');
///
/// var errors = instance.validate();
/// Associations
///
/// Models can have associations with other Models via belongsTo and hasMany associations. For example, let's say we're writing a blog administration application which deals with Users, Posts and Comments. We can express the relationships between these models like this:
///
/// Ext.regModel('Post', {
/// fields: ['id', 'user_id'],
///
/// belongsTo: 'User',
/// hasMany : {model: 'Comment', name: 'comments'}
/// });
///
/// Ext.regModel('Comment', {
/// fields: ['id', 'user_id', 'post_id'],
///
/// belongsTo: 'Post'
/// });
///
/// Ext.regModel('User', {
/// fields: ['id'],
///
/// hasMany: [
/// 'Post',
/// {model: 'Comment', name: 'comments'}
/// ]
/// });
/// See the docs for Ext.data.BelongsToAssociation and Ext.data.HasManyAssociation for details on the usage and configuration of associations. Note that associations can also be specified like this:
///
/// Ext.regModel('User', {
/// fields: ['id'],
///
/// associations: [
/// {type: 'hasMany', model: 'Post', name: 'posts'},
/// {type: 'hasMany', model: 'Comment', name: 'comments'}
/// ]
/// });
/// Using a Proxy
///
/// Models are great for representing types of data and relationships, but sooner or later we're going to want to load or save that data somewhere. All loading and saving of data is handled via a Proxy, which can be set directly on the Model:
///
/// Ext.regModel('User', {
/// fields: ['id', 'name', 'email'],
///
/// proxy: {
/// type: 'rest',
/// url : '/users'
/// }
/// });
/// Here we've set up a Rest Proxy, which knows how to load and save data to and from a RESTful backend. Let's see how this works:
///
/// var user = Ext.ModelManager.create({name: 'Ed Spencer', email: 'ed@sencha.com'}, 'User');
///
/// user.save(); //POST /users
/// Calling save on the new Model instance tells the configured RestProxy that we wish to persist this Model's data onto our server. RestProxy figures out that this Model hasn't been saved before because it doesn't have an id, and performs the appropriate action - in this case issuing a POST request to the url we configured (/users). We configure any Proxy on any Model and always follow this API - see Ext.data.proxy.Proxy for a full list.
///
/// Loading data via the Proxy is equally easy:
///
/// //get a reference to the User model class
/// var User = Ext.ModelManager.getModel('User');
///
/// //Uses the configured RestProxy to make a GET request to /users/123
/// User.load(123, {
/// success: function(user) {
/// console.log(user.getId()); //logs 123
/// }
/// });
/// Models can also be updated and destroyed easily:
///
/// //the user Model we loaded in the last snippet:
/// user.set('name', 'Edward Spencer');
///
/// //tells the Proxy to save the Model. In this case it will perform a PUT request to /users/123 as this Model already has an id
/// user.save({
/// success: function() {
/// console.log('The User was updated');
/// }
/// });
///
/// //tells the Proxy to destroy the Model. Performs a DELETE request to /users/123
/// user.destroy({
/// success: function() {
/// console.log('The User was destroyed!');
/// }
/// });
/// Usage in Stores
///
/// It is very common to want to load a set of Model instances to be displayed and manipulated in the UI. We do this by creating a Store:
///
/// var store = new Ext.data.Store({
/// model: 'User'
/// });
///
/// //uses the Proxy we set up on Model to load the Store data
/// store.load();
/// A Store is just a collection of Model instances - usually loaded from a server somewhere. Store can also maintain a set of added, updated and removed Model instances to be synchronized with the server via the Proxy. See the Store docs for more information on Stores.
/// </summary>
[Meta]
public partial class Model : Observable, ICustomConfigSerialization, IVirtual
{
/// <summary>
///
/// </summary>
public Model()
{
}
/// <summary>
///
/// </summary>
[Description("")]
protected internal override bool IsIdRequired
{
get
{
return !this.IsGeneratedID || !(this.IsSelfRender || this.IsPageSelfRender || this.IsDynamic || this.IsMVC) || this.ForceIdRendering;
}
}
/// <summary>
///
/// </summary>
[ConfigOption(JsonMode.Ignore)]
[Description("")]
protected override string ConfigIDProxy
{
get
{
return base.ConfigIDProxy;
}
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Model Get(string name)
{
return Model.Models.ContainsKey(name) ? Model.Models[name] : null;
}
/// <summary>
///
/// </summary>
public static bool SuppressChecking
{
get
{
if (HttpContext.Current == null)
{
return false;
}
var obj = HttpContext.Current.Items["Ext.Net.Models.SuppressChecking"];
return obj != null ? (bool)obj : false;
}
set
{
HttpContext.Current.Items["Ext.Net.Models.SuppressChecking"] = value;
}
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static bool IsRegistered(string name)
{
return Model.SuppressChecking ? false : Model.Models.ContainsKey(name);
}
private static Dictionary<string, Model> Models
{
get
{
var models = HttpContext.Current.Items["Ext.Net.Models"] as Dictionary<string, Model>;
if (models == null)
{
models = new Dictionary<string, Model>();
HttpContext.Current.Items["Ext.Net.Models"] = models;
}
return models;
}
}
/// <summary>
/// The model name. Required
/// </summary>
[Meta]
[DefaultValue(null)]
[NotifyParentProperty(true)]
[Description("The model name. Required")]
public virtual string Name
{
get
{
return this.State.Get<string>("Name", null);
}
set
{
this.State.Set("Name", value);
}
}
/// <summary>
/// One or more BelongsTo associationa for this model.
/// </summary>
[Meta]
[DefaultValue("")]
[NotifyParentProperty(true)]
[Description("One or more BelongsTo associationa for this model.")]
public virtual string BelongsTo
{
get
{
return this.State.Get<string>("BelongsTo", "");
}
set
{
this.State.Set("BelongsTo", value);
}
}
[ConfigOption("belongsTo", JsonMode.Raw)]
[DefaultValue("")]
protected string BelongsToProxy
{
get
{
if (this.BelongsTo.IsEmpty())
{
return "";
}
if (this.BelongsTo.Contains(","))
{
return JSON.Serialize(this.BelongsTo.Split(','));
}
return JSON.Serialize(this.BelongsTo);
}
}
/// <summary>
/// One or more HasMany associations for this model.
/// </summary>
[Meta]
[DefaultValue("")]
[NotifyParentProperty(true)]
[Description("One or more HasMany associations for this model.")]
public virtual string HasMany
{
get
{
return this.State.Get<string>("HasMany", "");
}
set
{
this.State.Set("HasMany", value);
}
}
[ConfigOption("hasMany", JsonMode.Raw)]
[DefaultValue("")]
protected string HasManyProxy
{
get
{
if (this.HasMany.IsEmpty())
{
return "";
}
if (this.HasMany.Contains(","))
{
return JSON.Serialize(this.HasMany.Split(','));
}
return JSON.Serialize(this.HasMany);
}
}
/// <summary>
/// The name of a property that is used for submitting this Model's unique client-side identifier to the server when multiple phantom records are saved as part of the same Operation. In such a case, the server response should include the client id for each record so that the server response data can be used to update the client-side records if necessary.
/// This property cannot have the same name as any of this Model's fields.
/// </summary>
[Meta]
[ConfigOption]
[DefaultValue("clientId")]
[NotifyParentProperty(true)]
[Description("The name of a property that is used for submitting this Model's unique client-side identifier to the server when multiple phantom records are saved")]
public virtual string ClientIdProperty
{
get
{
return this.State.Get<string>("ClientIdProperty", "clientId");
}
set
{
this.State.Set("ClientIdProperty", value);
}
}
/// <summary>
///
/// </summary>
[Meta]
[DefaultValue("Ext.data.Model")]
[NotifyParentProperty(true)]
[Description("")]
public virtual string Extend
{
get
{
return this.State.Get<string>("Extend", "Ext.data.Model");
}
set
{
this.State.Set("Extend", value);
}
}
private ModelFieldCollection fields;
/// <summary>
/// The fields for this model. This is an Array of Field definition objects. A Field definition may simply be the name of the Field, but a Field encapsulates data type, custom conversion of raw data, and a mapping property to specify by name of index, how to extract a field's value from a raw data object, so it is best practice to specify a full set of Field config objects.
/// </summary>
[Meta]
[ConfigOption(JsonMode.AlwaysArray)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[NotifyParentProperty(true)]
[Description("An array of fields definition objects")]
public virtual ModelFieldCollection Fields
{
get
{
if (this.fields == null)
{
this.fields = new ModelFieldCollection();
this.fields.AfterItemAdd += Fields_AfterItemAdd;
}
return this.fields;
}
}
protected virtual void Fields_AfterItemAdd(ModelField item)
{
if (item.Validations != null)
{
this.Validations.AddRange(item.Validations);
}
}
/// <summary>
/// The name of the field treated as this Model's unique id (defaults to 'id').
/// </summary>
[Meta]
[ConfigOption("idProperty")]
[DefaultValue("")]
[NotifyParentProperty(true)]
[Description("The name of the field treated as this Model's unique id (defaults to 'id').")]
public virtual string IDProperty
{
get
{
return this.State.Get<string>("IDProperty", "");
}
set
{
this.State.Set("IDProperty", value);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual string GetIDProperty()
{
if (this.IDProperty.IsNotEmpty())
{
return this.IDProperty;
}
if (this.Proxy.Count > 0 && this.Proxy.Primary is ServerProxy)
{
var proxy = (ServerProxy)this.Proxy.Primary;
if (proxy.Reader.Count > 0 && proxy.Reader.Primary.IDProperty.IsNotEmpty())
{
return proxy.Reader.Primary.IDProperty;
}
}
return "";
}
private ProxyCollection proxy;
/// <summary>
/// The Proxy object which provides access to a data object.
/// </summary>
[Meta]
[ConfigOption("proxy>Primary")]
[NotifyParentProperty(true)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[Description("The Proxy object which provides access to a data object.")]
public virtual ProxyCollection Proxy
{
get
{
return this.proxy ?? (this.proxy = new ProxyCollection ());
}
}
private AssociationCollection associations;
/// <summary>
/// Models associations
/// </summary>
[Meta]
[ConfigOption(JsonMode.AlwaysArray)]
[NotifyParentProperty(true)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[Description("Models associations")]
public virtual AssociationCollection Associations
{
get
{
return this.associations ?? (this.associations = new AssociationCollection());
}
}
private ValidationCollection validations;
/// <summary>
/// Models validations
/// </summary>
[Meta]
[ConfigOption(JsonMode.Array)]
[NotifyParentProperty(true)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[Description("Models validations")]
public virtual ValidationCollection Validations
{
get
{
return this.validations ?? (this.validations = new ValidationCollection());
}
}
private ModelIdGeneratorCollection idgen;
/// <summary>
/// The id generator to use for this model. The default id generator does not generate values for the idProperty.
/// </summary>
[Meta]
[ConfigOption("idgen>Primary")]
[NotifyParentProperty(true)]
[PersistenceMode(PersistenceMode.InnerProperty)]
[Description("The id generator to use for this model. The default id generator does not generate values for the idProperty.")]
public virtual ModelIdGeneratorCollection IDGen
{
get
{
return this.idgen ?? (this.idgen = new ModelIdGeneratorCollection());
}
}
/// <summary>
///
/// </summary>
/// <param name="owner"></param>
/// <returns></returns>
public string ToScript(Control owner)
{
string tpl = "Ext.define({0}, {{extend: {3}, {1} }}){2}";
string id = this.Name.IsNotEmpty() ? JSON.Serialize(this.Name) : (this.IsGeneratedID ? "Ext.id()" : JSON.Serialize(this.ClientID));
return tpl.FormatWith(id, new ClientConfig().Serialize(this, true).Chop(),
this.IsLazy ? "" : ";", JSON.Serialize(this.Extend));
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!Model.Models.ContainsKey(this.Name ?? this.ClientID))
{
this.Register(false);
}
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public virtual void Register(bool client)
{
lock(Model.Models)
{
string name = this.Name ?? this.ClientID;
if (!Model.Models.ContainsKey(name))
{
Model.Models.Add(name, this);
}
else
{
throw new Exception("Model with name '{0}' is already registered".FormatWith(name));
}
}
if (client)
{
this.RegisterOnClient();
}
}
/// <summary>
///
/// </summary>
public virtual void RegisterOnClient()
{
this.RenderScript("Ext.ModelManager.registerType({0}, {1});".FormatWith(JSON.Serialize(this.Name ?? this.ClientID), new ClientConfig().Serialize(this, true)));
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public virtual void Unregister(bool client)
{
lock (Model.Models)
{
string name = this.Name ?? this.ClientID;
if (Model.Models.ContainsKey(this.Name ?? this.ClientID))
{
Model.Models.Remove(this.Name ?? this.ClientID);
}
else
{
throw new Exception("Model with name '{0}' doesn't exist".FormatWith(name));
}
}
if (client)
{
this.UnregisterOnClient();
}
}
/// <summary>
///
/// </summary>
public virtual void UnregisterOnClient()
{
this.RenderScript("Ext.ModelManager.unregister(Ext.ModelManager.getModel({0}));".FormatWith(JSON.Serialize(this.Name ?? this.ClientID)));
}
}
/// <summary>
///
/// </summary>
public partial class ModelCollection : SingleItemCollection<Model>
{
/// <summary>
///
/// </summary>
[ConfigOption(typeof(LazyControlJsonConverter))]
public Model Primary
{
get
{
if (this.Count > 0)
{
return this[0];
}
return null;
}
}
}
}