-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathserverbase.cs
More file actions
4638 lines (4067 loc) · 176 KB
/
serverbase.cs
File metadata and controls
4638 lines (4067 loc) · 176 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
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.Data;
#if MICROSOFTDATA
#else
using System.Data.SqlClient;
#endif
using System.Text;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Management;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.SqlServer.Management.Smo.Broker;
using Microsoft.SqlServer.Management.Smo.Agent;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo.Mail;
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.Sdk.Sfc.Metadata;
using Cmn = Microsoft.SqlServer.Management.Common;
using Sfc = Microsoft.SqlServer.Management.Sdk.Sfc;
using System.Linq.Expressions;
namespace Microsoft.SqlServer.Management.Smo
{
[Facets.EvaluationMode(Dmf.AutomatedPolicyEvaluationMode.CheckOnSchedule)]
[Microsoft.SqlServer.Management.Sdk.Sfc.PhysicalFacet]
[Sfc.RootFacetAttribute(typeof(Server))]
public partial class Server : SqlSmoObject, Cmn.IAlterable, IScriptable, IServerSettings, IServerInformation, IAlienRoot, ISfcDomainLite
{
private ExecutionManager m_ExecutionManager;
//Server is root for SMO domain. It should provide domain name, which is used in serialization, among others.
private const string DomainName = "SMO";
public Server(string name)
: base()
{
m_ExecutionManager = new ExecutionManager(name);
m_ExecutionManager.Parent = this;
Init();
}
public Server()
: base()
{
m_ExecutionManager = new ExecutionManager(".");
m_ExecutionManager.Parent = this;
Init();
}
private ServerConnection serverConnection;
/// <summary>
/// Constructs a new Server object that relies on the given ServerConnection for connectivity.
/// </summary>
/// <param name="serverConnection"></param>
/// <remarks>If serverConnection.ConnectAsUser is true, its NonPooledConnection property must also be true.
/// Otherwise, Server may attempt to duplicate the ServerConnection without preserving the ConnectAsUser parameters,
/// leading to either failed connections or connections as the incorrect user when using integrated security.
/// </remarks>
public Server(ServerConnection serverConnection)
: base()
{
this.serverConnection = serverConnection;
//Note: Execution Manager for this case will be initialized in the GetExecutionManager() method
// to take care of the transparent conenction switching for the Cloud DB
// (as the tranparent switching within this constructor breaks some usercases of the on-premises server)
Init();
}
private bool IsAzureDbScopedConnection(ServerConnection sc)
{
// we delay making a connection to fetch the engine type since we can eliminate common cases without it.
return ((!string.IsNullOrEmpty(sc.DatabaseName) && sc.DatabaseName.ToUpperInvariant() != "MASTER") ||
(!string.IsNullOrEmpty(sc.InitialCatalog) && sc.InitialCatalog.ToUpperInvariant() != "MASTER"))
&& sc.DatabaseEngineType == DatabaseEngineType.SqlAzureDatabase;
}
public override ExecutionManager ExecutionManager
{
get
{
return this.GetExecutionManager();
}
}
void Init()
{
if (this.serverConnection == null)
{
Diagnostics.TraceHelper.Assert(m_ExecutionManager != null, "m_ExecutionManager == null");
this.serverConnection = m_ExecutionManager.ConnectionContext;
}
SetState(SqlSmoState.Existing);
objectInSpace = false;
SetObjectKey(new SimpleObjectKey(this.Name));
}
[SfcKey(0)]
[SfcProperty(SfcPropertyFlags.Standalone | SfcPropertyFlags.SqlAzureDatabase)]
public string Name
{
get
{
try
{
if (!SqlContext.IsAvailable)
{
//try to get it from server connection property
return NormalizeServerName(ConnectionContext.ServerInstance);
}
else
{
return ConnectionContext.ServerInstance;
}
}
catch (PropertyNotAvailableException)
{
//failed to syncronize with connection context because it has a connection string set
//try to get it from server
try
{
return ConnectionContext.TrueName;
}
catch (ExecutionFailureException)
{
}
}
//could not determine the name
return string.Empty;
}
}
//serialization adapter is needed since system.version cannot be serialized by xmlserializer (because state is not settable).
[SfcSerializationAdapter(typeof(VersionSerializationAdapter))]
[SfcProperty(SfcPropertyFlags.Standalone | SfcPropertyFlags.SqlAzureDatabase)]
public Version Version
{
get
{
ServerVersion sv = this.ServerVersion;
return new Version(sv.Major, sv.Minor, sv.BuildNumber);
}
//internal so that public API doesn't change. Fine for now since serializer uses reflection.
//In the near future, SFC will be made friend of this assembly, so this setter becomes
//available at compile time as well.
internal set
{
//make server version settable in design mode, so that serializer can set the value.
if (this.IsDesignMode)
{
if (value != null)
{
this.ConnectionContext.ServerVersion = new ServerVersion(value.Major, value.Minor, value.Build);
}
else
{
this.ConnectionContext.ServerVersion = null;
}
}
else
{
Diagnostics.TraceHelper.Assert(false, "Version property of Server can only be set in design mode");
}
}
}
[SfcProperty(SfcPropertyFlags.Standalone | SfcPropertyFlags.SqlAzureDatabase)]
public Edition EngineEdition
{
get
{
// from Books Online (SQL Server 2005):
// SERVERPROPERTY('EngineEdition') returns the following
// 1 = Personal or Desktop Engine
// 2 = Standard
// 3 = Enterprise, Enterprise Evaluation, or Developer
// 4 = Express
int result = (Int32)this.Properties.GetValueWithNullReplacement("EngineEdition");
return (Edition)result;
}
}
[SfcProperty(SfcPropertyFlags.Standalone | SfcPropertyFlags.SqlAzureDatabase)]
public Version ResourceVersion
{
get
{
return new Version(this.ResourceVersionString);
}
}
[SfcProperty(SfcPropertyFlags.Standalone)]
public Version BuildClrVersion
{
get
{
//BuildClrVersionString is of format 'v2.0.50727', hence getting substring leaving first character
return new Version(this.BuildClrVersionString.Substring(1));
}
}
/// <summary>
/// Overrides the standard behavior of scripting object permissions.
/// </summary>
/// <param name="query"></param>
/// <param name="sp"></param>
internal override void AddScriptPermission(StringCollection query, ScriptingPreferences sp)
{
// script server permissions.
AddScriptPermissions(query, PermissionWorker.PermissionEnumKind.Server, sp);
}
internal void SetServerNameFromConnectionInfo()
{
SetObjectKey(new SimpleObjectKey(NormalizeServerName(ConnectionContext.ServerInstance)));
}
private string NormalizeServerName(string name)
{
// treat special server names : ".", "", "(locall)"
if (name == "." || name == "(local)" || name == "localhost" || name.Length == 0)
{
return System.Environment.MachineName;
}
// named instances on the above exceptions
if (name.StartsWith(".\\", StringComparison.Ordinal))
{
return name.Replace(".", System.Environment.MachineName);
}
if (name.StartsWith("(local)\\", StringComparison.Ordinal))
{
return name.Replace("(local)", System.Environment.MachineName);
}
return name;
}
// returns the name of the type in the urn expression
public static string UrnSuffix
{
get
{
return "Server";
}
}
/// <summary>
/// This object supports permissions.
/// </summary>
internal override UserPermissionCollection Permissions
{
get
{
// call the base class
return GetUserPermissions();
}
}
/// <summary>
/// Returns the comparer object corresponding to the collation string passed.
/// </summary>
/// <param name="collationName"></param>
/// <returns></returns>
public IComparer GetStringComparer(string collationName)
{
int lcid = GetLCIDCollation(collationName);
StringComparer comparer = new StringComparer(collationName, lcid);
return comparer;
}
//given a collation name, reads the collation atributes from server
//and constructs a StringComparer
SortedList collationCache;
internal int GetLCIDCollation(string collationName)
{
//Latin1 this is a collation hardcoded for some of the metadata
//columns make it a special case
//excluding SQL_Latin1_General_CP1254 as its lcid is 1055 instead of 1033
if (collationName.Contains("Latin1") && !collationName.Contains("SQL_Latin1_General_CP1254"))
{
return 1033;
}
//VSTS 763652: "Culture isn't supported failure" is hit using SSMS to connect SQL instance when SQLCOLLATION="Japanese_Unicode_CS_AS_KS_WS".
//According to msdn http://support.microsoft.com/?id=302747, Japanese_Unicode
//has been deprecated from Windows Server 2000 onwards. The link suggests to use LCID 1041 in the clients.
if (collationName.StartsWith("Japanese_Unicode", StringComparison.Ordinal))
{
return 1041;
}
// Try to get the LCID without trying to get to the server, which can be unnecessary expensive
// If the collation does not happen to be known, then we'll pay the price of a trip to the server.
var colInfo = CollationInfo.GetCollationInfo(collationName);
if (colInfo != null)
{
return colInfo.LCID;
}
//initialize the collation cache if needed
if (null == collationCache)
{
collationCache = new SortedList(System.StringComparer.Ordinal);
}
//if we don't already store the collation lcid
//we have to get it from the server
if (!collationCache.Contains(collationName))
{
//build enumerator rquest
Request req = new Request(
"Server/Collation[@Name = '" + Urn.EscapeString(collationName) + "']",
new String[] { "LocaleID" });
DataTable collationTable = this.ExecutionManager.GetEnumeratorData(req);
//if we have something valid use it
if (collationTable.Rows.Count == 1 && !(collationTable.Rows[0][0] is DBNull))
{
collationCache[collationName] = (int)collationTable.Rows[0][0];
}
//else fall back to 1033
else
{
collationCache[collationName] = 1033;
}
}
return (int)collationCache[collationName];
}
/// <summary>
/// Returns the object with the corresponding Urn in string form
/// </summary>
/// <param name="urn"></param>
/// <returns></returns>
object IAlienRoot.SfcHelper_GetSmoObject(string urn)
{
return GetSmoObject(new Urn(urn));
}
/// <summary>
///
/// Helper for SFC. Ask Enumerator for a DataTable of results given a Urn.
/// </summary>
/// <returns>DataTable</returns>
DataTable IAlienRoot.SfcHelper_GetDataTable(object connection, string urn, string[] fields,
Microsoft.SqlServer.Management.Sdk.Sfc.OrderBy[] orderByFields)
{
OrderBy[] smoOrderByFields = null;
if (null != orderByFields)
{
smoOrderByFields = new OrderBy[orderByFields.Length];
orderByFields.CopyTo(smoOrderByFields, 0);
}
return Enumerator.GetData(connection, new Urn(urn), fields, smoOrderByFields);
}
void IAlienRoot.DesignModeInitialize()
{
//ensure the server is disconnected.
//For design mode, server version is required. we set the server version to be latest known version.
FileVersionInfo latestVersion = FileVersionInfo.GetVersionInfo(this.GetType().GetAssembly().Location);
this.ConnectionContext.ServerVersion = new ServerVersion(latestVersion.FileMajorPart, latestVersion.FileMinorPart);
this.ConnectionContext.TrueName = "DesignMode";
//sever connection.
((ISfcHasConnection)this).ConnectionContext.Mode = SfcConnectionContextMode.Offline;
}
/// <summary>
/// Helper for SFC. Query and iterator/enumerator interfaces should be the level we abstract at, but for now
/// we make sure caching via InitChildLevel is done while we still give back the list of Urns.
/// </summary>
/// <returns>The list of SMO Urns.</returns>
List<string> IAlienRoot.SfcHelper_GetSmoObjectQuery(string urn, string[] fields, OrderBy[] orderByFields)
{
return GetSmoObjectQuery(new Urn(urn), fields, orderByFields);
}
/// <summary>
/// Execute the given query and return the list of Urns matching it.
/// The objects representing the Urns are all cached for subsequent access via the usual collections and GetSmoObject.
/// </summary>
/// <param name="queryString">The XPath query string to satisfy.</param>
/// <param name="fields">The fields to ensure are present in all leaf-type objects matched, or null for default fields.</param>
/// <param name="orderByFields">The fields to order the resulting list of Urns, or null for default ordering.</param>
/// <returns>The list of SMO Urns satisfying the query.</returns>
private List<string> GetSmoObjectQuery(string queryString, string[] fields, OrderBy[] orderByFields)
{
// Prime a few things that otherwise would cause a DataReader in use exception deeper in
string dummyEdition = this.Information.Edition;
Urn fullQueryUrn = new Urn(queryString);
XPathExpression parsedUrn = fullQueryUrn.XPathExpression;
int nodeCount = parsedUrn.Length;
if (nodeCount < 1)
{
throw new InternalSmoErrorException(ExceptionTemplates.CallingInitChildLevelWithWrongUrn(fullQueryUrn));
}
// Do a top-down query though each level of the Urn, to cause ancestors to be cached and present at each level.
GetSmoObjectQueryRec(new Urn(queryString));
List<string> urnList = null;
try
{
// See if any additional fields needed for the true leaf type query
string[] infrastructureFields = null;
switch (parsedUrn[parsedUrn.Length - 1].Name)
{
default:
// No extra fields at this time to add, apart from the ones on the early passes in the recursive part
break;
}
urnList = InitQueryUrns(fullQueryUrn, fields, orderByFields, infrastructureFields);
}
catch (ArgumentException e)
{
throw new ArgumentException(ExceptionTemplates.UnsupportedObjectQueryUrn(queryString), e);
}
return urnList;
}
private void GetSmoObjectQueryRec(Urn urn)
{
urn = urn.Parent;
if (urn == null || urn.Parent == null)
{
// Stop recursing if we are on the "Server" part, since it doesn't really mean anythign to query for just a server.
return;
}
// Since these are intermediate top-down queries for caching purposes, don't pass any request info yet.
GetSmoObjectQueryRec(urn);
// From the top-down (left to right in the Urn), we need to perform a query to cache the ancestor infrastructure
XPathExpression parsedUrn = urn.XPathExpression;
// Add special fields we know get asked for for certain types when they are the leaf,
// otherwise the queries are way too inefficient
int nodeCount = parsedUrn.Length;
Type t = GetChildType(parsedUrn[nodeCount - 1].Name,
(nodeCount > 1) ? parsedUrn[nodeCount - 2].Name : this.GetType().Name);
string[] fields = GetQueryTypeInfrastructureFields(t);
InitQueryUrns(urn, fields, null, null);
}
/// <summary>
/// Returns the object with the corresponding Urn
/// </summary>
/// <param name="urn"></param>
/// <returns></returns>
public SqlSmoObject GetSmoObject(Urn urn)
{
#if DEBUGTRACE
Trace("Entering: Server.GetSmoObject( " + urn + ")");
#endif
try
{
if (null == urn)
{
throw new ArgumentNullException("urn");
}
if ("Default" == urn.Type && "Column" == urn.Parent.Type)
{
Column c = GetSmoObjectRec(urn.Parent) as Column;
return c.GetDefaultConstraintBaseByName(urn.GetAttribute("Name"));
}
if ("DatabaseOption" == urn.Type)
{
Database d = GetSmoObjectRec(urn.Parent) as Database;
return d.DatabaseOptions;
}
return GetSmoObjectRec(urn);
}
catch (Exception e)
{
FilterException(e);
throw new FailedOperationException(ExceptionTemplates.GetSmoObject, this, e);
}
}
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Microsoft.SqlServer.Management.Smo.SmoException.#ctor(System.String)")]
private SqlSmoObject GetSmoObjectRec(Urn urn)
{
// stop condition goes first
// TODO: add code to handle urn's that do not contain server
if (null == urn.Parent)
{
if (urn.Type == "Server")
{
CheckValidUrnServerLevel(urn.XPathExpression[0]);
return this;
}
else
{
throw new SmoException("For the moment we don't support Urn's that do not start with Server");
}
}
// we are going down one level to get the parent object
SqlSmoObject parentNode = GetSmoObjectRec(urn.Parent);
// we'll try to get the child object here. This can fail if parent
// does not have this node in the child collection
string nodeType = urn.Type;
// take care of the special case of objects that are not in a collection
nodeType = String.Intern(nodeType); // faster comparison in switch
/*
if( nodeType == ServiceBroker.UrnSuffix)
return ( ((Database)parentNode).ServiceBroker );
*/
if (nodeType == JobServer.UrnSuffix)
{
return ((Server)parentNode).JobServer;
}
if (nodeType == AlertSystem.UrnSuffix)
{
return ((JobServer)parentNode).AlertSystem;
}
if (nodeType == UserOptions.UrnSuffix)
{
return ((Server)parentNode).UserOptions;
}
if (nodeType == Information.UrnSuffix)
{
return ((Server)parentNode).Information;
}
if (nodeType == Settings.UrnSuffix)
{
return ((Server)parentNode).Settings;
}
if (nodeType == FullTextIndex.UrnSuffix)
{
return ((TableViewBase)parentNode).FullTextIndex;
}
if (nodeType == DefaultConstraint.UrnSuffix &&
parentNode is Microsoft.SqlServer.Management.Smo.Column)
{
return ((Column)parentNode).DefaultConstraint;
}
if (nodeType == DatabaseOptions.UrnSuffix)
{
return ((Database)parentNode).DatabaseOptions;
}
if (nodeType == SqlMail.UrnSuffix)
{
return ((Server)parentNode).Mail;
}
if (nodeType == SoapPayload.UrnSuffix)
{
return ((Endpoint)parentNode).Payload.Soap;
}
if (nodeType == DatabaseMirroringPayload.UrnSuffix)
{
return ((Endpoint)parentNode).Payload.DatabaseMirroring;
}
if (nodeType == ServiceBrokerPayload.UrnSuffix &&
parentNode is Microsoft.SqlServer.Management.Smo.Endpoint)
{
return ((Endpoint)parentNode).Payload.ServiceBroker;
}
if (nodeType == HttpProtocol.UrnSuffix)
{
return ((Endpoint)parentNode).Protocol.Http;
}
if (nodeType == TcpProtocol.UrnSuffix)
{
return ((Endpoint)parentNode).Protocol.Tcp;
}
if (nodeType == ServiceBroker.UrnSuffix)
{
return ((Database)parentNode).ServiceBroker;
}
if (nodeType == DatabaseEncryptionKey.UrnSuffix)
{
return ((Database)parentNode).DatabaseEncryptionKey;
}
if (nodeType == ServiceMasterKey.UrnSuffix &&
parentNode is Microsoft.SqlServer.Management.Smo.Server)
{
return ((Server)parentNode).ServiceMasterKey;
}
if (nodeType == MasterKey.UrnSuffix &&
parentNode is Microsoft.SqlServer.Management.Smo.Database)
{
return ((Database)parentNode).MasterKey;
}
if (nodeType == ResourceGovernor.UrnSuffix)
{
return ((Server)parentNode).ResourceGovernor;
}
if (nodeType == ServerProxyAccount.UrnSuffix)
{
return ((Server)parentNode).ProxyAccount;
}
if (nodeType == SmartAdmin.UrnSuffix)
{
return ((Server)parentNode).SmartAdmin;
}
if (nodeType == FullTextService.UrnSuffix)
{
return ((Server)parentNode).FullTextService;
}
if (nodeType == QueryStoreOptions.UrnSuffix)
{
return ((Database) parentNode).QueryStoreOptions;
}
// retrieve the child collection
object childCollection = SqlSmoObject.GetChildCollection(parentNode,
urn.XPathExpression,
urn.XPathExpression.Length - 1,
ServerVersion);
// transform the Urn filter into a key
ObjectKeyBase childKey = ((AbstractCollectionBase)childCollection).CreateKeyFromUrn(urn);
// get the child object from child collection
SqlSmoObject thisNode = ((SmoCollectionBase)childCollection).GetObjectByKey(childKey) as SqlSmoObject;
if (null == thisNode)
{
throw new MissingObjectException(ExceptionTemplates.ObjectDoesNotExist(GetTypeName(nodeType), childKey.ToString()));
}
return thisNode;
}
/// <summary>
/// Alter the metadata for the server, including dependent child objects such as Configuration, Information, and Settings.
/// The Configuration class will not override value checking with this call.
/// </summary>
public void Alter()
{
this.overrideValueChecking = false;
base.AlterImpl();
}
// the base class doesn't allow passing values from alter to ScriptAlter()
// thus we have to use a shared variable between the two methods
bool overrideValueChecking = false;
/// <summary>
/// Alter the metadata for the server, including dependent child objects such as Configuration, Information, and Settings.
/// </summary>
/// <param name="overrideValueChecking">Boolean property value that specifies whether the Configuration changes should be installed with "RECONFIGURE WITH OVERRRIDE"</param>
public void Alter(bool overrideValueChecking)
{
this.overrideValueChecking = overrideValueChecking;
base.AlterImpl();
}
internal override void ScriptAlter(StringCollection query, ScriptingPreferences sp)
{
//script configurations
if (null != m_config)
{
m_config.ScriptAlter(query, sp, this.overrideValueChecking);
}
if (null != this.affinityInfo)
{
this.affinityInfo.Alter();
}
ScriptProperties(query, sp);
}
// the initial TextMode property value for TextObjects
bool defaultTextMode = true;
public bool DefaultTextMode
{
get { return defaultTextMode; }
set { defaultTextMode = value; }
}
/// <summary>
/// Detach a database
/// </summary>
public void DetachDatabase(string databaseName, bool updateStatistics)
{
if (null == databaseName)
{
throw new ArgumentNullException("databaseName");
}
try
{
DetachDatabaseWorker(databaseName, updateStatistics, false, false);
}
catch (Exception e)
{
FilterException(e);
throw new FailedOperationException(ExceptionTemplates.DetachDatabase, this, e);
}
}
/// <summary>
/// Detach a database
/// </summary>
public void DetachDatabase(string databaseName, bool updateStatistics, bool removeFulltextIndexFile)
{
ThrowIfBelowVersion90();
if (null == databaseName)
{
throw new ArgumentNullException("databaseName");
}
try
{
DetachDatabaseWorker(databaseName, updateStatistics, true, removeFulltextIndexFile);
}
catch (Exception e)
{
FilterException(e);
throw new FailedOperationException(ExceptionTemplates.DetachDatabase, this, e);
}
}
private void DetachDatabaseWorker(string name, bool updateStatistics, bool emitFT, bool dropFulltextIndexFile)
{
if (!Databases.Contains(name))
{
throw new MissingObjectException(ExceptionTemplates.ObjectDoesNotExist(ExceptionTemplates.Database, name));
}
StringCollection query = new StringCollection();
query.Add("USE [master]"); //release this possible lock on the detaching db
StringBuilder sbStatement = new StringBuilder();
sbStatement.AppendFormat(SmoApplication.DefaultCulture, "EXEC master.dbo.sp_detach_db @dbname = N'{0}'", SqlString(name));
if (updateStatistics)
{
sbStatement.Append(", @skipchecks = 'false'");
}
if (emitFT)
{
sbStatement.AppendFormat(SmoApplication.DefaultCulture,
", @keepfulltextindexfile=N'{0}'", dropFulltextIndexFile ? "false" : "true");
}
query.Add(sbStatement.ToString());
// detach database from the server
this.ExecutionManager.ExecuteNonQuery(query);
// remove the object from the collection
Databases[name].MarkDroppedInternal();
Databases.RemoveObject(new SimpleObjectKey(name));
if (!this.ExecutionManager.Recording)
{
if (!SmoApplication.eventsSingleton.IsNullDatabaseEvent())
{
// give back a 'fake' Urn - the database does not exist anymore
// we are consistent with Drop(), where we also return the Urn of the dropped object
// this is needed so clients can identify the object just from the
// context of the event args
Urn detachedUrn = new Urn(this.Urn + string.Format(SmoApplication.DefaultCulture, "/Database[@Name='{0}']", Urn.EscapeString(name)));
SmoApplication.eventsSingleton.CallDatabaseEvent(this, new DatabaseEventArgs(
detachedUrn, null, name, DatabaseEventType.Detach));
}
}
}
/// <summary>
/// Worker function for various attach overloads
/// </summary>
/// <param name="name"></param>
/// <param name="files"></param>
/// <param name="owner"></param>
/// <param name="attachOptions"></param>
private void AttachDatabaseWorker(string name,
StringCollection files,
string owner,
AttachOptions attachOptions)
{
try
{
StringCollection query = new StringCollection();
if (files.Count < 1)
{
throw new ArgumentException(ExceptionTemplates.TooFewFiles);
}
if (this.Databases.Contains(name))
{
throw new SmoException(ExceptionTemplates.DatabaseAlreadyExists);
}
if (name.Length == 0)
{
throw new ArgumentException(ExceptionTemplates.EmptyInputParam("name", "string"));
}
if (owner != null && owner.Length == 0)
{
throw new ArgumentException(ExceptionTemplates.EmptyInputParam("owner", "string"));
}
StringBuilder statement = new StringBuilder();
statement.AppendFormat(SmoApplication.DefaultCulture, "CREATE DATABASE [{0}] ON ", SqlBraket(name));
for (int i = 0; i < files.Count; i++)
{
string filename = files[i];
if (i != 0)
{
statement.Append(Globals.comma);
}
statement.Append(Globals.newline);
statement.Append(Globals.LParen);
statement.AppendFormat(SmoApplication.DefaultCulture, " FILENAME = N'{0}' ", SqlString(filename));
statement.Append(Globals.RParen);
}
statement.Append(Globals.newline);
if (this.ServerVersion.Major >= 9)
{
if (attachOptions == AttachOptions.RebuildLog)
{
statement.Append(" FOR ATTACH_REBUILD_LOG");
}
else
{
statement.Append(" FOR ATTACH");
switch (attachOptions)
{
case AttachOptions.EnableBroker:
statement.Append(" WITH ENABLE_BROKER");
break;
case AttachOptions.NewBroker:
statement.Append(" WITH NEW_BROKER");
break;
case AttachOptions.ErrorBrokerConversations:
statement.Append(" WITH ERROR_BROKER_CONVERSATIONS");
break;
case AttachOptions.None:
//
// do nothing.
//
break;
default:
throw new ArgumentException(ExceptionTemplates.UnknownEnumeration("AttachOptions"));
}
}
}
else
{
statement.Append(" FOR ATTACH");
}
query.Add(Scripts.USEMASTER);
query.Add(statement.ToString());
if (null != owner)
{
// try to change the owner of the database
string sysname = string.Empty;
string dbsidfieldname = string.Empty;
if (this.ServerVersion.Major <= 8)
{
sysname = "master.dbo.sysdatabases";
dbsidfieldname = "sid";
}
else
{
sysname = "master.sys.databases";
dbsidfieldname = "owner_sid";
}
query.Add(string.Format(SmoApplication.DefaultCulture, "if exists (select name from {0} sd where name = N'{1}' and SUSER_SNAME(sd.{2}) = SUSER_SNAME() ) " +
"EXEC [{3}].dbo.sp_changedbowner @loginame=N'{4}', @map=false",
sysname, SqlString(name), dbsidfieldname,
SqlBraket(name), SqlString(owner)));
}
this.ExecutionManager.ExecuteNonQuery(query);
// add the new database to the collection
Databases.InitializeChildObject(new SimpleObjectKey(name));
if (!this.ExecutionManager.Recording)
{
if (!SmoApplication.eventsSingleton.IsNullDatabaseEvent())
{
SmoApplication.eventsSingleton.CallDatabaseEvent(this, new DatabaseEventArgs(
Databases[name].Urn, Databases[name], name, DatabaseEventType.Attach));
}
}
}
catch (Exception e)
{
FilterException(e);
throw new FailedOperationException(ExceptionTemplates.AttachDatabase, this, e);
}
}
/// <summary>
/// Attach Database
/// </summary>
/// <param name="name">database name</param>
/// <param name="files">list of files to attach</param>
/// <param name="owner">new owner name</param>
public void AttachDatabase(string name, StringCollection files, string owner)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
if (null == files)
{
throw new ArgumentNullException("files");
}
if (null == owner)
{
throw new ArgumentNullException("owner");
}
AttachDatabaseWorker(name, files, owner, AttachOptions.None);
}
/// <summary>
/// Attach Database
/// </summary>
/// <param name="name">database name</param>
/// <param name="files">file list</param>
public void AttachDatabase(string name, StringCollection files)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
if (null == files)
{
throw new ArgumentNullException("files");
}
AttachDatabaseWorker(name, files, null, AttachOptions.None);