-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathSqlSmoObject.cs
8957 lines (7913 loc) · 360 KB
/
SqlSmoObject.cs
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Text;
using System.Data;
#if MICROSOFTDATA
using Microsoft.Data.SqlClient;
#else
using System.Data.SqlClient;
#endif
using System.Collections;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Reflection;
using System.Data.SqlTypes;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.SqlServer.Management.Smo.Broker;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo.Agent;
using Microsoft.SqlServer.Management.Sdk.Sfc.Metadata;
using Microsoft.SqlServer.Management.Sdk.Sfc;
#pragma warning disable 1590,1591,1592,1573,1571,1570,1572,1587
namespace Microsoft.SqlServer.Management.Smo
{
// Given index and value, get/set the appropriate data member in XSchema
internal interface IPropertyDataDispatch
{
object GetPropertyValue(int index);
void SetPropertyValue(int index, object value);
}
}
namespace Microsoft.SqlServer.Management.Smo
{
public class NamedSmoObject : SqlSmoObject
{
internal NamedSmoObject(AbstractCollectionBase parentColl, ObjectKeyBase key, SqlSmoState state)
: base(parentColl, key, state)
{
}
// this default constructor has to be called by objects that do not know their parent
// because they don't live inside a collection
internal NamedSmoObject(ObjectKeyBase key, SqlSmoState state)
: base(key, state)
{
}
// this constructor called by objects thet are created in space
protected internal NamedSmoObject()
: base()
{
}
[SfcKey(0)]
[SfcProperty(SfcPropertyFlags.ReadOnlyAfterCreation | SfcPropertyFlags.Design | SfcPropertyFlags.Standalone)]
public virtual string Name
{
get
{
return ((SimpleObjectKey)key).Name;
}
set
{
try
{
ValidateName(value);
if (ShouldNotifyPropertyChange)
{
if (this.Name != value)
{
((SimpleObjectKey)key).Name = value;
OnPropertyChanged("Name");
}
}
else
{
((SimpleObjectKey)key).Name = value;
}
UpdateObjectState();
}
catch (Exception e)
{
FilterException(e);
throw new FailedOperationException(ExceptionTemplates.SetName, this, e);
}
}
}
internal virtual void ValidateName(string name)
{
if (null == name)
{
throw new SmoException(ExceptionTemplates.InnerException, new ArgumentNullException("Name"));
}
if (
(State != SqlSmoState.Pending) &&
(State != SqlSmoState.Creating)
)
{
throw new InvalidSmoOperationException(ExceptionTemplates.OperationOnlyInPendingState);
}
}
internal override string FullQualifiedName
{
get
{
return string.Format(SmoApplication.DefaultCulture, "[{0}]", SqlBraket(this.Name));
}
}
internal override string InternalName
{
get { return string.Format(SmoApplication.DefaultCulture, "{0}", this.Name); }
}
///<summary>
/// change object name
///</summary>
protected void RenameImpl(string newName)
{
try
{
CheckObjectState();
string oldName = this.Name;
string oldUrn = this.Urn;
RenameImplWorker(newName);
if (!this.ExecutionManager.Recording)
{
// generate internal events
if (!SmoApplication.eventsSingleton.IsNullObjectRenamed())
{
SmoApplication.eventsSingleton.CallObjectRenamed(GetServerObject(),
// Only new Urn (this.Urn) and old Urn (oldUrn) are used now by SSMS
// Other parameters are left for backwards compatibility with old
// receivers of the event who might use them
new ObjectRenamedEventArgs(this.Urn, this, oldName, newName, oldUrn));
}
}
}
catch (Exception e)
{
FilterException(e);
throw new FailedOperationException(ExceptionTemplates.Rename, this, e);
}
}
protected void RenameImplWorker(string newName)
{
if (null == newName)
{
throw new SmoException(ExceptionTemplates.InnerException, new ArgumentNullException("newName"));
}
ObjectKeyBase oldKey = this.key;
ExecuteRenameQuery(newName);
if (!this.ExecutionManager.Recording)
{
((SimpleObjectKey)this.key).Name = newName;
if (null != ParentColl)
{
ParentColl.RemoveObject(oldKey);
ParentColl.AddExisting(this);
}
}
}
/// <summary>
/// Creates the Rename query for a SqlSmoObject and Executes it on the Server.
/// </summary>
/// <param name="newName"></param>
protected virtual void ExecuteRenameQuery(string newName)
{
// builds the t-sql for filegroup rename
StringCollection renameQuery = new StringCollection();
ScriptingPreferences sp = new ScriptingPreferences();
sp.SetTargetServerInfo(this);
ScriptRename(renameQuery, sp, newName);
// execute t-sql
if (renameQuery.Count > 0 && !this.IsDesignMode)
{
// don't include database context while renaming a database
this.ExecuteNonQuery(renameQuery, !(this is Database), executeForAlter: false);
}
}
internal virtual void ScriptRename(StringCollection renameQuery, ScriptingPreferences sp, string newName)
{
throw new InvalidOperationException();
}
internal override ObjectKeyBase GetEmptyKey()
{
return new SimpleObjectKey(null);
}
/// <summary>
/// This is the prefix that is added to the permission DDL for the object
/// The list is extracted from file 'secmgr.cpp' in the array:
/// static const SECPermMappings::SECClassNameStrings x_sps_Class[] =
/// Objects whose securable class_desc is OBJECT can omit the "object::" qualifier
/// </summary>
internal string PermissionPrefix
{
get
{
string prefix = null;
switch (this.GetType().Name)
{
case nameof(ExternalLanguage):
prefix = "EXTERNAL LANGUAGE"; break;
case nameof(ExternalLibrary):
prefix = "EXTERNAL LIBRARY"; break;
case nameof(SqlAssembly):
prefix = "ASSEMBLY"; break;
case nameof(UserDefinedDataType):
case nameof(UserDefinedTableType):
case nameof(UserDefinedType):
prefix = "TYPE"; break;
case nameof(FullTextCatalog):
prefix = "FULLTEXT CATALOG"; break;
case nameof(Login):
prefix = "LOGIN"; break;
case nameof(ServerRole):
prefix = "SERVER ROLE"; break;
case nameof(Schema):
prefix = "SCHEMA"; break;
case nameof(Endpoint):
case "HttpEndpoint":
prefix = "ENDPOINT"; break;
case nameof(XmlSchemaCollection):
prefix = "XML SCHEMA COLLECTION"; break;
case nameof(Certificate):
prefix = "CERTIFICATE"; break;
case nameof(ApplicationRole):
prefix = "APPLICATION ROLE"; break;
case nameof(User):
prefix = "USER"; break;
case nameof(DatabaseRole):
prefix = "ROLE"; break;
case nameof(SymmetricKey):
prefix = "SYMMETRIC KEY"; break;
case nameof(AsymmetricKey):
prefix = "ASYMMETRIC KEY"; break;
// service broker related objects
case "MessageType":
prefix = "MESSAGE TYPE"; break;
case "ServiceContract":
prefix = "CONTRACT"; break;
case "BrokerService":
prefix = "SERVICE"; break;
case "ServiceRoute":
prefix = "ROUTE"; break;
case "RemoteServiceBinding":
prefix = "REMOTE SERVICE BINDING"; break;
case nameof(FullTextStopList):
prefix = "FULLTEXT STOPLIST"; break;
case nameof(SearchPropertyList):
prefix = "SEARCH PROPERTY LIST"; break;
case nameof(Database):
prefix = "DATABASE"; break;
case nameof(AvailabilityGroup):
prefix = AvailabilityGroup.AvailabilityGroupScript; break;
case nameof(DatabaseScopedCredential):
prefix = "DATABASE SCOPED CREDENTIAL"; break;
}
if (null != prefix)
{
return prefix + "::";
}
return string.Empty;
}
}
internal virtual string FormatFullNameForScripting(ScriptingPreferences sp)
{
return FormatFullNameForScripting(sp, true);
}
/// <summary>
/// format full object name for scripting
/// </summary>
/// <param name="sp"></param>
/// <param name="nameIsIndentifier"></param>
/// <returns></returns>
internal string FormatFullNameForScripting(ScriptingPreferences sp, bool nameIsIndentifier)
{
CheckObjectState();
if (nameIsIndentifier)
{
return MakeSqlBraket(GetName(sp));
}
else
{
return MakeSqlString(GetName(sp));
}
}
/// <summary>
/// Returns the name that will be used for scripting, in case we allow
/// users to script the object with a different name.
/// </summary>
/// <param name="sp"></param>
/// <returns></returns>
internal virtual string GetName(ScriptingPreferences sp)
{
return this.Name;
}
internal void ScriptOwner(StringCollection queries, ScriptingPreferences sp)
{
this.ScriptChangeOwner(queries,sp);
}
protected void SetSchemaOwned()
{
if (this.ExecutionManager.Recording || !this.IsDesignMode || !this.IsVersion90AndAbove())
{
return;
}
string owner = this.Properties.Get("Owner").Value as string;
bool schemaOwned = false;
if (string.IsNullOrEmpty(owner))
{
schemaOwned = true;
}
//lookup the property ordinal from name
int isSchemaOwnedSet = this.Properties.LookupID("IsSchemaOwned", PropertyAccessPurpose.Write);
//set the new value
this.Properties.SetValue(isSchemaOwnedSet, schemaOwned);
//mark the property as retrived, that means that it is
//in sync with value on the server
this.Properties.SetRetrieved(isSchemaOwnedSet, true);
}
internal virtual void ScriptChangeOwner(StringCollection queries, ScriptingPreferences sp)
{
Property prop = this.GetPropertyOptional("Owner");
if (!prop.IsNull && (prop.Dirty || !sp.ScriptForAlter))
{
ScriptChangeOwner(queries, (string)prop.Value, sp);
}
}
/// <summary>
/// Generate the script statements to change the owner of this object to the specified
/// owner name.
/// </summary>
/// <param name="queries">Query collection to add the statements to</param>
/// <param name="newOwner">The name of the new owner</param>
/// <param name="sp">The scripting preferences</param>
internal virtual void ScriptChangeOwner(StringCollection queries, string newOwner, ScriptingPreferences sp = null)
{
StringBuilder sb = new StringBuilder(Globals.INIT_BUFFER_SIZE);
if ((sp != null && sp.TargetServerVersion > SqlServerVersion.Version80) ||
(sp == null && this.IsVersion90AndAbove()))
{
sb.AppendFormat(SmoApplication.DefaultCulture, "ALTER AUTHORIZATION ON {0}", this.PermissionPrefix);
sb.AppendFormat(SmoApplication.DefaultCulture, "{0}", FormatFullNameForScripting(sp));
sb.AppendFormat(SmoApplication.DefaultCulture, " TO ");
sb.AppendFormat(SmoApplication.DefaultCulture, "{0}", MakeSqlBraket(newOwner));
}
else
{
this.ScriptOwnerForShiloh(sb, sp, newOwner);
}
if (sb.Length > 0)
{
queries.Add(sb.ToString());
}
}
/// <summary>
/// Scripting the owner for shiloh (2005) which doesn't support the ALTER AUTHORIZATION statement
/// </summary>
/// <param name="sb">Builder to add the statements to</param>
/// <param name="newOwner">The name of the new owner</param>
/// <param name="sp">The scripting preferences</param>
/// <returns></returns>
internal virtual void ScriptOwnerForShiloh(StringBuilder sb, ScriptingPreferences sp, string newOwner)
{
sb.AppendFormat(SmoApplication.DefaultCulture, "EXEC sp_changeobjectowner {0} , {1} ", MakeSqlString(FormatFullNameForScripting(sp)), MakeSqlString(newOwner));
}
}
///<summary>
/// Contains common functionality for all the instance classes
///</summary>
[TypeConverter(typeof(LocalizableTypeConverter))]
public abstract class SqlSmoObject : SmoObjectBase
, Microsoft.SqlServer.Management.Sdk.Sfc.ISfcPropertyProvider
, Microsoft.SqlServer.Management.Common.IRefreshable
, IAlienObject
, ISqlSmoObjectInitialize
{
internal const BindingFlags UrnSuffixBindingFlags =
BindingFlags.Default | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public |
BindingFlags.GetProperty | BindingFlags.FlattenHierarchy;
/// <summary>
/// Event that is raised when a property fetch is made after object initialization
/// and the object needs to issue a SQL query to retrieve the value.
/// This event is raised synchronously, so the fetch is blocked until all handlers of the event return.
/// </summary>
public static event EventHandler<PropertyMissingEventArgs> PropertyMissing = delegate { };
internal SqlSmoObject(AbstractCollectionBase parentColl,
ObjectKeyBase key, SqlSmoState state)
{
#if DEBUG
if (null == parentColl)
{
throw new SmoException(ExceptionTemplates.InnerException, new ArgumentNullException("parentColl"));
}
if (null == key)
{
throw new SmoException(ExceptionTemplates.InnerException, new ArgumentNullException("key"));
}
#endif
SetObjectKey(key);
this.parentColl = parentColl;
Init();
SetState(state);
}
internal virtual SqlPropertyMetadataProvider GetPropertyMetadataProvider()
{
return null;
}
// this default constructor has to be called by objects that do not know their parent
// because they don't live inside a collection
internal SqlSmoObject(ObjectKeyBase key, SqlSmoState state)
{
SetObjectKey(key);
Init();
SetState(state);
}
// this constructor called by objects thet are created in space
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected internal SqlSmoObject()
{
Init();
SetState(SqlSmoState.Pending);
objectInSpace = true;
key = GetEmptyKey();
}
internal virtual ObjectKeyBase GetEmptyKey()
{
return new ObjectKeyBase();
}
// some initialization calls
private void Init()
{
// sets initial state
propertyBagState = PropertyBagState.Empty;
// inits the properties to null, we will populate the property
// collection with enumerator metadata when the user asks for it
properties = null;
// we assume every object will be scripted
m_bIgnoreForScripting = false;
m_comparer = null;
m_ExtendedProperties = null;
}
// Cache the lookup of the property name in the parent object based on the singleton child type
// Used for SMO Object Query processing. Default capacity is 20 since there are abotu 20 singleton classes
// in SMO in Katmai.
private static Dictionary<Type, string> s_SingletonTypeToProperty = new Dictionary<Type, string>(20);
// Cache the lookup of the property name in the parent object based on the singleton child type
// Used for SMO Object Query processing. Default capacity is 150 since there are about 132 object classes
// in SMO in Katmai.
private static Dictionary<Type, string[]> s_TypeToKeyFields = new Dictionary<Type, string[]>(150);
bool initializedForScripting = false;
internal bool InitializedForScripting
{
get { return initializedForScripting; }
set { initializedForScripting = value; }
}
internal bool objectInSpace = false;
protected bool ObjectInSpace
{
get { return objectInSpace; }
}
// this function returns true if the object is in space, of one of its parents is in space
internal protected bool IsObjectInSpace()
{
if (this.State == SqlSmoState.Pending)
{
return true;
}
// climb up the tree to the server object
SqlSmoObject current = this;
while ((null != current) && !(current is Server))
{
if (current.ObjectInSpace)
{
return true;
}
if (null == current.ParentColl || null == current.ParentColl.ParentInstance)
{
PropertyInfo mi = current.GetType().GetProperty("Parent", BindingFlags.Instance | BindingFlags.Public);
if (null == mi)
{
throw new InternalSmoErrorException(ExceptionTemplates.GetParentFailed);
}
current = mi.GetValue(current, null) as SqlSmoObject;
}
else
{
current = current.ParentColl.ParentInstance;
}
}
return false;
}
// Not all SqlSmoObjects have ExtendedProperties, but we need to make sure that
// when an object is refreshed, that its ExtendedProperties are also refreshed.
// To do this, we push this into the base class and clear extended properties in
// SqlSmoObject.Refresh()
[SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")]
protected ExtendedPropertyCollection m_ExtendedProperties;
protected virtual void MarkDropped()
{
// mark the object itself as dropped
SetState(SqlSmoState.Dropped);
if (null != userPermissions)
{
userPermissions.MarkAllDropped();
}
}
// we have this function so that we can call MarkDropped internally
// internal virtual ... is forbidden by the compiler; to be fixed by Everett
internal void MarkDroppedInternal()
{
MarkDropped();
}
protected void MarkForDropImpl(bool dropOnAlter)
{
CheckObjectState();
if (this.State != SqlSmoState.Existing && this.State != SqlSmoState.ToBeDropped)
{
throw new InvalidSmoOperationException("MarkForDrop", this.State);
}
if (dropOnAlter)
{
SetState(SqlSmoState.ToBeDropped);
}
else if (this.State == SqlSmoState.ToBeDropped)
{
SetState(SqlSmoState.Existing);
}
}
// this function will be the first thing called in EVERY public method
// and property of ANY SMO object. It checks if the object is still
// alive, meaning that it has not been dropped yet. If the object
// has been dropped, the method throws an exception. There will
// be some exception from this rule, eg methods that do not do this
// check are mainly methods and properties that go up the chain
// Methods not checked : Name, State, Parent, class constructors
// Also, note that the checks will not apply to objects that cannot be
// dropped, like Languages, or Backup
// For properties that are accessed through the property bag, we will
// check the property bag.
protected void CheckObjectState()
{
CheckObjectState(false);
}
/// <summary>
/// This is a virtual function, so that derived classes can
/// override it if they want to do additional checks on the state of the object
/// </summary>
/// <param name="throwIfNotCreated"></param>
protected virtual void CheckObjectState(bool throwIfNotCreated)
{
CheckObjectStateImpl(throwIfNotCreated);
}
/// <summary>
/// Checks object state
/// Because it is not recusrive, this function can be called directly and
/// which means derived classes can't supply their own validation
/// </summary>
/// <param name="throwIfNotCreated"></param>
protected void CheckObjectStateImpl(bool throwIfNotCreated)
{
CheckPendingState();
if (this.State == SqlSmoState.Dropped)
{
throw new SmoException(ExceptionTemplates.ObjectDroppedExceptionText(this.GetType().ToString(), this.key.ToString()));
}
if (throwIfNotCreated && this.State == SqlSmoState.Creating)
{
throw new InvalidSmoOperationException(ExceptionTemplates.ErrorInCreatingState);
}
}
AbstractCollectionBase parentColl;
/// <summary>
/// Pointer to the collection that holds the object, if any
/// </summary>
internal AbstractCollectionBase ParentColl
{
get
{
return parentColl;
}
set
{
parentColl = value;
}
}
/// <summary>
/// Returns the collection that contains the object. May be null.
/// </summary>
public AbstractCollectionBase ParentCollection
{
get { return ParentColl; }
}
internal virtual string FullQualifiedName
{
get
{
return key.ToString();
}
}
internal virtual string InternalName
{
get { return key.ToString(); }
}
public override string ToString()
{
if (key.GetType().Name == "ObjectKeyBase")
{
return base.ToString();
}
return key.ToString();
}
// the Skeleton of the Urn is consists of an Urn devoided of filters
// we need it in order to get the list of properties that an object has
// we do not want to pass the whole Urn to the enumerator for that
internal string UrnSkeleton
{
get
{
CheckObjectState();
#if INCLUDE_PERF_COUNT
if( PerformanceCounters.DoCount )
PerformanceCounters.UrnSkelCallsCount++;
#endif
StringBuilder urnbuilder = new StringBuilder(Globals.INIT_BUFFER_SIZE);
GetUrnShellRecursive(urnbuilder);
return urnbuilder.ToString();
}
}
/// This function returns the Type matching the given URN
/// skeleton. It is the inverse of GetUrnSkeletonFromType.
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Type.InvokeMember")]
public static Type GetTypeFromUrnSkeleton(Urn urn)
{
XPathExpression skeleton = urn.XPathExpression;
Type childType = null;
string parentName = null;
for (int i = 0; i < skeleton.Length; i++)
{
childType = GetChildType(skeleton[i].Name, parentName);
if (null == childType)
{
break;
}
parentName = childType.Name;
}
return childType;
}
// go up the chain recursively to get the skeleton
// we have this recursive function in the event some levels would have
// different rules, otherwise we could have avoided recursivity
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Type.InvokeMember")]
internal void GetUrnShellRecursive(StringBuilder urnbuilder)
{
// determine the suffix, which is static member of the class
string urnsuffix = SqlSmoObject.GetUrnSuffix(this.GetType());
// if this is an empty string, we are in RootObject
if (urnsuffix.Length == 0)
{
return;
}
// the recursive call to get the parent's skeleton
if (null != ParentColl)
{
ParentColl.ParentInstance.GetUrnShellRecursive(urnbuilder);
}
else if (!(this is Server))
{
SqlSmoObject parent = (SqlSmoObject)this.GetType().InvokeMember("Parent",
BindingFlags.Default | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.GetProperty,
null,
this,
new object[] { }, SmoApplication.DefaultCulture);
parent.GetUrnShellRecursive(urnbuilder);
}
if (urnbuilder.Length != 0)
{
urnbuilder.AppendFormat(SmoApplication.DefaultCulture, "/{0}", urnsuffix);
}
else
{
// if the parentSkeleton is empty we are in Server object,
// and we do not append any prefix
urnbuilder.Append("Server");
}
}
internal void GetUrnRecImpl(StringBuilder urnbuilder, UrnIdOption idOption)
{
GetUrnRecursive(urnbuilder, idOption);
}
/// <summary>
/// Computes the Urn for the object.
/// </summary>
/// <param name="urnbuilder"></param>
protected virtual void GetUrnRecursive(StringBuilder urnbuilder)
{
GetUrnRecursive(urnbuilder, UrnIdOption.NoId);
}
/// <summary>
/// Computes the Urn for the object, potentially including other fields in
/// the definition besides the key fields.
/// </summary>
/// <param name="urnbuilder">holds the Urn</param>
/// <param name="useIdAsKey">Us ID as key instead of the regular key
/// fields. If the object does not have this property the regular key
/// fields will still be used.</param>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Type.InvokeMember")]
protected virtual void GetUrnRecursive(StringBuilder urnbuilder, UrnIdOption idOption)
{
// determine the suffix, which is static member of the class
string urnsuffix = SqlSmoObject.GetUrnSuffix(this.GetType());
// if this is an empty string, we are in RootObject
if (urnsuffix.Length == 0)
{
return;
}
// the recursive call
if (null != ParentColl)
{
ParentColl.ParentInstance.GetUrnRecursive(urnbuilder, idOption);
}
if (urnbuilder.Length != 0)
{
switch (idOption)
{
case UrnIdOption.WithId:
// this could be a bug but I keep the old behavior
if (!this.Properties.Contains("ID"))
{
goto case UrnIdOption.NoId;
}
urnbuilder.AppendFormat(SmoApplication.DefaultCulture,
"/{0}[{1} and @ID={2}]", urnsuffix, key.UrnFilter, GetPropValueOptional("ID", 0).ToString(SmoApplication.DefaultCulture));
break;
case UrnIdOption.OnlyId:
// this could be a bug but I keep the old behavior
if (!this.Properties.Contains("ID"))
{
goto case UrnIdOption.NoId;
}
urnbuilder.AppendFormat(SmoApplication.DefaultCulture,
"/{0}[@ID={1}]", urnsuffix, GetPropValueOptional("ID", 0).ToString(SmoApplication.DefaultCulture));
break;
case UrnIdOption.NoId:
urnbuilder.AppendFormat(SmoApplication.DefaultCulture,
"/{0}[{1}]", urnsuffix, key.UrnFilter);
break;
}
}
else
{
// if the parenturn is empty we are in Server object, and we
// do not append any prefix
//null if in capture mode and we didn't take the name yet
if (null == this.GetServerObject().ExecutionManager.TrueServerName)
{
urnbuilder.Append(urnsuffix);
}
else
{
urnbuilder.AppendFormat(SmoApplication.DefaultCulture, "{0}[@Name='{1}']", urnsuffix,
Urn.EscapeString(this.GetServerObject().ExecutionManager.TrueServerName));
}
return;
}
}
/// <summary>
/// Gets the UrnSuffix from the specified type - or an empty string if the type
/// does not define a static property named UrnSuffix.
/// </summary>
/// <param name="type"></param>
public static string GetUrnSuffix(Type type)
{
PropertyInfo pi = type.GetProperty("UrnSuffix", UrnSuffixBindingFlags);
if (pi == null)
{
return string.Empty;
}
return pi.GetValue(null, null) as string;
}
/// <summary>
/// Returns the Urn of the object, computed on the fly
/// </summary>
public Urn Urn
{
get
{
CheckObjectStateImpl(false);
#if INCLUDE_PERF_COUNT
if( PerformanceCounters.DoCount )
PerformanceCounters.UrnCallsCount++;
#endif
StringBuilder urnbuilder = new StringBuilder(Globals.INIT_BUFFER_SIZE);
GetUrnRecursive(urnbuilder);
return new Urn(urnbuilder.ToString());
}
}
// Get Urn where each fragment *contains* the ID, as in [@Name='foo' and @ID='100']
internal Urn UrnWithId
{
get
{
#if INCLUDE_PERF_COUNT
if( PerformanceCounters.DoCount )
PerformanceCounters.UrnCallsCount++;
#endif
StringBuilder urnbuilder = new StringBuilder(Globals.INIT_BUFFER_SIZE);
GetUrnRecursive(urnbuilder, UrnIdOption.WithId);
return new Urn(urnbuilder.ToString());
}
}
// Get Urn where each fragment *is* the ID, as in [@ID='100']
// This is only called by DMF
internal Urn UrnOnlyId
{
get
{
#if INCLUDE_PERF_COUNT
if( PerformanceCounters.DoCount )
PerformanceCounters.UrnCallsCount++;
#endif
StringBuilder urnbuilder = new StringBuilder(Globals.INIT_BUFFER_SIZE);
GetUrnRecursive(urnbuilder, UrnIdOption.OnlyId);
return new Urn(urnbuilder.ToString());
}
}
// this is the key that identifies the object in the collection
// for the regular objects it will be name
internal ObjectKeyBase key = null;
internal void SetObjectKey(ObjectKeyBase key)
{
this.key = key;
}
/// <summary>
/// Regular SMO objects access the parent class reference through parentColl (corresponding collection in parent class).
/// Singleton class has no collection in parent.
/// </summary>
protected SqlSmoObject singletonParent = null;
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Type.InvokeMember")]
internal virtual void ValidateParent(SqlSmoObject newParent)
{
// we are going to use the parent to get the child collection where this object is
// going to sit. This is also a validation to make sure newParent can be a
// parent of this object
string urnsuffix = SqlSmoObject.GetUrnSuffix(this.GetType());
if (null == urnsuffix || urnsuffix.Length == 0)
{
throw new InternalSmoErrorException(ExceptionTemplates.NoUrnSuffix);
}
try
{
parentColl = GetChildCollection(newParent, urnsuffix, null, newParent.ServerVersion);
}
catch(ArgumentException)
{
PropertyInfo childProperty;
try
{
childProperty = newParent.GetType().GetProperty(this.GetType().Name);
}
catch (MissingMethodException)