/
SqlLocalDbApi.cs
1404 lines (1227 loc) · 51.5 KB
/
SqlLocalDbApi.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) Martin Costello, 2012-2018. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using MartinCostello.SqlLocalDb.Interop;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace MartinCostello.SqlLocalDb;
/// <summary>
/// A class representing a wrapper to the SQL Server LocalDB Instance API. This class cannot be inherited.
/// </summary>
public sealed class SqlLocalDbApi : ISqlLocalDbApi, ISqlLocalDbApiAdapter, IDisposable
{
/// <summary>
/// The name of the default instance in SQL LocalDB 2012.
/// </summary>
private const string DefaultInstanceName2012 = "v11.0";
/// <summary>
/// The name of the default instance in SQL LocalDB 2014 and later.
/// </summary>
private const string DefaultInstanceName2014AndLater = "MSSQLLocalDB";
/// <summary>
/// The maximum length of a SQL LocalDB instance name, in bytes.
/// </summary>
private const int MaxInstanceNameLength = (LocalDbInstanceApi.MaximumInstanceNameLength + 1) * sizeof(char);
/// <summary>
/// The maximum length of a SQL LocalDB version string, in bytes.
/// </summary>
private const int MaxVersionLength = (LocalDbInstanceApi.MaximumInstanceVersionLength + 1) * sizeof(char);
/// <summary>
/// The value to pass to functions which have a reserved parameter for future use.
/// </summary>
private const int ReservedValue = 0;
/// <summary>
/// The native API. This field is read-only.
/// </summary>
private readonly LocalDbInstanceApi _api;
/// <summary>
/// Whether the instance has been disposed of.
/// </summary>
private bool _disposed;
/// <summary>
/// The available versions of SQL Server LocalDB installed on the local machine.
/// </summary>
private string[]? _versions;
/// <summary>
/// The timeout for stopping an instance of LocalDB.
/// </summary>
private TimeSpan _stopTimeout;
/// <summary>
/// Initializes a new instance of the <see cref="SqlLocalDbApi"/> class.
/// </summary>
public SqlLocalDbApi()
: this(new SqlLocalDbOptions(), NullLoggerFactory.Instance)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SqlLocalDbApi"/> class.
/// </summary>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="loggerFactory"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// <paramref name="loggerFactory"/> did create the required loggers.
/// </exception>
public SqlLocalDbApi(ILoggerFactory loggerFactory)
: this(new SqlLocalDbOptions(), loggerFactory)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SqlLocalDbApi"/> class.
/// </summary>
/// <param name="options">The <see cref="SqlLocalDbOptions"/> to use.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="options"/> or <paramref name="loggerFactory"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// <paramref name="loggerFactory"/> did create the required loggers.
/// </exception>
public SqlLocalDbApi(SqlLocalDbOptions options, ILoggerFactory loggerFactory)
: this(options, new WindowsRegistry(), loggerFactory)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SqlLocalDbApi"/> class.
/// </summary>
/// <param name="options">The <see cref="SqlLocalDbOptions"/> to use.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use.</param>
/// <param name="registry">The <see cref="IRegistry"/> to use.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="options"/>, <paramref name="registry"/> or <paramref name="loggerFactory"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// <paramref name="loggerFactory"/> did not create the required loggers.
/// </exception>
internal SqlLocalDbApi(SqlLocalDbOptions options, IRegistry registry, ILoggerFactory loggerFactory)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
#pragma warning disable CA1508
Logger = loggerFactory.CreateLogger<SqlLocalDbApi>() ?? throw new InvalidOperationException(SRHelper.Format(SR.SqlLocalDbApi_NoLoggerFormat, nameof(SqlLocalDbApi)));
var apiLogger = loggerFactory.CreateLogger<LocalDbInstanceApi>() ?? throw new InvalidOperationException(SRHelper.Format(SR.SqlLocalDbApi_NoLoggerFormat, nameof(LocalDbInstanceApi)));
#pragma warning restore CA1508
AutomaticallyDeleteInstanceFiles = options.AutomaticallyDeleteInstanceFiles;
LanguageId = options.LanguageId;
StopOptions = options.StopOptions;
StopTimeout = options.StopTimeout;
_api = new LocalDbInstanceApi(options.NativeApiOverrideVersion, registry, apiLogger);
}
/// <summary>
/// Gets or sets a value indicating whether to automatically delete the
/// files associated with SQL LocalDB instances when they are deleted.
/// </summary>
/// <remarks>
/// Setting the value of this property affects the behavior of all delete
/// operations in the current <see cref="AppDomain"/> unless the overloads
/// of <see cref="DeleteInstance(string, bool)"/> and <see cref="DeleteUserInstances(bool)"/> are
/// used. The default value is <see langword="false"/>, unless overridden
/// by the <c>SQLLocalDB:AutomaticallyDeleteInstanceFiles</c> application configuration setting.
/// </remarks>
public bool AutomaticallyDeleteInstanceFiles { get; set; }
/// <summary>
/// Gets the name of the default SQL LocalDB instance.
/// </summary>
public string DefaultInstanceName
{
get
{
// Force the native API to be loaded so we can determine its version
if (!IsLocalDBInstalled())
{
// It isn't installed, so don't assume anything
return string.Empty;
}
if (_api.NativeApiVersion!.Major == 11)
{
return DefaultInstanceName2012;
}
// Provided Microsoft do not change the default name again this should work for all versions 12.0+
return DefaultInstanceName2014AndLater;
}
}
/// <summary>
/// Gets or sets the locale ID (LCID) to use for formatting error messages.
/// </summary>
/// <remarks>
/// The default value for this property is zero, in which case the <c>Win32</c> <c>FormatMessage</c> language
/// order is used. This property is provided for integrators to specifically override the language used from
/// the defaults used by the local installed operating system.
/// </remarks>
public int LanguageId { get; set; }
/// <summary>
/// Gets the version string for the latest installed version of SQL Server LocalDB.
/// </summary>
/// <exception cref="InvalidOperationException">
/// No versions of SQL Server LocalDB are installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
public string LatestVersion
{
get
{
EnsurePlatformSupported();
// Access through property to ensure initialized
IReadOnlyList<string> versions = Versions;
if (versions.Count < 1)
{
string message = SRHelper.Format(SR.SqlLocalDbApi_NoVersionsFormat, Environment.MachineName);
throw new InvalidOperationException(message);
}
// Return the version with the highest number
return versions
.Select((p) => new Version(p))
.OrderBy((p) => p)
.Last()
.ToString();
}
}
/// <summary>
/// Gets or sets the options to use when stopping instances of SQL LocalDB.
/// </summary>
public StopInstanceOptions StopOptions { get; set; }
/// <summary>
/// Gets or sets the default timeout to use when
/// stopping instances of SQL LocalDB.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is less than <see cref="TimeSpan.Zero"/>.
/// </exception>
public TimeSpan StopTimeout
{
get
{
return _stopTimeout;
}
set
{
if (value < TimeSpan.Zero)
{
string message = SRHelper.Format(SR.SqlLocalDbApi_TimeoutTooSmallFormat, nameof(value));
throw new ArgumentOutOfRangeException(nameof(value), value, message);
}
_stopTimeout = value;
}
}
/// <summary>
/// Gets an <see cref="IList{T}"/> of <see cref="string"/> containing
/// the available versions of SQL LocalDB.
/// </summary>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The installed versions of SQL LocalDB could not be determined.
/// </exception>
public IReadOnlyList<string> Versions
{
get
{
if (!IsWindows)
{
return [];
}
// Use lazy initialization to allow some functionality to be
// accessed regardless of whether LocalDB is installed
_versions ??= GetLocalDbVersions();
return (string[])_versions.Clone();
}
}
/// <inheritdoc />
ISqlLocalDbApi ISqlLocalDbApiAdapter.LocalDb => this;
/// <summary>
/// Gets a value indicating whether the executing platform is Microsoft Windows.
/// </summary>
internal static bool IsWindows { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
/// <summary>
/// Gets the <see cref="ILoggerFactory"/> to use.
/// </summary>
internal ILoggerFactory LoggerFactory { get; }
/// <summary>
/// Gets the <see cref="ILogger"/> to use.
/// </summary>
private ILogger Logger { get; }
/// <summary>
/// Gets the full path of the directory containing the SQL LocalDB instance files for the current user.
/// </summary>
/// <returns>
/// The full path of the directory containing the SQL LocalDB instance files for the current user.
/// </returns>
/// <remarks>
/// The folder usually used to store SQL LocalDB instance files is <c>%LOCALAPPDATA%\Microsoft\Microsoft SQL Server Local DB\Instances</c>.
/// </remarks>
public static string GetInstancesFolderPath()
{
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Microsoft",
"Microsoft SQL Server Local DB",
"Instances");
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates a new instance of SQL Server LocalDB.
/// </summary>
/// <param name="instanceName">The name of the LocalDB instance.</param>
/// <returns>
/// An <see cref="ISqlLocalDbInstanceInfo"/> containing information about the instance that was created.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// No versions of SQL Server LocalDB are installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could
/// not be stopped or the installed versions of SQL LocalDB could not be determined.
/// </exception>
public ISqlLocalDbInstanceInfo CreateInstance(string instanceName) => CreateInstance(instanceName, LatestVersion);
/// <summary>
/// Creates a new instance of SQL Server LocalDB.
/// </summary>
/// <param name="instanceName">The name of the LocalDB instance.</param>
/// <param name="version">The version of SQL Server LocalDB to use.</param>
/// <returns>
/// An <see cref="ISqlLocalDbInstanceInfo"/> containing information about the instance that was created.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> or <paramref name="version"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> and <paramref name="version"/> could not be created.
/// </exception>
public ISqlLocalDbInstanceInfo CreateInstance(string instanceName, string version)
{
if (instanceName == null)
{
throw new ArgumentNullException(nameof(instanceName));
}
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
Logger.CreatingInstance(instanceName, version);
InvokeThrowOnError(
() => _api.CreateInstance(version, instanceName, ReservedValue),
EventIds.CreatingInstanceFailed,
instanceName);
Logger.CreatedInstance(instanceName, version);
return GetInstanceInfo(instanceName);
}
/// <summary>
/// Deletes the specified SQL Server LocalDB instance.
/// </summary>
/// <param name="instanceName">
/// The name of the LocalDB instance to delete.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not be deleted.
/// </exception>
public void DeleteInstance(string instanceName) => DeleteInstance(instanceName, deleteFiles: AutomaticallyDeleteInstanceFiles);
/// <summary>
/// Deletes the specified SQL Server LocalDB instance.
/// </summary>
/// <param name="instanceName">
/// The name of the LocalDB instance to delete.
/// </param>
/// <param name="deleteFiles">
/// Whether to delete the file(s) associated with the SQL LocalDB instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not be deleted.
/// </exception>
public void DeleteInstance(string instanceName, bool deleteFiles)
{
DeleteInstanceInternal(instanceName, throwIfNotFound: true, deleteFiles: deleteFiles);
}
/// <summary>
/// Deletes all user instances of SQL LocalDB on the current machine.
/// </summary>
/// <returns>
/// The number of user instances of SQL LocalDB that were deleted.
/// </returns>
/// <remarks>
/// The default instance(s) of any version(s) of SQL LocalDB that are
/// installed on the local machine are not deleted.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
public int DeleteUserInstances() => DeleteUserInstances(deleteFiles: AutomaticallyDeleteInstanceFiles);
/// <summary>
/// Deletes all user instances of SQL LocalDB on the current machine,
/// optionally also deleting all of the file(s) associated with the
/// SQL LocalDB user instance(s) from disk.
/// </summary>
/// <param name="deleteFiles">
/// Whether to delete the file(s) associated with the SQL LocalDB user instance(s).
/// </param>
/// <returns>
/// The number of user instances of SQL LocalDB that were deleted.
/// </returns>
/// <remarks>
/// The default instance(s) of any version(s) of SQL LocalDB that are
/// installed on the local machine are not deleted.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
public int DeleteUserInstances(bool deleteFiles)
{
int instancesDeleted = 0;
IReadOnlyList<string> instanceNames = GetInstanceNames();
foreach (string instanceName in instanceNames)
{
ISqlLocalDbInstanceInfo info = GetInstanceInfo(instanceName);
// Do not try to delete automatic instances.
// These are the default instances created for each version.
// As of SQL LocalDB 2014, the default instance is named 'MSSQLLocalDB'.
if (!info.Exists ||
info.IsAutomatic ||
string.Equals(info.Name, DefaultInstanceName2014AndLater, StringComparison.Ordinal))
{
continue;
}
// In some cases, SQL LocalDB may report instance names in calls
// to enumerate the instances that do not actually exist. Presumably
// this can occur if the installation/instances become corrupted.
// Such failures to delete an instance should be ignored
try
{
if (DeleteInstanceInternal(instanceName, throwIfNotFound: false, deleteFiles: deleteFiles))
{
instancesDeleted++;
}
}
catch (SqlLocalDbException ex)
{
if (ex.ErrorCode == SqlLocalDbErrors.InstanceBusy)
{
Logger.DeletingInstanceFailedAsInUse(ex, ex.InstanceName);
continue;
}
throw;
}
}
return instancesDeleted;
}
/// <summary>
/// Returns information about the specified LocalDB instance.
/// </summary>
/// <param name="instanceName">The name of the LocalDB instance to get the information for.</param>
/// <returns>
/// An instance of <see cref="ISqlLocalDbInstanceInfo"/> containing information
/// about the LocalDB instance specified by <paramref name="instanceName"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The information for the SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not obtained.
/// </exception>
public ISqlLocalDbInstanceInfo GetInstanceInfo(string instanceName)
{
if (instanceName == null)
{
throw new ArgumentNullException(nameof(instanceName));
}
Logger.GettingInstanceInfo(instanceName);
LocalDbInstanceInfo info;
int size = LocalDbInstanceInfo.MarshalSize;
IntPtr ptrInfo = Marshal.AllocHGlobal(size);
try
{
InvokeThrowOnError(
() => _api.GetInstanceInfo(instanceName, ptrInfo, size),
EventIds.GettingInstanceInfoFailed,
instanceName);
info = Marshal.PtrToStructure<LocalDbInstanceInfo>(ptrInfo);
}
finally
{
Marshal.FreeHGlobal(ptrInfo);
}
Logger.GotInstanceInfo(instanceName);
var result = new SqlLocalDbInstanceInfo(this);
result.Update(info);
return result;
}
/// <summary>
/// Returns the names of all the SQL Server LocalDB instances for the current user.
/// </summary>
/// <returns>
/// The names of the the SQL Server LocalDB instances for the current user.
/// </returns>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance names could not be determined.
/// </exception>
public IReadOnlyList<string> GetInstanceNames()
{
EnsurePlatformSupported();
Logger.GettingInstanceNames();
// Query the LocalDB API to get the number of instances
int count = 0;
int hr = _api.GetInstanceNames(IntPtr.Zero, ref count);
if (hr != 0 &&
hr != SqlLocalDbErrors.InsufficientBuffer)
{
throw GetLocalDbError(hr, EventIds.GettingInstanceNamesFailed);
}
string[] names;
// Allocate enough memory to receive the instance name array
int nameLength = MaxInstanceNameLength;
IntPtr ptrNames = Marshal.AllocHGlobal(nameLength * count);
try
{
InvokeThrowOnError(
() => _api.GetInstanceNames(ptrNames, ref count),
EventIds.GettingInstanceNamesFailed);
// Read the instance names back from unmanaged memory
names = MarshalStringArray(ptrNames, nameLength, count);
}
finally
{
Marshal.FreeHGlobal(ptrNames);
}
Logger.GotInstanceNames(names.Length);
return names;
}
/// <summary>
/// Returns information about the specified LocalDB version.
/// </summary>
/// <param name="version">The name of the LocalDB version to get the information for.</param>
/// <returns>
/// An instance of <see cref="ISqlLocalDbVersionInfo"/> containing information
/// about the LocalDB version specified by <paramref name="version"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="version"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The information for the SQL Server LocalDB version specified by <paramref name="version"/> could not be obtained.
/// </exception>
public ISqlLocalDbVersionInfo GetVersionInfo(string version)
{
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
Logger.GettingVersionInfo(version);
LocalDbVersionInfo info;
int size = LocalDbVersionInfo.MarshalSize;
IntPtr ptrInfo = Marshal.AllocHGlobal(size);
try
{
InvokeThrowOnError(
() => _api.GetVersionInfo(version, ptrInfo, size),
EventIds.GettingVersionInfoFailed);
info = Marshal.PtrToStructure<LocalDbVersionInfo>(ptrInfo);
}
finally
{
Marshal.FreeHGlobal(ptrInfo);
}
Logger.GotVersionInfo(version);
var result = new SqlLocalDbVersionInfo();
result.Update(info);
return result;
}
/// <summary>
/// Returns whether the specified LocalDB instance exists.
/// </summary>
/// <param name="instanceName">The name of the LocalDB instance to check for existence.</param>
/// <returns>
/// <see langword="true"/> if the LocalDB instance specified by
/// <paramref name="instanceName"/> exists; otherwise <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// Whether the SQL Server LocalDB instance specified by <paramref name="instanceName"/> exists could not be determined.
/// </exception>
public bool InstanceExists(string instanceName)
{
try
{
return GetInstanceInfo(instanceName).Exists;
}
catch (SqlLocalDbException ex) when (ex.ErrorCode == SqlLocalDbErrors.UnknownInstance)
{
return false;
}
}
/// <summary>
/// Returns whether SQL LocalDB is installed on the current machine.
/// </summary>
/// <returns>
/// <see langword="true"/> if SQL Server LocalDB is installed on the
/// current machine; otherwise <see langword="false"/>.
/// </returns>
public bool IsLocalDBInstalled()
{
// SQL LocalDB is only supported on Windows, so shortcut
if (!IsWindows)
{
return false;
}
// Call one of the "get info" functions with a zero buffer.
// If LocalDB is installed, it will return a "buffer too small" HRESULT,
// otherwise it will return the "not installed" HRESULT.
int notUsed = 0;
int hr = _api.GetVersions(IntPtr.Zero, ref notUsed);
return hr != SqlLocalDbErrors.NotInstalled;
}
/// <summary>
/// Shares the specified SQL Server LocalDB instance with other
/// users of the computer, using the specified shared name.
/// </summary>
/// <param name="ownerSid">The SID of the instance owner.</param>
/// <param name="instanceName">The private name for the LocalDB instance to share.</param>
/// <param name="sharedInstanceName">The shared name for the LocalDB instance to share as.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="ownerSid"/>, <paramref name="instanceName"/> or <paramref name="sharedInstanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not be shared.
/// </exception>
public void ShareInstance(
string ownerSid,
string instanceName,
string sharedInstanceName)
{
if (ownerSid == null)
{
throw new ArgumentNullException(nameof(ownerSid));
}
if (instanceName == null)
{
throw new ArgumentNullException(nameof(instanceName));
}
if (sharedInstanceName == null)
{
throw new ArgumentNullException(nameof(sharedInstanceName));
}
EnsurePlatformSupported();
if (instanceName.Length == 0)
{
// There is a bug in the SQL LocalDB native API that
// lets you share out an instance with no name, which
// then causes "interesting" results when using the other
// API functions on it. Block this explicitly to stop
// callers messing up their LocalDB instance.
throw new ArgumentException(SR.SqlLocalDbApi_NoInstanceName, nameof(instanceName));
}
Logger.SharingInstance(instanceName, ownerSid, sharedInstanceName);
// Get the binary version of the SID from its string
#pragma warning disable CA1416
byte[] binaryForm = GetOwnerSidAsByteArray(ownerSid);
#pragma warning restore CA1416
IntPtr ptrSid = Marshal.AllocHGlobal(binaryForm.Length);
try
{
// Copy the SID binary form to unmanaged memory
Marshal.Copy(binaryForm, 0, ptrSid, binaryForm.Length);
InvokeThrowOnError(
() => _api.ShareInstance(ptrSid, instanceName, sharedInstanceName, ReservedValue),
EventIds.SharingInstanceFailed,
instanceName);
Logger.SharedInstance(instanceName, ownerSid, sharedInstanceName);
}
finally
{
Marshal.FreeHGlobal(ptrSid);
}
}
/// <summary>
/// Starts the specified instance of SQL Server LocalDB.
/// </summary>
/// <param name="instanceName">The name of the LocalDB instance to start.</param>
/// <returns>
/// The named pipe to use to connect to the LocalDB instance.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not be started.
/// </exception>
public string StartInstance(string instanceName)
{
if (instanceName == null)
{
throw new ArgumentNullException(nameof(instanceName));
}
Logger.StartingInstance(instanceName);
int size = LocalDbInstanceApi.MaximumSqlConnectionStringBufferLength + 1;
var buffer = new StringBuilder(size);
InvokeThrowOnError(
() => _api.StartInstance(instanceName, ReservedValue, buffer, ref size),
EventIds.StartingInstanceFailed,
instanceName);
string namedPipe = buffer.ToString();
Logger.StartedInstance(instanceName, namedPipe);
return namedPipe;
}
/// <summary>
/// Enables tracing of native API calls for all the SQL Server
/// LocalDB instances owned by the current Windows user.
/// </summary>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// Tracing could not be initialized.
/// </exception>
public void StartTracing()
{
Logger.StartingTracing();
InvokeThrowOnError(_api.StartTracing, EventIds.StartingTracingFailed);
Logger.StartedTracing();
}
/// <summary>
/// Stops the specified instance of SQL Server LocalDB using
/// the timeout specified by <see cref="StopTimeout"/>.
/// </summary>
/// <param name="instanceName">
/// The name of the LocalDB instance to stop.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not be stopped.
/// </exception>
public void StopInstance(string instanceName)
{
StopInstance(instanceName, _stopTimeout);
}
/// <summary>
/// Stops the specified instance of SQL Server LocalDB.
/// </summary>
/// <param name="instanceName">
/// The name of the LocalDB instance to stop.
/// </param>
/// <param name="timeout">
/// The optional amount of time to give the LocalDB instance to stop.
/// If no value is specified, the value of <see cref="StopTimeout"/> will
/// be used. If the value is <see cref="TimeSpan.Zero"/>, the method will
/// return immediately and not wait for the instance to stop.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="timeout"/> is less than <see cref="TimeSpan.Zero"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not be stopped.
/// </exception>
/// <remarks>
/// The <paramref name="timeout"/> parameter is rounded to the nearest second.
/// </remarks>
public void StopInstance(string instanceName, TimeSpan? timeout)
{
StopInstance(instanceName, StopOptions, timeout);
}
/// <summary>
/// Stops the specified instance of SQL Server LocalDB.
/// </summary>
/// <param name="instanceName">
/// The name of the LocalDB instance to stop.
/// </param>
/// <param name="options">
/// The options specifying the way to stop the instance.
/// </param>
/// <param name="timeout">
/// The amount of time to give the LocalDB instance to stop.
/// If no value is specified, the value of <see cref="StopTimeout"/> will
/// be used. If the value is <see cref="TimeSpan.Zero"/>, the method will
/// return immediately and not wait for the instance to stop.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="instanceName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="timeout"/> is less than <see cref="TimeSpan.Zero"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// SQL Server LocalDB is not installed on the local machine.
/// </exception>
/// <exception cref="PlatformNotSupportedException">
/// The method is called from a non-Windows operating system.
/// </exception>
/// <exception cref="SqlLocalDbException">
/// The SQL Server LocalDB instance specified by <paramref name="instanceName"/> could not be stopped.
/// </exception>
/// <remarks>
/// The <paramref name="timeout"/> parameter is rounded to the nearest second.
/// </remarks>
public void StopInstance(string instanceName, StopInstanceOptions options, TimeSpan? timeout)
{
if (instanceName == null)
{
throw new ArgumentNullException(nameof(instanceName));
}
TimeSpan theTimeout = timeout ?? StopTimeout;
if (theTimeout < TimeSpan.Zero)
{
string message = SRHelper.Format(SR.SqlLocalDbApi_TimeoutTooSmallFormat, nameof(timeout));
throw new ArgumentOutOfRangeException(nameof(timeout), timeout, message);
}
Logger.StoppingInstance(instanceName, theTimeout, options);
Stopwatch stopwatch = Stopwatch.StartNew();
InvokeThrowOnError(
() => _api.StopInstance(instanceName, options, (int)theTimeout.TotalSeconds),
EventIds.StoppingInstanceFailed,
instanceName);