diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000000..1483f4e861
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,158 @@
+# editorconfig.org
+
+# top-most EditorConfig file
+root = true
+
+# Default settings:
+# A newline ending every file
+# Use 4 spaces as indentation
+[*]
+insert_final_newline = true
+indent_style = space
+indent_size = 4
+
+[project.json]
+indent_size = 2
+
+# C# files
+[*.cs]
+# New line preferences
+csharp_new_line_before_open_brace = all
+csharp_new_line_before_else = true
+csharp_new_line_before_catch = true
+csharp_new_line_before_finally = true
+csharp_new_line_before_members_in_object_initializers = true
+csharp_new_line_before_members_in_anonymous_types = true
+csharp_new_line_between_query_expression_clauses = true
+
+# Indentation preferences
+csharp_indent_block_contents = true
+csharp_indent_braces = false
+csharp_indent_case_contents = true
+csharp_indent_switch_labels = true
+csharp_indent_labels = one_less_than_current
+
+# avoid this. unless absolutely necessary
+dotnet_style_qualification_for_field = false:suggestion
+dotnet_style_qualification_for_property = false:suggestion
+dotnet_style_qualification_for_method = false:suggestion
+dotnet_style_qualification_for_event = false:suggestion
+
+# only use var when it's obvious what the variable type is
+csharp_style_var_for_built_in_types = false:none
+csharp_style_var_when_type_is_apparent = false:none
+csharp_style_var_elsewhere = false:suggestion
+
+# use language keywords instead of BCL types
+dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
+dotnet_style_predefined_type_for_member_access = true:suggestion
+
+# name all constant fields using PascalCase
+dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
+dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
+
+dotnet_naming_symbols.constant_fields.applicable_kinds = field
+dotnet_naming_symbols.constant_fields.required_modifiers = const
+
+dotnet_naming_style.pascal_case_style.capitalization = pascal_case
+
+# static fields should have s_ prefix
+dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion
+dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields
+dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style
+
+dotnet_naming_symbols.static_fields.applicable_kinds = field
+dotnet_naming_symbols.static_fields.required_modifiers = static
+
+dotnet_naming_style.static_prefix_style.required_prefix = s_
+dotnet_naming_style.static_prefix_style.capitalization = camel_case
+
+# internal and private fields should be _camelCase
+dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion
+dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields
+dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style
+
+dotnet_naming_symbols.private_internal_fields.applicable_kinds = field
+dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal
+
+dotnet_naming_style.camel_case_underscore_style.required_prefix = _
+dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case
+
+# Code style defaults
+dotnet_sort_system_directives_first = true
+csharp_preserve_single_line_blocks = true
+csharp_preserve_single_line_statements = false
+
+# Expression-level preferences
+dotnet_style_object_initializer = true:suggestion
+dotnet_style_collection_initializer = true:suggestion
+dotnet_style_explicit_tuple_names = true:suggestion
+dotnet_style_coalesce_expression = true:suggestion
+dotnet_style_null_propagation = true:suggestion
+
+# Expression-bodied members
+csharp_style_expression_bodied_methods = false:none
+csharp_style_expression_bodied_constructors = false:none
+csharp_style_expression_bodied_operators = false:none
+csharp_style_expression_bodied_properties = true:none
+csharp_style_expression_bodied_indexers = true:none
+csharp_style_expression_bodied_accessors = true:none
+
+# Pattern matching
+csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
+csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
+csharp_style_inlined_variable_declaration = true:suggestion
+
+# Null checking preferences
+csharp_style_throw_expression = true:suggestion
+csharp_style_conditional_delegate_call = true:suggestion
+
+# Space preferences
+csharp_space_after_cast = false
+csharp_space_after_colon_in_inheritance_clause = true
+csharp_space_after_comma = true
+csharp_space_after_dot = false
+csharp_space_after_keywords_in_control_flow_statements = true
+csharp_space_after_semicolon_in_for_statement = true
+csharp_space_around_binary_operators = before_and_after
+csharp_space_around_declaration_statements = do_not_ignore
+csharp_space_before_colon_in_inheritance_clause = true
+csharp_space_before_comma = false
+csharp_space_before_dot = false
+csharp_space_before_open_square_brackets = false
+csharp_space_before_semicolon_in_for_statement = false
+csharp_space_between_empty_square_brackets = false
+csharp_space_between_method_call_empty_parameter_list_parentheses = false
+csharp_space_between_method_call_name_and_opening_parenthesis = false
+csharp_space_between_method_call_parameter_list_parentheses = false
+csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
+csharp_space_between_method_declaration_name_and_open_parenthesis = false
+csharp_space_between_method_declaration_parameter_list_parentheses = false
+csharp_space_between_parentheses = false
+csharp_space_between_square_brackets = false
+
+# Xml project files
+[*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}]
+indent_size = 2
+
+# Xml build files
+[*.builds]
+indent_size = 2
+
+# Xml files
+[*.{xml,stylecop,resx,ruleset}]
+indent_size = 2
+
+# Xml config files
+[*.{props,targets,config,nuspec}]
+indent_size = 2
+
+# Shell scripts
+[*.sh]
+end_of_line = lf
+[*.{cmd, bat}]
+end_of_line = crlf
+
+# Analyzers
+dotnet_code_quality.ca1802.api_surface = private, internal
diff --git a/.gitignore b/.gitignore
index 62e4e8f2e1..4794a6e136 100644
--- a/.gitignore
+++ b/.gitignore
@@ -29,6 +29,7 @@ bld/
[Bb]in/
[Oo]bj/
[Ll]og/
+.nuget/
# Visual Studio 2015/2017 cache/options directory
.vs/
diff --git a/src/Directory.Build.props b/src/Directory.Build.props
index b8878c0503..da8678358f 100644
--- a/src/Directory.Build.props
+++ b/src/Directory.Build.props
@@ -11,7 +11,9 @@
true
true
-
+
+ $(DefineConstants);DEBUG
+
$(MSBuildThisFileDirectory)
$(ProjectDir)..\
diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.Manual.cs b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.Manual.cs
index 79bf00c58a..0519992f61 100644
--- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.Manual.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.Manual.cs
@@ -19,4 +19,4 @@ public sealed partial class SqlParameter
{
internal class SqlParameterConverter { }
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.NetCoreApp.cs
index d2329e7e10..eef032209c 100644
--- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.NetCoreApp.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.NetCoreApp.cs
@@ -143,4 +143,4 @@ public override void Flush() { }
public override void SetLength(long value) { throw null; }
public override void Write(byte[] buffer, int offset, int count) { throw null; }
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs
index 6c216643a1..dbf0cfe197 100644
--- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs
@@ -1081,4 +1081,4 @@ public SensitivityProperty(Microsoft.Data.SqlClient.DataClassification.Label lab
public Microsoft.Data.SqlClient.DataClassification.InformationType InformationType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public Microsoft.Data.SqlClient.DataClassification.Label Label { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs
index ea6a7d6fb5..f5f7ab1b07 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/NegotiationInfoClass.cs
@@ -16,12 +16,14 @@ internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState)
{
if (safeHandle.IsInvalid)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Invalid handle:{safeHandle}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, $"Invalid handle:{safeHandle}");
return;
}
IntPtr packageInfo = safeHandle.DangerousGetHandle();
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:x}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:x}");
if (negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_COMPLETE
|| negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_OPTIMISTIC)
@@ -30,14 +32,15 @@ internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState)
unsafe
{
- IntPtr unmanagedString = ((SecurityPackageInfo *)packageInfo)->Name;
+ IntPtr unmanagedString = ((SecurityPackageInfo*)packageInfo)->Name;
if (unmanagedString != IntPtr.Zero)
{
name = Marshal.PtrToStringUni(unmanagedString);
}
}
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:x} name:{name}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:x} name:{name}");
// An optimization for future string comparisons.
if (string.Equals(name, Kerberos, StringComparison.OrdinalIgnoreCase))
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs
index 20b7f6746a..8855379df7 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs
@@ -27,7 +27,8 @@ public SecurityPackageInfoClass[] SecurityPackages
public int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(this);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this);
return SafeFreeContextBuffer.EnumeratePackages(out pkgnum, out pkgArray);
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs
index dc3cc16b1c..c46f602221 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs
@@ -26,7 +26,8 @@ public SecurityPackageInfoClass[] SecurityPackages
public int EnumerateSecurityPackages(out int pkgnum, out SafeFreeContextBuffer pkgArray)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(this);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this);
return SafeFreeContextBuffer.EnumeratePackages(out pkgnum, out pkgArray);
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs
index c841556692..3e31c0c845 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs
@@ -13,7 +13,8 @@ internal static class SSPIWrapper
{
internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterface secModule)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Enter(null);
if (secModule.SecurityPackages == null)
{
@@ -26,7 +27,8 @@ internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterfa
try
{
int errorCode = secModule.EnumerateSecurityPackages(out moduleCount, out arrayBaseHandle);
- if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"arrayBase: {arrayBaseHandle}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(null, $"arrayBase: {arrayBaseHandle}");
if (errorCode != 0)
{
throw new Win32Exception(errorCode);
@@ -38,7 +40,8 @@ internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterfa
for (i = 0; i < moduleCount; i++)
{
securityPackages[i] = new SecurityPackageInfoClass(arrayBaseHandle, i);
- if (NetEventSource.IsEnabled) NetEventSource.Log.EnumerateSecurityPackages(securityPackages[i].Name);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.EnumerateSecurityPackages(securityPackages[i].Name);
}
secModule.SecurityPackages = securityPackages;
@@ -54,7 +57,8 @@ internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterfa
}
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null);
return secModule.SecurityPackages;
}
@@ -72,7 +76,8 @@ internal static SecurityPackageInfoClass GetVerifyPackageInfo(SSPIInterface secM
}
}
- if (NetEventSource.IsEnabled) NetEventSource.Log.SspiPackageNotFound(packageName);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.SspiPackageNotFound(packageName);
if (throwIfMissing)
{
@@ -95,7 +100,8 @@ public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface secModu
if (errorCode != 0)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireDefaultCredential), $"0x{errorCode:X}"));
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireDefaultCredential), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
return outCredential;
@@ -103,14 +109,16 @@ public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface secModu
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata)
{
- if (NetEventSource.IsEnabled) NetEventSource.Log.AcquireCredentialsHandle(package, intent, authdata);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.AcquireCredentialsHandle(package, intent, authdata);
SafeFreeCredentials credentialsHandle = null;
int errorCode = secModule.AcquireCredentialsHandle(package, intent, ref authdata, out credentialsHandle);
if (errorCode != 0)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
@@ -134,43 +142,51 @@ public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModu
if (errorCode != 0)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, outCredential);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, outCredential);
return outCredential;
}
internal static int InitializeSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
- if (NetEventSource.IsEnabled) NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags);
int errorCode = secModule.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, datarep, inputBuffer, outputBuffer, ref outFlags);
- if (NetEventSource.IsEnabled) NetEventSource.Log.SecurityContextInputBuffer(nameof(InitializeSecurityContext), inputBuffer?.size ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.SecurityContextInputBuffer(nameof(InitializeSecurityContext), inputBuffer?.size ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
internal static int InitializeSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
- if (NetEventSource.IsEnabled) NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags);
int errorCode = secModule.InitializeSecurityContext(credential, ref context, targetName, inFlags, datarep, inputBuffers, outputBuffer, ref outFlags);
- if (NetEventSource.IsEnabled) NetEventSource.Log.SecurityContextInputBuffers(nameof(InitializeSecurityContext), inputBuffers?.Length ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.SecurityContextInputBuffers(nameof(InitializeSecurityContext), inputBuffers?.Length ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
internal static int AcceptSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
- if (NetEventSource.IsEnabled) NetEventSource.Log.AcceptSecurityContext(credential, context, inFlags);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.AcceptSecurityContext(credential, context, inFlags);
int errorCode = secModule.AcceptSecurityContext(credential, ref context, inputBuffers, inFlags, datarep, outputBuffer, ref outFlags);
- if (NetEventSource.IsEnabled) NetEventSource.Log.SecurityContextInputBuffers(nameof(AcceptSecurityContext), inputBuffers?.Length ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.SecurityContextInputBuffers(nameof(AcceptSecurityContext), inputBuffers?.Length ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
@@ -179,7 +195,8 @@ internal static int CompleteAuthToken(SSPIInterface secModule, ref SafeDeleteCon
{
int errorCode = secModule.CompleteAuthToken(ref context, inputBuffers);
- if (NetEventSource.IsEnabled) NetEventSource.Log.OperationReturnedSomething(nameof(CompleteAuthToken), (Interop.SECURITY_STATUS)errorCode);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.OperationReturnedSomething(nameof(CompleteAuthToken), (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
@@ -188,7 +205,8 @@ internal static int ApplyControlToken(SSPIInterface secModule, ref SafeDeleteCon
{
int errorCode = secModule.ApplyControlToken(ref context, inputBuffers);
- if (NetEventSource.IsEnabled) NetEventSource.Log.OperationReturnedSomething(nameof(ApplyControlToken), (Interop.SECURITY_STATUS)errorCode);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Log.OperationReturnedSomething(nameof(ApplyControlToken), (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
@@ -366,17 +384,20 @@ private static unsafe int EncryptDecryptHelper(OP op, SSPIInterface secModule, S
public static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, contextAttribute);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Enter(null, contextAttribute);
SafeFreeContextBufferChannelBinding result;
int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result);
if (errorCode != 0)
{
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, result);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, result);
return result;
}
@@ -388,7 +409,8 @@ public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteC
public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, out int errorCode)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, contextAttribute);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Enter(null, contextAttribute);
int nativeBlockSize = IntPtr.Size;
Type handleType = null;
@@ -456,7 +478,8 @@ public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteC
errorCode = secModule.QueryContextAttributes(securityContext, contextAttribute, nativeBuffer, handleType, out sspiHandle);
if (errorCode != 0)
{
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
@@ -511,7 +534,7 @@ public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteC
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL:
unsafe
{
- fixed (void *ptr = nativeBuffer)
+ fixed (void* ptr = nativeBuffer)
{
attribute = Marshal.PtrToStructure(new IntPtr(ptr));
}
@@ -531,7 +554,8 @@ public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteC
}
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, attribute);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, attribute);
return attribute;
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs
index cf10092e68..74fca62e89 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SecurityPackageInfoClass.cs
@@ -27,12 +27,14 @@ internal unsafe SecurityPackageInfoClass(SafeHandle safeHandle, int index)
{
if (safeHandle.IsInvalid)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Invalid handle: {safeHandle}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, $"Invalid handle: {safeHandle}");
return;
}
IntPtr unmanagedAddress = safeHandle.DangerousGetHandle() + (sizeof(SecurityPackageInfo) * index);
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"unmanagedAddress: {unmanagedAddress}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, $"unmanagedAddress: {unmanagedAddress}");
SecurityPackageInfo* pSecurityPackageInfo = (SecurityPackageInfo*)unmanagedAddress;
@@ -47,17 +49,20 @@ internal unsafe SecurityPackageInfoClass(SafeHandle safeHandle, int index)
if (unmanagedString != IntPtr.Zero)
{
Name = Marshal.PtrToStringUni(unmanagedString);
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Name: {Name}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, $"Name: {Name}");
}
unmanagedString = pSecurityPackageInfo->Comment;
if (unmanagedString != IntPtr.Zero)
{
Comment = Marshal.PtrToStringUni(unmanagedString);
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Comment: {Comment}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, $"Comment: {Comment}");
}
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, this.ToString());
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, this.ToString());
}
public override string ToString()
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs
index 9c1411434c..eddb15826b 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SecuritySafeHandles.cs
@@ -209,7 +209,8 @@ public static unsafe int AcquireDefaultCredential(
Interop.SspiCli.CredentialUse intent,
out SafeFreeCredentials outCredential)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Enter(null, package, intent);
int errorCode = -1;
long timeStamp;
@@ -274,7 +275,8 @@ public static unsafe int AcquireCredentialsHandle(
ref Interop.SspiCli.SCHANNEL_CRED authdata,
out SafeFreeCredentials outCredential)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Enter(null, package, intent, authdata);
int errorCode = -1;
long timeStamp;
@@ -513,7 +515,7 @@ internal static unsafe int InitializeSecurityContext(
}
Interop.SspiCli.SecBuffer outUnmanagedBuffer = default;
-
+
// Fix Descriptor pointer that points to unmanaged SecurityBuffers.
outSecurityBufferDescriptor.pBuffers = &outUnmanagedBuffer;
outUnmanagedBuffer.cbBuffer = outSecBuffer.size;
@@ -558,7 +560,8 @@ internal static unsafe int InitializeSecurityContext(
outFreeContextBuffer);
}
- if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshalling OUT buffer");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(null, "Marshalling OUT buffer");
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer.cbBuffer;
@@ -597,7 +600,8 @@ internal static unsafe int InitializeSecurityContext(
}
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
return errorCode;
}
@@ -841,7 +845,8 @@ internal static unsafe int AcceptSecurityContext(
ref outFlags,
outFreeContextBuffer);
- if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshaling OUT buffer");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(null, "Marshaling OUT buffer");
// Get unmanaged buffer with index 0 as the only one passed into PInvoke.
outSecBuffer.size = outUnmanagedBuffer[0].cbBuffer;
@@ -882,7 +887,8 @@ internal static unsafe int AcceptSecurityContext(
}
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}");
return errorCode;
}
@@ -1065,7 +1071,8 @@ internal static unsafe int CompleteAuthToken(
}
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}");
return errorCode;
}
@@ -1168,7 +1175,8 @@ internal static unsafe int ApplyControlToken(
}
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}");
return errorCode;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/BasicFieldNameLookup.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/BasicFieldNameLookup.cs
index 6e427f771e..6d5b5b8891 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/BasicFieldNameLookup.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/BasicFieldNameLookup.cs
@@ -2,11 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-using Microsoft.Data.Common;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
+using Microsoft.Data.Common;
namespace Microsoft.Data.ProviderBase
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/DbConnectionOptions.Common.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/DbConnectionOptions.Common.cs
index e65b6380e3..2cab0ba6ed 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/DbConnectionOptions.Common.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/DbConnectionOptions.Common.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Data.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -58,7 +57,7 @@ partial class DbConnectionOptions
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ ")" // although the spec does not allow {}
- // embedded within a value, the retail code does.
+ // embedded within a value, the retail code does.
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
@@ -357,7 +356,7 @@ internal static int GetKeyValuePair(string connectionString, int currentPosition
}
buffer.Append(currentChar);
}
- ParserExit:
+ ParserExit:
switch (parserState)
{
case ParserState.Key:
@@ -483,7 +482,7 @@ private static Dictionary SplitConnectionString(string connectio
string synonym;
string realkeyname = null != synonyms ?
(synonyms.TryGetValue(keyname, out synonym) ? synonym : null) : keyname;
-
+
if (!IsKeyNameValid(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
@@ -558,47 +557,47 @@ private static NameValuePair ParseInternal(Dictionary parsetable
try
{
#endif
- int nextStartPosition = 0;
- int endPosition = connectionString.Length;
- while (nextStartPosition < endPosition)
- {
- int startPosition = nextStartPosition;
-
- string keyname, keyvalue;
- nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
- if (string.IsNullOrEmpty(keyname))
+ int nextStartPosition = 0;
+ int endPosition = connectionString.Length;
+ while (nextStartPosition < endPosition)
{
- // if (nextStartPosition != endPosition) { throw; }
- break;
- }
+ int startPosition = nextStartPosition;
+
+ string keyname, keyvalue;
+ nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
+ if (string.IsNullOrEmpty(keyname))
+ {
+ // if (nextStartPosition != endPosition) { throw; }
+ break;
+ }
#if DEBUG
DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
#endif
- string synonym;
- string realkeyname = null != synonyms ?
- (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) :
- keyname;
- if (!IsKeyNameValid(realkeyname))
- {
- throw ADP.KeywordNotSupported(keyname);
- }
- if (!firstKey || !parsetable.ContainsKey(realkeyname))
- {
- parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
- }
+ string synonym;
+ string realkeyname = null != synonyms ?
+ (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) :
+ keyname;
+ if (!IsKeyNameValid(realkeyname))
+ {
+ throw ADP.KeywordNotSupported(keyname);
+ }
+ if (!firstKey || !parsetable.ContainsKey(realkeyname))
+ {
+ parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
+ }
- if (null != localKeychain)
- {
- localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
- }
- else if (buildChain)
- { // first time only - don't contain modified chain from UDL file
- keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
+ if (null != localKeychain)
+ {
+ localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
+ }
+ else if (buildChain)
+ { // first time only - don't contain modified chain from UDL file
+ keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
+ }
}
- }
#if DEBUG
}
catch (ArgumentException e)
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/NameValuePair.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/NameValuePair.cs
index 2cdd8cb6ce..abdbdfd28d 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/NameValuePair.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/NameValuePair.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Data.Common;
using System.Diagnostics;
namespace Microsoft.Data.Common
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
index e96a6505d8..1ac82b68cc 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
@@ -31,7 +31,7 @@ internal abstract partial class DbConnectionInternal
private bool _connectionIsDoomed; // true when the connection should no longer be used.
private bool _cannotBePooled; // true when the connection should no longer be pooled.
-
+
private DateTime _createTime; // when the connection was created.
#if DEBUG
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs
index 8ba682fa10..1949341de2 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugCriticalHandleMinusOneIsInvalid.cs
@@ -23,7 +23,8 @@ protected DebugCriticalHandleMinusOneIsInvalid() : base()
private void Trace()
{
_trace = "WARNING! GC-ed >>" + this.GetType().FullName + "<< (should be explicitly closed) \r\n";
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Creating SafeHandle");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, "Creating SafeHandle");
#if TRACE_VERBOSE
string stacktrace = Environment.StackTrace;
_trace += stacktrace;
@@ -33,7 +34,8 @@ private void Trace()
~DebugCriticalHandleMinusOneIsInvalid()
{
DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, _trace);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, _trace);
}
}
#endif // DEBUG
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs
index ff4ea687d2..c28a7107b1 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugCriticalHandleZeroOrMinusOneIsInvalid.cs
@@ -23,7 +23,8 @@ protected DebugCriticalHandleZeroOrMinusOneIsInvalid() : base()
private void Trace()
{
_trace = "WARNING! GC-ed >>" + this.GetType().FullName + "<< (should be explicitly closed) \r\n";
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Creating SafeHandle");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, "Creating SafeHandle");
#if TRACE_VERBOSE
string stacktrace = Environment.StackTrace;
_trace += stacktrace;
@@ -33,7 +34,8 @@ private void Trace()
~DebugCriticalHandleZeroOrMinusOneIsInvalid()
{
DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, _trace);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, _trace);
}
}
#endif // DEBUG
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugSafeHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugSafeHandle.cs
index e2e7c4629a..b0646f92e9 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugSafeHandle.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/DebugSafeHandle.cs
@@ -43,7 +43,8 @@ private void Trace()
~DebugSafeHandle()
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, _trace);
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, _trace);
}
}
#endif // DEBUG
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Logging/DebugThreadTracking.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Logging/DebugThreadTracking.cs
index d10cf44d08..78d8d48ac6 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Logging/DebugThreadTracking.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Logging/DebugThreadTracking.cs
@@ -34,16 +34,19 @@ internal static IDisposable SetThreadKind(ThreadKinds kind)
// Special warnings when doing dangerous things on a thread.
if ((threadKind & ThreadKinds.User) != 0 && (kind & ThreadKinds.System) != 0)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, "Thread changed from User to System; user's thread shouldn't be hijacked.");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, "Thread changed from User to System; user's thread shouldn't be hijacked.");
}
if ((threadKind & ThreadKinds.Async) != 0 && (kind & ThreadKinds.Sync) != 0)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, "Thread changed from Async to Sync, may block an Async thread.");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, "Thread changed from Async to Sync, may block an Async thread.");
}
else if ((threadKind & (ThreadKinds.Other | ThreadKinds.CompletionPort)) == 0 && (kind & ThreadKinds.Sync) != 0)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, "Thread from a limited resource changed to Sync, may deadlock or bottleneck.");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, "Thread from a limited resource changed to Sync, may deadlock or bottleneck.");
}
ThreadKindStack.Push(
@@ -54,7 +57,8 @@ internal static IDisposable SetThreadKind(ThreadKinds kind)
if (CurrentThreadKind != threadKind)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Thread becomes:({CurrentThreadKind})");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(null, $"Thread becomes:({CurrentThreadKind})");
}
return new ThreadKindFrame();
@@ -86,7 +90,8 @@ void IDisposable.Dispose()
if (CurrentThreadKind != previous && NetEventSource.IsEnabled)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Thread reverts:({CurrentThreadKind})");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Info(this, $"Thread reverts:({CurrentThreadKind})");
}
}
}
@@ -106,7 +111,8 @@ internal static void SetThreadSource(ThreadKinds source)
if (ThreadKindStack.Count > 1)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, "SetThreadSource must be called at the base of the stack, or the stack has been corrupted.");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, "SetThreadSource must be called at the base of the stack, or the stack has been corrupted.");
while (ThreadKindStack.Count > 1)
{
ThreadKindStack.Pop();
@@ -115,7 +121,8 @@ internal static void SetThreadSource(ThreadKinds source)
if (ThreadKindStack.Peek() != source)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, "The stack has been corrupted.");
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, "The stack has been corrupted.");
ThreadKinds last = ThreadKindStack.Pop() & ThreadKinds.SourceMask;
if (last != source && last != ThreadKinds.Other && NetEventSource.IsEnabled)
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Logging/NetEventSource.Common.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Logging/NetEventSource.Common.cs
index 6d3b94e120..4430445f30 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Logging/NetEventSource.Common.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Logging/NetEventSource.Common.cs
@@ -45,7 +45,7 @@ namespace System.Net
// method that takes an object and optionally provides a string representation of it, in case a particular library wants to customize further.
/// Provides logging facilities for System.Net libraries.
-#if NET46
+#if NET46
[SecuritySafeCritical]
#endif
internal sealed partial class NetEventSource : EventSource
@@ -101,7 +101,8 @@ public static void Enter(object thisOrContextObject, FormattableString formattab
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ if (IsEnabled)
+ Log.Enter(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// Logs entrance to a method.
@@ -113,7 +114,8 @@ public static void Enter(object thisOrContextObject, object arg0, [CallerMemberN
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
- if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
+ if (IsEnabled)
+ Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)})");
}
/// Logs entrance to a method.
@@ -127,7 +129,8 @@ public static void Enter(object thisOrContextObject, object arg0, object arg1, [
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
DebugValidateArg(arg1);
- if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
+ if (IsEnabled)
+ Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)})");
}
/// Logs entrance to a method.
@@ -143,7 +146,8 @@ public static void Enter(object thisOrContextObject, object arg0, object arg1, o
DebugValidateArg(arg0);
DebugValidateArg(arg1);
DebugValidateArg(arg2);
- if (IsEnabled) Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
+ if (IsEnabled)
+ Log.Enter(IdOf(thisOrContextObject), memberName, $"({Format(arg0)}, {Format(arg1)}, {Format(arg2)})");
}
[Event(EnterEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
@@ -161,7 +165,8 @@ public static void Exit(object thisOrContextObject, FormattableString formattabl
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ if (IsEnabled)
+ Log.Exit(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// Logs exit from a method.
@@ -173,7 +178,8 @@ public static void Exit(object thisOrContextObject, object arg0, [CallerMemberNa
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
- if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
+ if (IsEnabled)
+ Log.Exit(IdOf(thisOrContextObject), memberName, Format(arg0).ToString());
}
/// Logs exit from a method.
@@ -187,7 +193,8 @@ public static void Exit(object thisOrContextObject, object arg0, object arg1, [C
DebugValidateArg(thisOrContextObject);
DebugValidateArg(arg0);
DebugValidateArg(arg1);
- if (IsEnabled) Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
+ if (IsEnabled)
+ Log.Exit(IdOf(thisOrContextObject), memberName, $"{Format(arg0)}, {Format(arg1)}");
}
[Event(ExitEventId, Level = EventLevel.Informational, Keywords = Keywords.EnterExit)]
@@ -205,7 +212,8 @@ public static void Info(object thisOrContextObject, FormattableString formattabl
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
+ if (IsEnabled)
+ Log.Info(IdOf(thisOrContextObject), memberName, formattableString != null ? Format(formattableString) : NoParameters);
}
/// Logs an information message.
@@ -217,7 +225,8 @@ public static void Info(object thisOrContextObject, object message, [CallerMembe
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
- if (IsEnabled) Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled)
+ Log.Info(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(InfoEventId, Level = EventLevel.Informational, Keywords = Keywords.Default)]
@@ -235,7 +244,8 @@ public static void Error(object thisOrContextObject, FormattableString formattab
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(formattableString);
- if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ if (IsEnabled)
+ Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(formattableString));
}
/// Logs an error message.
@@ -247,7 +257,8 @@ public static void Error(object thisOrContextObject, object message, [CallerMemb
{
DebugValidateArg(thisOrContextObject);
DebugValidateArg(message);
- if (IsEnabled) Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled)
+ Log.ErrorMessage(IdOf(thisOrContextObject), memberName, Format(message).ToString());
}
[Event(ErrorEventId, Level = EventLevel.Warning, Keywords = Keywords.Default)]
@@ -266,7 +277,8 @@ public static void Fail(object thisOrContextObject, FormattableString formattabl
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
// that should never happen in production, and thus we don't care about extra costs.
- if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
+ if (IsEnabled)
+ Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(formattableString));
Debug.Fail(Format(formattableString), $"{IdOf(thisOrContextObject)}.{memberName}");
}
@@ -280,7 +292,8 @@ public static void Fail(object thisOrContextObject, object message, [CallerMembe
// Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
// that should never happen in production, and thus we don't care about extra costs.
- if (IsEnabled) Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
+ if (IsEnabled)
+ Log.CriticalFailure(IdOf(thisOrContextObject), memberName, Format(message).ToString());
Debug.Fail(Format(message).ToString(), $"{IdOf(thisOrContextObject)}.{memberName}");
}
@@ -299,7 +312,7 @@ public static void DumpBuffer(object thisOrContextObject, byte[] buffer, [Caller
{
DumpBuffer(thisOrContextObject, buffer, 0, buffer.Length, memberName);
}
-
+
/// Logs the contents of a buffer.
/// `this`, or another object that serves to provide context for the operation.
/// The buffer to be logged.
@@ -367,7 +380,8 @@ public static void Associate(object first, object second, [CallerMemberName] str
{
DebugValidateArg(first);
DebugValidateArg(second);
- if (IsEnabled) Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
+ if (IsEnabled)
+ Log.Associate(IdOf(first), memberName, IdOf(first), IdOf(second));
}
/// Logs a relationship between two objects.
@@ -381,7 +395,8 @@ public static void Associate(object thisOrContextObject, object first, object se
DebugValidateArg(thisOrContextObject);
DebugValidateArg(first);
DebugValidateArg(second);
- if (IsEnabled) Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
+ if (IsEnabled)
+ Log.Associate(IdOf(thisOrContextObject), memberName, IdOf(first), IdOf(second));
}
[Event(AssociateEventId, Level = EventLevel.Informational, Keywords = Keywords.Default, Message = "[{2}]<-->[{3}]")]
@@ -409,7 +424,7 @@ private static void DebugValidateArg(FormattableString arg)
public static new bool IsEnabled =>
Log.IsEnabled();
- //true; // uncomment for debugging only
+ //true; // uncomment for debugging only
[NonEvent]
public static string IdOf(object value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
@@ -478,10 +493,14 @@ private static string Format(FormattableString s)
{
switch (s.ArgumentCount)
{
- case 0: return s.Format;
- case 1: return string.Format(s.Format, Format(s.GetArgument(0)));
- case 2: return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)));
- case 3: return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)), Format(s.GetArgument(2)));
+ case 0:
+ return s.Format;
+ case 1:
+ return string.Format(s.Format, Format(s.GetArgument(0)));
+ case 2:
+ return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)));
+ case 3:
+ return string.Format(s.Format, Format(s.GetArgument(0)), Format(s.GetArgument(1)), Format(s.GetArgument(2)));
default:
object[] args = s.GetArguments();
object[] formattedArgs = new object[args.Length];
@@ -503,10 +522,14 @@ private unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg
{
if (IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- if (arg3 == null) arg3 = "";
- if (arg4 == null) arg4 = "";
+ if (arg1 == null)
+ arg1 = "";
+ if (arg2 == null)
+ arg2 = "";
+ if (arg3 == null)
+ arg3 = "";
+ if (arg4 == null)
+ arg4 = "";
fixed (char* string1Bytes = arg1)
fixed (char* string2Bytes = arg2)
@@ -547,9 +570,12 @@ private unsafe void WriteEvent(int eventId, string arg1, string arg2, byte[] arg
{
if (IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- if (arg3 == null) arg3 = Array.Empty();
+ if (arg1 == null)
+ arg1 = "";
+ if (arg2 == null)
+ arg2 = "";
+ if (arg3 == null)
+ arg3 = Array.Empty();
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
@@ -590,7 +616,8 @@ private unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3, int
{
if (IsEnabled())
{
- if (arg1 == null) arg1 = "";
+ if (arg1 == null)
+ arg1 = "";
fixed (char* arg1Ptr = arg1)
{
@@ -628,8 +655,10 @@ private unsafe void WriteEvent(int eventId, string arg1, int arg2, string arg3)
{
if (IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg3 == null) arg3 = "";
+ if (arg1 == null)
+ arg1 = "";
+ if (arg3 == null)
+ arg3 = "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg3Ptr = arg3)
@@ -663,8 +692,10 @@ private unsafe void WriteEvent(int eventId, string arg1, string arg2, int arg3)
{
if (IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
+ if (arg1 == null)
+ arg1 = "";
+ if (arg2 == null)
+ arg2 = "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
@@ -698,9 +729,12 @@ private unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg
{
if (IsEnabled())
{
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- if (arg3 == null) arg3 = "";
+ if (arg1 == null)
+ arg1 = "";
+ if (arg2 == null)
+ arg2 = "";
+ if (arg3 == null)
+ arg3 = "";
fixed (char* arg1Ptr = arg1)
fixed (char* arg2Ptr = arg2)
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs
index 36b850af7b..961086a6fe 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs
@@ -39,7 +39,8 @@ internal static unsafe SafeFreeCredentials AcquireCredentialsHandle(string packa
if (result != Interop.SECURITY_STATUS.OK)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(Interop.SspiCli.SspiEncodeStringsAsAuthIdentity), $"0x{(int)result:X}"));
+ if (NetEventSource.IsEnabled)
+ NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(Interop.SspiCli.SspiEncodeStringsAsAuthIdentity), $"0x{(int)result:X}"));
throw new Win32Exception((int)result);
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/PasteArguments.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/PasteArguments.Windows.cs
index 7cdcbc4533..1e8cfdbaf7 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/PasteArguments.Windows.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/PasteArguments.Windows.cs
@@ -10,7 +10,7 @@ namespace System
{
internal static partial class PasteArguments
{
- ///
+ ///
/// Repastes a set of arguments into a linear string that parses back into the originals under pre- or post-2008 VC parsing rules.
/// The rules for parsing the executable name (argv[0]) are special, so you must indicate whether the first argument actually is argv[0].
///
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Common.cs b/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Common.cs
index 6d63bc6633..ed33b6897a 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Common.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Common.cs
@@ -21,4 +21,4 @@ internal enum SniSpecialErrors : uint
MaxErrorValue = SNICommon.MaxErrorValue
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/ActivityCorrelator.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/ActivityCorrelator.cs
index 5abd103464..d4f1c1ac6f 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/ActivityCorrelator.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/ActivityCorrelator.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
using System;
using System.Globalization;
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs
index f8ec10f703..27cba16b44 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs
@@ -324,7 +324,7 @@ internal static Exception InvalidXmlInvalidValue(string collectionName, string c
{
return Argument(System.SRHelper.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName));
}
-
+
internal static Exception CollectionNameIsNotUnique(string collectionName)
{
return Argument(System.SRHelper.GetString(SR.MDF_CollectionNameISNotUnique, collectionName));
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionOptions.cs
index 02092e5f57..647a5aee94 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionOptions.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionOptions.cs
@@ -6,7 +6,6 @@
using System.Collections.Generic;
using System.Globalization;
-
namespace Microsoft.Data.Common
{
internal partial class DbConnectionOptions
@@ -21,7 +20,8 @@ public DbConnectionOptions(string connectionString, Dictionary s
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
- if (0 < _usersConnectionString.Length) {
+ if (0 < _usersConnectionString.Length)
+ {
_keyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, false);
HasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
HasUserIdKeyword = (_parsetable.ContainsKey(KEY.User_ID) || _parsetable.ContainsKey(SYNONYM.UID));
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.NetCoreApp.cs
index bb5c8f07ba..a0ad228a3c 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.NetCoreApp.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.NetCoreApp.cs
@@ -2,9 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Data.SqlClient;
using System;
using System.Diagnostics;
+using Microsoft.Data.SqlClient;
namespace Microsoft.Data.Common
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.cs
index a26639bb7a..34ed70bb42 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.cs
@@ -2,12 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System;
using System.Diagnostics;
+using System.Globalization;
using System.Reflection;
-using System;
using Microsoft.Data.SqlClient;
-using System.Globalization;
-using Microsoft.Data.Common;
namespace Microsoft.Data.Common
{
@@ -321,7 +320,7 @@ internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod valu
return value == SqlAuthenticationMethod.SqlPassword
|| value == SqlAuthenticationMethod.ActiveDirectoryPassword
|| value == SqlAuthenticationMethod.ActiveDirectoryIntegrated
- || value == SqlAuthenticationMethod.ActiveDirectoryInteractive
+ || value == SqlAuthenticationMethod.ActiveDirectoryInteractive
|| value == SqlAuthenticationMethod.NotSpecified;
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs
index 32f9b5280b..ad3840237b 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
using System;
namespace Microsoft.Data
@@ -12,8 +11,7 @@ namespace Microsoft.Data
// The dangerous point there are the string arguments of the exported (internal) methods.
// This string can be argument, table or constraint name but never text of exception itself.
// Make an invariant that all texts of exceptions coming from resources only.
-
-
+
internal static class ExceptionBuilder
{
// The class defines the exceptions that are specific to the DataSet.
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/OperationAbortedException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/OperationAbortedException.cs
index a804341524..9dd6cbaa72 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/OperationAbortedException.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/OperationAbortedException.cs
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+
using System;
using System.Runtime.Serialization;
@@ -16,7 +17,7 @@ private OperationAbortedException(string message, Exception innerException) : ba
}
private OperationAbortedException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
+ {
}
internal static OperationAbortedException Aborted(Exception inner)
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs
index 01e3c32497..89663d2f90 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs
@@ -2,9 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Data.Common;
-using System.Data.Common;
using System.Transactions;
+using Microsoft.Data.Common;
namespace Microsoft.Data.ProviderBase
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs
index ab5d1de089..65c608d700 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs
@@ -2,13 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Diagnostics;
+using System.Data;
using System.Data.Common;
+using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
-using Microsoft.Data.Common;
using System.Transactions;
-using System.Data;
+using Microsoft.Data.Common;
namespace Microsoft.Data.ProviderBase
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
index 710503cc4b..39a6f0c3dd 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
@@ -2,14 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-using Microsoft.Data.Common;
using System;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Transactions;
-
+using Microsoft.Data.Common;
namespace Microsoft.Data.ProviderBase
{
@@ -374,7 +372,7 @@ public virtual void Dispose()
enlistedTransaction.Dispose();
}
}
-
+
abstract public void EnlistTransaction(Transaction transaction);
// Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs
index 0406343c93..6a7231d0c8 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs
@@ -2,14 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
-using System.Collections.Concurrent;
using System.Transactions;
-using System;
using Microsoft.Data.Common;
namespace Microsoft.Data.ProviderBase
@@ -128,7 +128,7 @@ internal DbConnectionInternal GetTransactedObject(Transaction transaction)
}
}
}
-
+
return transactedObject;
}
@@ -622,7 +622,7 @@ private void CleanupCallback(object state)
// new stack to old stack.
if (_waitHandles.PoolSemaphore.WaitOne(0))
{
- for (; ;)
+ for (; ; )
{
DbConnectionInternal obj;
@@ -750,7 +750,8 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio
Timer t = new Timer(new TimerCallback(this.ErrorCallback), null, Timeout.Infinite, Timeout.Infinite);
bool timerIsNotDisposed;
- try { }
+ try
+ { }
finally
{
_waitHandles.ErrorEvent.Set();
@@ -969,7 +970,8 @@ private void WaitForPendingOpen()
try
{
- try { }
+ try
+ { }
finally
{
started = Interlocked.CompareExchange(ref _pendingOpensWaiting, 1, 0) == 0;
@@ -1383,7 +1385,8 @@ private void PoolCreateRequest(object state)
int waitResult = BOGUS_HANDLE;
try
{
- try { }
+ try
+ { }
finally
{
waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(withCreate: true), CreationTimeout);
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContext.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContext.cs
index 51946630cd..6fc660b8b1 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContext.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContext.cs
@@ -101,4 +101,4 @@ internal void ReleaseLockToUpdate() {
Debug.Assert(oldValue == STATUS_LOCKED);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContextKey.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContextKey.cs
index e6499a96bf..0f89649628 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContextKey.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContextKey.cs
@@ -99,4 +99,4 @@ private int ComputeHashCode() {
return hashCode;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs
index 1723ea86be..3eceb6d3e3 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
namespace Microsoft.Data.ProviderBase
{
internal class DbConnectionPoolGroupProviderInfo
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs
index 1b26771e3b..93d2b0f329 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs
@@ -3,8 +3,8 @@
// See the LICENSE file in the project root for more information.
using System;
-using Microsoft.Data.SqlClient;
using System.Security.Principal;
+using Microsoft.Data.SqlClient;
namespace Microsoft.Data.ProviderBase
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolProviderInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolProviderInfo.cs
index 9eb0379ab0..5392795dff 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolProviderInfo.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolProviderInfo.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
namespace Microsoft.Data.ProviderBase
{
internal class DbConnectionPoolProviderInfo
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Sql/SqlNotificationRequest.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Sql/SqlNotificationRequest.cs
index dcbedb6324..3337b576e5 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Sql/SqlNotificationRequest.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Sql/SqlNotificationRequest.cs
@@ -71,4 +71,4 @@ public string UserData
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs
index 9679168b92..8e7fca8dcf 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs
@@ -2,18 +2,19 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Security.Cryptography;
+using System;
using System.ComponentModel;
+using System.Security.Cryptography;
using System.Text;
-using System;
-
-namespace Microsoft.Data.SqlClient {
+namespace Microsoft.Data.SqlClient
+{
///
/// AD auth retry states.
///
- internal enum ActiveDirectoryAuthenticationTimeoutRetryState {
+ internal enum ActiveDirectoryAuthenticationTimeoutRetryState
+ {
NotStarted = 0,
Retrying,
HasLoggedIn,
@@ -22,7 +23,8 @@ internal enum ActiveDirectoryAuthenticationTimeoutRetryState {
///
/// AD auth retry helper.
///
- internal class ActiveDirectoryAuthenticationTimeoutRetryHelper {
+ internal class ActiveDirectoryAuthenticationTimeoutRetryHelper
+ {
private ActiveDirectoryAuthenticationTimeoutRetryState _state = ActiveDirectoryAuthenticationTimeoutRetryState.NotStarted;
private SqlFedAuthToken _token;
private readonly string _typeName;
@@ -30,25 +32,31 @@ internal class ActiveDirectoryAuthenticationTimeoutRetryHelper {
///
/// Constructor.
///
- public ActiveDirectoryAuthenticationTimeoutRetryHelper() {
+ public ActiveDirectoryAuthenticationTimeoutRetryHelper()
+ {
_typeName = GetType().Name;
}
///
/// Retry state.
///
- public ActiveDirectoryAuthenticationTimeoutRetryState State {
+ public ActiveDirectoryAuthenticationTimeoutRetryState State
+ {
get { return _state; }
- set {
- switch (_state) {
+ set
+ {
+ switch (_state)
+ {
case ActiveDirectoryAuthenticationTimeoutRetryState.NotStarted:
if (value != ActiveDirectoryAuthenticationTimeoutRetryState.Retrying
- && value != ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn) {
+ && value != ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn)
+ {
throw new InvalidOperationException($"Cannot transit from {_state} to {value}.");
}
break;
case ActiveDirectoryAuthenticationTimeoutRetryState.Retrying:
- if (value != ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn) {
+ if (value != ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn)
+ {
throw new InvalidOperationException($"Cannot transit from {_state} to {value}.");
}
break;
@@ -64,11 +72,14 @@ public ActiveDirectoryAuthenticationTimeoutRetryState State {
///
/// Cached token.
///
- public SqlFedAuthToken CachedToken {
- get {
+ public SqlFedAuthToken CachedToken
+ {
+ get
+ {
return _token;
}
- set {
+ set
+ {
_token = value;
}
}
@@ -76,29 +87,36 @@ public SqlFedAuthToken CachedToken {
///
/// Whether login can be retried after a client/server connection timeout due to a long-time token acquisition.
///
- public bool CanRetryWithSqlException(SqlException sqlex) {
+ public bool CanRetryWithSqlException(SqlException sqlex)
+ {
if (_state == ActiveDirectoryAuthenticationTimeoutRetryState.NotStarted
&& CachedToken != null
- && IsConnectTimeoutError(sqlex)){
+ && IsConnectTimeoutError(sqlex))
+ {
return true;
}
return false;
}
- private static bool IsConnectTimeoutError(SqlException sqlex) {
+ private static bool IsConnectTimeoutError(SqlException sqlex)
+ {
var innerException = sqlex.InnerException as Win32Exception;
- if (innerException == null) return false;
+ if (innerException == null)
+ return false;
return innerException.NativeErrorCode == 10054 // Server timeout
|| innerException.NativeErrorCode == 258; // Client timeout
}
- private static string GetTokenHash(SqlFedAuthToken token) {
- if (token == null) return "null";
+ private static string GetTokenHash(SqlFedAuthToken token)
+ {
+ if (token == null)
+ return "null";
// Here we mimic how ADAL calculates hash for token. They use UTF8 instead of Unicode.
var originalTokenString = SqlAuthenticationToken.AccessTokenStringFromBytes(token.accessToken);
var bytesInUtf8 = Encoding.UTF8.GetBytes(originalTokenString);
- using (var sha256 = SHA256.Create()) {
+ using (var sha256 = SHA256.Create())
+ {
var hash = sha256.ComputeHash(bytesInUtf8);
return Convert.ToBase64String(hash);
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ActiveDirectoryNativeAuthenticationProvider.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ActiveDirectoryNativeAuthenticationProvider.cs
index 877c415902..5652d93f04 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ActiveDirectoryNativeAuthenticationProvider.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ActiveDirectoryNativeAuthenticationProvider.cs
@@ -2,9 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Identity.Client;
using System.Security;
using System.Threading.Tasks;
+using Microsoft.Identity.Client;
namespace Microsoft.Data.SqlClient
{
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedHelperClasses.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedHelperClasses.cs
index cdeb388481..93eee05b61 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedHelperClasses.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedHelperClasses.cs
@@ -2,10 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Data.SqlClient.Server;
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using Microsoft.Data.SqlClient.Server;
namespace Microsoft.Data.SqlClient
{
@@ -239,7 +239,7 @@ internal _SqlMetaDataSet(int count, SqlTceCipherInfoTable? cipherTable)
_metaDataArray = new _SqlMetaData[count];
for (int i = 0; i < _metaDataArray.Length; ++i)
{
- _metaDataArray[i] = new _SqlMetaData(i);
+ _metaDataArray[i] = new _SqlMetaData(i);
}
}
}
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ApplicationIntent.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ApplicationIntent.cs
index 4a1142bfd9..9e6af8cd0b 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ApplicationIntent.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ApplicationIntent.cs
@@ -2,9 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-//------------------------------------------------------------------------------
-
namespace Microsoft.Data.SqlClient
{
///
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs
index c7a4394643..eaecec4f9d 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs
@@ -36,10 +36,14 @@ internal class ColumnEncryptionKeyInfo
internal ColumnEncryptionKeyInfo(byte[] decryptedKey, int databaseId, byte[] keyMetadataVersion, int keyid)
{
- if (null == decryptedKey) { throw SQL.NullArgumentInConstructorInternal(_decryptedKeyName, _className); }
- if (0 == decryptedKey.Length) { throw SQL.EmptyArgumentInConstructorInternal(_decryptedKeyName, _className); }
- if (null == keyMetadataVersion) { throw SQL.NullArgumentInConstructorInternal(_keyMetadataVersionName, _className); }
- if (0 == keyMetadataVersion.Length) { throw SQL.EmptyArgumentInConstructorInternal(_keyMetadataVersionName, _className); }
+ if (null == decryptedKey)
+ throw SQL.NullArgumentInConstructorInternal(_decryptedKeyName, _className);
+ if (0 == decryptedKey.Length)
+ throw SQL.EmptyArgumentInConstructorInternal(_decryptedKeyName, _className);
+ if (null == keyMetadataVersion)
+ throw SQL.NullArgumentInConstructorInternal(_keyMetadataVersionName, _className);
+ if (0 == keyMetadataVersion.Length)
+ throw SQL.EmptyArgumentInConstructorInternal(_keyMetadataVersionName, _className);
KeyId = keyid;
DatabaseId = databaseId;
@@ -98,10 +102,14 @@ internal int GetLengthForSerialization()
internal int SerializeToBuffer(byte[] bytePackage, int startOffset)
{
- if (null == bytePackage) { throw SQL.NullArgumentInternal(_bytePackageName, _className, _serializeToBufferMethodName); }
- if (0 == bytePackage.Length) { throw SQL.EmptyArgumentInternal(_bytePackageName, _className, _serializeToBufferMethodName); }
- if (!(startOffset < bytePackage.Length)) { throw SQL.OffsetOutOfBounds(_startOffsetName, _className, _serializeToBufferMethodName); }
- if ((bytePackage.Length - startOffset) < GetLengthForSerialization()) { throw SQL.InsufficientBuffer(_bytePackageName, _className, _serializeToBufferMethodName); }
+ if (null == bytePackage)
+ throw SQL.NullArgumentInternal(_bytePackageName, _className, _serializeToBufferMethodName);
+ if (0 == bytePackage.Length)
+ throw SQL.EmptyArgumentInternal(_bytePackageName, _className, _serializeToBufferMethodName);
+ if (!(startOffset < bytePackage.Length))
+ throw SQL.OffsetOutOfBounds(_startOffsetName, _className, _serializeToBufferMethodName);
+ if ((bytePackage.Length - startOffset) < GetLengthForSerialization())
+ throw SQL.InsufficientBuffer(_bytePackageName, _className, _serializeToBufferMethodName);
Buffer.BlockCopy(DatabaseIdBytes, 0, bytePackage, startOffset, DatabaseIdBytes.Length);
startOffset += DatabaseIdBytes.Length;
diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/DataClassification/SensitivityClassification.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/DataClassification/SensitivityClassification.cs
index ca1344b559..845d139a77 100644
--- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/DataClassification/SensitivityClassification.cs
+++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/DataClassification/SensitivityClassification.cs
@@ -4,21 +4,24 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
-using System.Diagnostics;
-namespace Microsoft.Data.SqlClient.DataClassification {
+namespace Microsoft.Data.SqlClient.DataClassification
+{
- public class Label {
+ public class Label
+ {
public string Name { get; private set; }
public string Id { get; private set; }
- public Label(string name, string id) {
+ public Label(string name, string id)
+ {
Name = name;
Id = id;
}
}
- public class InformationType {
+ public class InformationType
+ {
public string Name { get; private set; }
public string Id { get; private set; }
@@ -29,30 +32,36 @@ public InformationType(string name, string id)
}
}
- public class SensitivityProperty {
+ public class SensitivityProperty
+ {
public Label Label { get; private set; }
public InformationType InformationType { get; private set; }
- public SensitivityProperty(Label label, InformationType informationType) {
+ public SensitivityProperty(Label label, InformationType informationType)
+ {
Label = label;
InformationType = informationType;
}
}
- public class ColumnSensitivity {
+ public class ColumnSensitivity
+ {
public ReadOnlyCollection SensitivityProperties { get; private set; }
- public ColumnSensitivity(IList sensitivityProperties) {
+ public ColumnSensitivity(IList sensitivityProperties)
+ {
SensitivityProperties = new ReadOnlyCollection(sensitivityProperties);
}
}
- public class SensitivityClassification {
+ public class SensitivityClassification
+ {
public ReadOnlyCollection
/// ActivityId
- internal static ActivityId Next()
+ internal static ActivityId Next()
{
if (tlsActivity == null)
{
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs
index ef01c6f475..0a9cfa2ff3 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs
@@ -2,32 +2,33 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
+using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
-using Microsoft.Data.SqlClient;
-using Microsoft.Data.SqlClient.Server;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
-using SysTx = System.Transactions;
+using Microsoft.Data.SqlClient;
+using Microsoft.Data.SqlClient.Server;
+using Microsoft.Win32;
using SysES = System.EnterpriseServices;
-using System.Runtime.Versioning;
-using System.Data.Common;
+using SysTx = System.Transactions;
-namespace Microsoft.Data.Common {
+namespace Microsoft.Data.Common
+{
internal static class ADP {
@@ -2579,4 +2580,4 @@ static internal bool IsAzureSqlServerEndpoint(string dataSource)
return false;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs
index e4f9b92985..2f502a12ef 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs
@@ -2,49 +2,46 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.Common {
+namespace Microsoft.Data.Common
+{
using System;
using System.Collections;
using System.Collections.Generic;
- using Microsoft.Data;
- using Microsoft.Data.Common;
+ using System.Data;
using System.Diagnostics;
- using System.Globalization;
using System.Linq;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
using System.Text;
- using System.Text.RegularExpressions;
- using System.Data;
[Serializable] // MDAC 83147
- internal sealed class DBConnectionString {
+ internal sealed class DBConnectionString
+ {
// instances of this class are intended to be immutable, i.e readonly
// used by permission classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
- private static class KEY {
- internal const string Password = "password";
+ private static class KEY
+ {
+ internal const string Password = "password";
internal const string PersistSecurityInfo = "persist security info";
- internal const string Pwd = "pwd";
+ internal const string Pwd = "pwd";
};
// this class is serializable with Everett, so ugly field names can't be changed
- readonly private string _encryptedUsersConnectionString;
+ readonly private string _encryptedUsersConnectionString;
// hash of unique keys to values
- readonly private Hashtable _parsetable;
+ readonly private Hashtable _parsetable;
// a linked list of key/value and their length in _encryptedUsersConnectionString
readonly private NameValuePair _keychain;
// track the existance of "password" or "pwd" in the connection string
// not used for anything anymore but must keep it set correct for V1.1 serialization
- readonly private bool _hasPassword;
+ readonly private bool _hasPassword;
readonly private string[] _restrictionValues;
- readonly private string _restrictions;
+ readonly private string _restrictions;
readonly private KeyRestrictionBehavior _behavior;
@@ -68,15 +65,17 @@ internal DBConnectionString(DbConnectionOptions connectionOptions)
// since backward compatability requires Everett level classes
}
- private DBConnectionString(DbConnectionOptions connectionOptions, string restrictions, KeyRestrictionBehavior behavior, Hashtable synonyms, bool mustCloneDictionary) { // used by DBDataPermission
+ private DBConnectionString(DbConnectionOptions connectionOptions, string restrictions, KeyRestrictionBehavior behavior, Hashtable synonyms, bool mustCloneDictionary)
+ { // used by DBDataPermission
Debug.Assert(null != connectionOptions, "null connectionOptions");
- switch(behavior) {
- case KeyRestrictionBehavior.PreventUsage:
- case KeyRestrictionBehavior.AllowOnly:
- _behavior = behavior;
- break;
- default:
- throw ADP.InvalidKeyRestrictionBehavior(behavior);
+ switch (behavior)
+ {
+ case KeyRestrictionBehavior.PreventUsage:
+ case KeyRestrictionBehavior.AllowOnly:
+ _behavior = behavior;
+ break;
+ default:
+ throw ADP.InvalidKeyRestrictionBehavior(behavior);
}
// grab all the parsed details from DbConnectionOptions
@@ -87,12 +86,14 @@ private DBConnectionString(DbConnectionOptions connectionOptions, string restric
// we do not want to serialize out user password unless directed so by "persist security info=true"
// otherwise all instances of user's password will be replaced with "*"
- if (_hasPassword && !connectionOptions.HasPersistablePassword) {
+ if (_hasPassword && !connectionOptions.HasPersistablePassword)
+ {
- if (mustCloneDictionary) {
+ if (mustCloneDictionary)
+ {
// clone the hashtable to replace user's password/pwd value with "*"
// we only need to clone if coming from DbConnectionOptions and password exists
- _parsetable = (Hashtable) _parsetable.Clone();
+ _parsetable = (Hashtable)_parsetable.Clone();
}
// different than Everett in that instead of removing password/pwd from
@@ -100,10 +101,12 @@ private DBConnectionString(DbConnectionOptions connectionOptions, string restric
// serialize out with '*' so already knows what we do. Better this way
// than to treat password specially later on which causes problems.
const string star = "*";
- if (_parsetable.ContainsKey(KEY.Password)) {
+ if (_parsetable.ContainsKey(KEY.Password))
+ {
_parsetable[KEY.Password] = star;
}
- if (_parsetable.ContainsKey(KEY.Pwd)) {
+ if (_parsetable.ContainsKey(KEY.Pwd))
+ {
_parsetable[KEY.Pwd] = star;
}
@@ -111,13 +114,15 @@ private DBConnectionString(DbConnectionOptions connectionOptions, string restric
_keychain = connectionOptions.ReplacePasswordPwd(out _encryptedUsersConnectionString, true);
}
- if (!ADP.IsEmpty(restrictions)) {
+ if (!ADP.IsEmpty(restrictions))
+ {
_restrictionValues = ParseRestrictions(restrictions, synonyms);
_restrictions = restrictions;
}
}
- private DBConnectionString(DBConnectionString connectionString, string[] restrictionValues, KeyRestrictionBehavior behavior) {
+ private DBConnectionString(DBConnectionString connectionString, string[] restrictionValues, KeyRestrictionBehavior behavior)
+ {
// used by intersect for two equal connection strings with different restrictions
_encryptedUsersConnectionString = connectionString._encryptedUsersConnectionString;
_parsetable = connectionString._parsetable;
@@ -131,31 +136,41 @@ private DBConnectionString(DBConnectionString connectionString, string[] restric
Verify(restrictionValues);
}
- internal KeyRestrictionBehavior Behavior {
+ internal KeyRestrictionBehavior Behavior
+ {
get { return _behavior; }
}
- internal string ConnectionString {
+ internal string ConnectionString
+ {
get { return _encryptedUsersConnectionString; }
}
- internal bool IsEmpty {
+ internal bool IsEmpty
+ {
get { return (null == _keychain); }
}
- internal NameValuePair KeyChain {
+ internal NameValuePair KeyChain
+ {
get { return _keychain; }
}
- internal string Restrictions {
- get {
+ internal string Restrictions
+ {
+ get
+ {
string restrictions = _restrictions;
- if (null == restrictions) {
+ if (null == restrictions)
+ {
string[] restrictionValues = _restrictionValues;
- if ((null != restrictionValues) && (0 < restrictionValues.Length)) {
+ if ((null != restrictionValues) && (0 < restrictionValues.Length))
+ {
StringBuilder builder = new StringBuilder();
- for(int i = 0; i < restrictionValues.Length; ++i) {
- if (!ADP.IsEmpty(restrictionValues[i])) {
+ for (int i = 0; i < restrictionValues.Length; ++i)
+ {
+ if (!ADP.IsEmpty(restrictionValues[i]))
+ {
builder.Append(restrictionValues[i]);
builder.Append("=;");
}
@@ -168,83 +183,105 @@ internal string Restrictions {
restrictions = builder.ToString();
}
}
- return ((null != restrictions) ? restrictions: "");
+ return ((null != restrictions) ? restrictions : "");
}
}
- internal string this[string keyword] {
+ internal string this[string keyword]
+ {
get { return (string)_parsetable[keyword]; }
}
- internal bool ContainsKey(string keyword) {
+ internal bool ContainsKey(string keyword)
+ {
return _parsetable.ContainsKey(keyword);
}
- internal DBConnectionString Intersect(DBConnectionString entry) {
+ internal DBConnectionString Intersect(DBConnectionString entry)
+ {
KeyRestrictionBehavior behavior = _behavior;
string[] restrictionValues = null;
- if (null == entry) {
+ if (null == entry)
+ {
//Debug.WriteLine("0 entry AllowNothing");
behavior = KeyRestrictionBehavior.AllowOnly;
}
- else if (this._behavior != entry._behavior) { // subset of the AllowOnly array
+ else if (this._behavior != entry._behavior)
+ { // subset of the AllowOnly array
behavior = KeyRestrictionBehavior.AllowOnly;
- if (KeyRestrictionBehavior.AllowOnly == entry._behavior) { // this PreventUsage and entry AllowOnly
- if (!ADP.IsEmptyArray(_restrictionValues)) {
- if (!ADP.IsEmptyArray(entry._restrictionValues)) {
+ if (KeyRestrictionBehavior.AllowOnly == entry._behavior)
+ { // this PreventUsage and entry AllowOnly
+ if (!ADP.IsEmptyArray(_restrictionValues))
+ {
+ if (!ADP.IsEmptyArray(entry._restrictionValues))
+ {
//Debug.WriteLine("1 this PreventUsage with restrictions and entry AllowOnly with restrictions");
restrictionValues = NewRestrictionAllowOnly(entry._restrictionValues, _restrictionValues);
}
- else {
+ else
+ {
//Debug.WriteLine("2 this PreventUsage with restrictions and entry AllowOnly with no restrictions");
}
}
- else {
+ else
+ {
//Debug.WriteLine("3/4 this PreventUsage with no restrictions and entry AllowOnly");
restrictionValues = entry._restrictionValues;
}
}
- else if (!ADP.IsEmptyArray(_restrictionValues)) { // this AllowOnly and entry PreventUsage
- if (!ADP.IsEmptyArray(entry._restrictionValues)) {
+ else if (!ADP.IsEmptyArray(_restrictionValues))
+ { // this AllowOnly and entry PreventUsage
+ if (!ADP.IsEmptyArray(entry._restrictionValues))
+ {
//Debug.WriteLine("5 this AllowOnly with restrictions and entry PreventUsage with restrictions");
restrictionValues = NewRestrictionAllowOnly(_restrictionValues, entry._restrictionValues);
}
- else {
+ else
+ {
//Debug.WriteLine("6 this AllowOnly and entry PreventUsage with no restrictions");
restrictionValues = _restrictionValues;
}
}
- else {
+ else
+ {
//Debug.WriteLine("7/8 this AllowOnly with no restrictions and entry PreventUsage");
}
}
- else if (KeyRestrictionBehavior.PreventUsage == this._behavior) { // both PreventUsage
- if (ADP.IsEmptyArray(_restrictionValues)) {
+ else if (KeyRestrictionBehavior.PreventUsage == this._behavior)
+ { // both PreventUsage
+ if (ADP.IsEmptyArray(_restrictionValues))
+ {
//Debug.WriteLine("9/10 both PreventUsage and this with no restrictions");
restrictionValues = entry._restrictionValues;
}
- else if (ADP.IsEmptyArray(entry._restrictionValues)) {
+ else if (ADP.IsEmptyArray(entry._restrictionValues))
+ {
//Debug.WriteLine("11 both PreventUsage and entry with no restrictions");
restrictionValues = _restrictionValues;
}
- else {
+ else
+ {
//Debug.WriteLine("12 both PreventUsage with restrictions");
restrictionValues = NoDuplicateUnion(_restrictionValues, entry._restrictionValues);
}
}
- else if (!ADP.IsEmptyArray(_restrictionValues) && !ADP.IsEmptyArray(entry._restrictionValues)) { // both AllowOnly with restrictions
- if (this._restrictionValues.Length <= entry._restrictionValues.Length) {
+ else if (!ADP.IsEmptyArray(_restrictionValues) && !ADP.IsEmptyArray(entry._restrictionValues))
+ { // both AllowOnly with restrictions
+ if (this._restrictionValues.Length <= entry._restrictionValues.Length)
+ {
//Debug.WriteLine("13a this AllowOnly with restrictions and entry AllowOnly with restrictions");
restrictionValues = NewRestrictionIntersect(_restrictionValues, entry._restrictionValues);
}
- else {
+ else
+ {
//Debug.WriteLine("13b this AllowOnly with restrictions and entry AllowOnly with restrictions");
restrictionValues = NewRestrictionIntersect(entry._restrictionValues, _restrictionValues);
}
}
- else { // both AllowOnly
+ else
+ { // both AllowOnly
//Debug.WriteLine("14/15/16 this AllowOnly and entry AllowOnly but no restrictions");
}
@@ -255,125 +292,155 @@ internal DBConnectionString Intersect(DBConnectionString entry) {
DBConnectionString value = new DBConnectionString(this, restrictionValues, behavior);
ValidateCombinedSet(this, value);
ValidateCombinedSet(entry, value);
-
+
return value;
}
[Conditional("DEBUG")]
- private void ValidateCombinedSet(DBConnectionString componentSet, DBConnectionString combinedSet) {
+ private void ValidateCombinedSet(DBConnectionString componentSet, DBConnectionString combinedSet)
+ {
Debug.Assert(combinedSet != null, "The combined connection string should not be null");
- if ((componentSet != null) && (combinedSet._restrictionValues != null) && (componentSet._restrictionValues != null)) {
- if (componentSet._behavior == KeyRestrictionBehavior.AllowOnly) {
- if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly) {
+ if ((componentSet != null) && (combinedSet._restrictionValues != null) && (componentSet._restrictionValues != null))
+ {
+ if (componentSet._behavior == KeyRestrictionBehavior.AllowOnly)
+ {
+ if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly)
+ {
// Component==Allow, Combined==Allow
// All values in the Combined Set should also be in the Component Set
// Combined - Component == null
Debug.Assert(combinedSet._restrictionValues.Except(componentSet._restrictionValues).Count() == 0, "Combined set allows values not allowed by component set");
}
- else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage) {
+ else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage)
+ {
// Component==Allow, Combined==PreventUsage
// Preventions override allows, so there is nothing to check here
}
- else {
+ else
+ {
Debug.Assert(false, string.Format("Unknown behavior for combined set: {0}", combinedSet._behavior));
}
}
- else if (componentSet._behavior == KeyRestrictionBehavior.PreventUsage) {
- if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly) {
+ else if (componentSet._behavior == KeyRestrictionBehavior.PreventUsage)
+ {
+ if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly)
+ {
// Component==PreventUsage, Combined==Allow
// There shouldn't be any of the values from the Component Set in the Combined Set
// Intersect(Component, Combined) == null
Debug.Assert(combinedSet._restrictionValues.Intersect(componentSet._restrictionValues).Count() == 0, "Combined values allows values prevented by component set");
}
- else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage) {
+ else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage)
+ {
// Component==PreventUsage, Combined==PreventUsage
// All values in the Component Set should also be in the Combined Set
// Component - Combined == null
Debug.Assert(componentSet._restrictionValues.Except(combinedSet._restrictionValues).Count() == 0, "Combined values does not prevent all of the values prevented by the component set");
}
- else {
+ else
+ {
Debug.Assert(false, string.Format("Unknown behavior for combined set: {0}", combinedSet._behavior));
}
}
- else {
+ else
+ {
Debug.Assert(false, string.Format("Unknown behavior for component set: {0}", componentSet._behavior));
}
}
}
- private bool IsRestrictedKeyword(string key) {
+ private bool IsRestrictedKeyword(string key)
+ {
// restricted if not found
return ((null == _restrictionValues) || (0 > Array.BinarySearch(_restrictionValues, key, StringComparer.Ordinal)));
}
- internal bool IsSupersetOf(DBConnectionString entry) {
+ internal bool IsSupersetOf(DBConnectionString entry)
+ {
Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this");
Debug.Assert(!entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry");
- switch(_behavior) {
- case KeyRestrictionBehavior.AllowOnly:
- // every key must either be in the resticted connection string or in the allowed keywords
- // keychain may contain duplicates, but it is better than GetEnumerator on _parsetable.Keys
- for(NameValuePair current = entry.KeyChain; null != current; current = current.Next) {
- if (!ContainsKey(current.Name) && IsRestrictedKeyword(current.Name)) {
- return false;
- }
- }
- break;
- case KeyRestrictionBehavior.PreventUsage:
- // every key can not be in the restricted keywords (even if in the restricted connection string)
- if (null != _restrictionValues) {
- foreach(string restriction in _restrictionValues) {
- if (entry.ContainsKey(restriction)) {
+ switch (_behavior)
+ {
+ case KeyRestrictionBehavior.AllowOnly:
+ // every key must either be in the resticted connection string or in the allowed keywords
+ // keychain may contain duplicates, but it is better than GetEnumerator on _parsetable.Keys
+ for (NameValuePair current = entry.KeyChain; null != current; current = current.Next)
+ {
+ if (!ContainsKey(current.Name) && IsRestrictedKeyword(current.Name))
+ {
return false;
}
}
- }
- break;
- default:
- Debug.Assert(false, "invalid KeyRestrictionBehavior");
- throw ADP.InvalidKeyRestrictionBehavior(_behavior);
+ break;
+ case KeyRestrictionBehavior.PreventUsage:
+ // every key can not be in the restricted keywords (even if in the restricted connection string)
+ if (null != _restrictionValues)
+ {
+ foreach (string restriction in _restrictionValues)
+ {
+ if (entry.ContainsKey(restriction))
+ {
+ return false;
+ }
+ }
+ }
+ break;
+ default:
+ Debug.Assert(false, "invalid KeyRestrictionBehavior");
+ throw ADP.InvalidKeyRestrictionBehavior(_behavior);
}
return true;
}
- static private string[] NewRestrictionAllowOnly(string[] allowonly, string[] preventusage) {
+ static private string[] NewRestrictionAllowOnly(string[] allowonly, string[] preventusage)
+ {
List newlist = null;
- for (int i = 0; i < allowonly.Length; ++i) {
- if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal)) {
- if (null == newlist) {
+ for (int i = 0; i < allowonly.Length; ++i)
+ {
+ if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal))
+ {
+ if (null == newlist)
+ {
newlist = new List();
}
newlist.Add(allowonly[i]);
}
}
string[] restrictionValues = null;
- if (null != newlist) {
+ if (null != newlist)
+ {
restrictionValues = newlist.ToArray();
}
Verify(restrictionValues);
return restrictionValues;
}
- static private string[] NewRestrictionIntersect(string[] a, string[] b) {
+ static private string[] NewRestrictionIntersect(string[] a, string[] b)
+ {
List newlist = null;
- for (int i = 0; i < a.Length; ++i) {
- if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal)) {
- if (null == newlist) {
+ for (int i = 0; i < a.Length; ++i)
+ {
+ if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal))
+ {
+ if (null == newlist)
+ {
newlist = new List();
}
newlist.Add(a[i]);
}
}
string[] restrictionValues = null;
- if (newlist != null) {
+ if (newlist != null)
+ {
restrictionValues = newlist.ToArray();
}
Verify(restrictionValues);
return restrictionValues;
}
- static private string[] NoDuplicateUnion(string[] a, string[] b) {
+ static private string[] NoDuplicateUnion(string[] a, string[] b)
+ {
#if DEBUG
Debug.Assert(null != a && 0 < a.Length, "empty a");
Debug.Assert(null != b && 0 < b.Length, "empty b");
@@ -381,11 +448,14 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) {
Verify(b);
#endif
List newlist = new List(a.Length + b.Length);
- for(int i = 0; i < a.Length; ++i) {
+ for (int i = 0; i < a.Length; ++i)
+ {
newlist.Add(a[i]);
}
- for(int i = 0; i < b.Length; ++i) { // find duplicates
- if (0 > Array.BinarySearch(a, b[i], StringComparer.Ordinal)) {
+ for (int i = 0; i < b.Length; ++i)
+ { // find duplicates
+ if (0 > Array.BinarySearch(a, b[i], StringComparer.Ordinal))
+ {
newlist.Add(b[i]);
}
}
@@ -395,7 +465,8 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) {
return restrictionValues;
}
- private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) {
+ private static string[] ParseRestrictions(string restrictions, Hashtable synonyms)
+ {
#if DEBUG
if (Bid.AdvancedOn) {
Bid.Trace(" Restrictions='%ls'\n", restrictions);
@@ -406,19 +477,22 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym
int nextStartPosition = 0;
int endPosition = restrictions.Length;
- while (nextStartPosition < endPosition) {
+ while (nextStartPosition < endPosition)
+ {
int startPosition = nextStartPosition;
string keyname, keyvalue; // since parsing restrictions ignores values, it doesn't matter if we use ODBC rules or OLEDB rules
nextStartPosition = DbConnectionOptions.GetKeyValuePair(restrictions, startPosition, buffer, false, out keyname, out keyvalue);
- if (!ADP.IsEmpty(keyname)) {
+ if (!ADP.IsEmpty(keyname))
+ {
#if DEBUG
if (Bid.AdvancedOn) {
Bid.Trace(" KeyName='%ls'\n", keyname);
}
#endif
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144
- if (ADP.IsEmpty(realkeyname)) {
+ if (ADP.IsEmpty(realkeyname))
+ {
throw ADP.KeywordNotSupported(keyname);
}
restrictionValues.Add(realkeyname);
@@ -428,27 +502,35 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym
}
- static internal string[] RemoveDuplicates(string[] restrictions) {
+ static internal string[] RemoveDuplicates(string[] restrictions)
+ {
int count = restrictions.Length;
- if (0 < count) {
+ if (0 < count)
+ {
Array.Sort(restrictions, StringComparer.Ordinal);
- for (int i = 1; i < restrictions.Length; ++i) {
- string prev = restrictions[i-1];
- if ((0 == prev.Length) || (prev == restrictions[i])) {
- restrictions[i-1] = null;
+ for (int i = 1; i < restrictions.Length; ++i)
+ {
+ string prev = restrictions[i - 1];
+ if ((0 == prev.Length) || (prev == restrictions[i]))
+ {
+ restrictions[i - 1] = null;
count--;
}
}
- if (0 == restrictions[restrictions.Length-1].Length) {
- restrictions[restrictions.Length-1] = null;
+ if (0 == restrictions[restrictions.Length - 1].Length)
+ {
+ restrictions[restrictions.Length - 1] = null;
count--;
}
- if (count != restrictions.Length) {
+ if (count != restrictions.Length)
+ {
string[] tmp = new String[count];
count = 0;
- for (int i = 0; i < restrictions.Length; ++i) {
- if (null != restrictions[i]) {
+ for (int i = 0; i < restrictions.Length; ++i)
+ {
+ if (null != restrictions[i])
+ {
tmp[count++] = restrictions[i];
}
}
@@ -460,12 +542,15 @@ static internal string[] RemoveDuplicates(string[] restrictions) {
}
[ConditionalAttribute("DEBUG")]
- private static void Verify(string[] restrictionValues) {
- if (null != restrictionValues) {
- for (int i = 1; i < restrictionValues.Length; ++i) {
- Debug.Assert(!ADP.IsEmpty(restrictionValues[i-1]), "empty restriction");
+ private static void Verify(string[] restrictionValues)
+ {
+ if (null != restrictionValues)
+ {
+ for (int i = 1; i < restrictionValues.Length; ++i)
+ {
+ Debug.Assert(!ADP.IsEmpty(restrictionValues[i - 1]), "empty restriction");
Debug.Assert(!ADP.IsEmpty(restrictionValues[i]), "empty restriction");
- Debug.Assert(0 >= StringComparer.Ordinal.Compare(restrictionValues[i-1], restrictionValues[i]));
+ Debug.Assert(0 >= StringComparer.Ordinal.Compare(restrictionValues[i - 1], restrictionValues[i]));
}
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs
index 6869a479a9..f446add866 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs
@@ -2,20 +2,19 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.Common {
+namespace Microsoft.Data.Common
+{
using System;
using System.Collections;
- using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
+ using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
- using System.Runtime.Versioning;
- internal class DbConnectionOptions {
+ internal class DbConnectionOptions
+ {
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
@@ -75,7 +74,7 @@ internal class DbConnectionOptions {
private static readonly Regex ConnectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private static readonly Regex ConnectionStringRegexOdbc = new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
- private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?=;
- if (useOdbcRules) {
+ if (null != keyValue)
+ { // else =;
+ if (useOdbcRules)
+ {
if ((0 < keyValue.Length) &&
(('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || (0 == String.Compare(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase))) &&
!ConnectionStringQuoteOdbcValueRegex.IsMatch(keyValue))
@@ -245,21 +277,25 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key
// always quote values that contain a ';'
builder.Append('{').Append(keyValue.Replace("}", "}}")).Append('}');
}
- else {
+ else
+ {
builder.Append(keyValue);
}
}
- else if (ConnectionStringQuoteValueRegex.IsMatch(keyValue)) {
+ else if (ConnectionStringQuoteValueRegex.IsMatch(keyValue))
+ {
// ->
builder.Append(keyValue);
}
- else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\''))) {
+ else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\'')))
+ {
// -> <'val"ue'>
builder.Append('\'');
builder.Append(keyValue);
builder.Append('\'');
}
- else {
+ else
+ {
// -> <"val'ue">
// <=value> -> <"=value">
// <;value> -> <";value">
@@ -273,102 +309,125 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key
}
}
- public bool ConvertValueToBoolean(string keyName, bool defaultValue) {
+ public bool ConvertValueToBoolean(string keyName, bool defaultValue)
+ {
object value = _parsetable[keyName];
- if (null == value) {
+ if (null == value)
+ {
return defaultValue;
}
- return ConvertValueToBooleanInternal(keyName, (string) value);
+ return ConvertValueToBooleanInternal(keyName, (string)value);
}
- internal static bool ConvertValueToBooleanInternal(string keyName, string stringValue) {
+ internal static bool ConvertValueToBooleanInternal(string keyName, string stringValue)
+ {
if (CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
- else {
+ else
+ {
string tmp = stringValue.Trim(); // Remove leading & trailing white space.
if (CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
- else {
+ else
+ {
throw ADP.InvalidConnectionOptionValue(keyName);
}
}
}
// same as Boolean, but with SSPI thrown in as valid yes
- public bool ConvertValueToIntegratedSecurity() {
+ public bool ConvertValueToIntegratedSecurity()
+ {
object value = _parsetable[KEY.Integrated_Security];
- if (null == value) {
+ if (null == value)
+ {
return false;
}
- return ConvertValueToIntegratedSecurityInternal((string) value);
+ return ConvertValueToIntegratedSecurityInternal((string)value);
}
- internal bool ConvertValueToIntegratedSecurityInternal(string stringValue) {
+ internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
+ {
if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
- else {
+ else
+ {
string tmp = stringValue.Trim(); // Remove leading & trailing white space.
if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
- else {
+ else
+ {
throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security);
}
}
}
- public int ConvertValueToInt32(string keyName, int defaultValue) {
+ public int ConvertValueToInt32(string keyName, int defaultValue)
+ {
object value = _parsetable[keyName];
- if (null == value) {
+ if (null == value)
+ {
return defaultValue;
}
- return ConvertToInt32Internal(keyName, (string) value);
+ return ConvertToInt32Internal(keyName, (string)value);
}
- internal static int ConvertToInt32Internal(string keyname, string stringValue) {
- try {
+ internal static int ConvertToInt32Internal(string keyname, string stringValue)
+ {
+ try
+ {
return System.Int32.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
}
- catch (FormatException e) {
+ catch (FormatException e)
+ {
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
- catch (OverflowException e) {
+ catch (OverflowException e)
+ {
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
}
- public string ConvertValueToString(string keyName, string defaultValue) {
+ public string ConvertValueToString(string keyName, string defaultValue)
+ {
string value = (string)_parsetable[keyName];
return ((null != value) ? value : defaultValue);
}
- static private bool CompareInsensitiveInvariant(string strvalue, string strconst) {
+ static private bool CompareInsensitiveInvariant(string strvalue, string strconst)
+ {
return (0 == StringComparer.OrdinalIgnoreCase.Compare(strvalue, strconst));
}
- public bool ContainsKey(string keyword) {
+ public bool ContainsKey(string keyword)
+ {
return _parsetable.ContainsKey(keyword);
}
- protected internal virtual System.Security.PermissionSet CreatePermissionSet() {
+ protected internal virtual System.Security.PermissionSet CreatePermissionSet()
+ {
return null;
}
- internal void DemandPermission() {
- if (null == _permissionset) {
+ internal void DemandPermission()
+ {
+ if (null == _permissionset)
+ {
_permissionset = CreatePermissionSet();
}
_permissionset.Demand();
}
- protected internal virtual string Expand() {
+ protected internal virtual string Expand()
+ {
return _usersConnectionString;
}
@@ -378,22 +437,28 @@ protected internal virtual string Expand() {
// * This method uses GetFullPath to validate that root path is valid, the result is not exposed out.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
- internal static string ExpandDataDirectory(string keyword, string value, ref string datadir) {
+ internal static string ExpandDataDirectory(string keyword, string value, ref string datadir)
+ {
string fullPath = null;
- if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) {
+ if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase))
+ {
string rootFolderPath = datadir;
- if (null == rootFolderPath) {
+ if (null == rootFolderPath)
+ {
// find the replacement path
object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory");
rootFolderPath = (rootFolderObject as string);
- if ((null != rootFolderObject) && (null == rootFolderPath)) {
+ if ((null != rootFolderObject) && (null == rootFolderPath))
+ {
throw ADP.InvalidDataDirectory();
}
- else if (ADP.IsEmpty(rootFolderPath)) {
+ else if (ADP.IsEmpty(rootFolderPath))
+ {
rootFolderPath = AppDomain.CurrentDomain.BaseDirectory;
}
- if (null == rootFolderPath) {
+ if (null == rootFolderPath)
+ {
rootFolderPath = "";
}
// cache the |DataDir| for ExpandDataDirectories
@@ -402,32 +467,37 @@ internal static string ExpandDataDirectory(string keyword, string value, ref str
// We don't know if rootFolderpath ends with '\', and we don't know if the given name starts with onw
int fileNamePosition = DataDirectory.Length; // filename starts right after the '|datadirectory|' keyword
- bool rootFolderEndsWith = (0 < rootFolderPath.Length) && rootFolderPath[rootFolderPath.Length-1] == '\\';
+ bool rootFolderEndsWith = (0 < rootFolderPath.Length) && rootFolderPath[rootFolderPath.Length - 1] == '\\';
bool fileNameStartsWith = (fileNamePosition < value.Length) && value[fileNamePosition] == '\\';
// replace |datadirectory| with root folder path
- if (!rootFolderEndsWith && !fileNameStartsWith) {
+ if (!rootFolderEndsWith && !fileNameStartsWith)
+ {
// need to insert '\'
fullPath = rootFolderPath + '\\' + value.Substring(fileNamePosition);
}
- else if (rootFolderEndsWith && fileNameStartsWith) {
+ else if (rootFolderEndsWith && fileNameStartsWith)
+ {
// need to strip one out
- fullPath = rootFolderPath + value.Substring(fileNamePosition+1);
+ fullPath = rootFolderPath + value.Substring(fileNamePosition + 1);
}
- else {
+ else
+ {
// simply concatenate the strings
fullPath = rootFolderPath + value.Substring(fileNamePosition);
}
// verify root folder path is a real path without unexpected "..\"
- if (!ADP.GetFullPath(fullPath).StartsWith(rootFolderPath, StringComparison.Ordinal)) {
+ if (!ADP.GetFullPath(fullPath).StartsWith(rootFolderPath, StringComparison.Ordinal))
+ {
throw ADP.InvalidConnectionOptionValue(keyword);
}
}
return fullPath;
}
- internal string ExpandDataDirectories(ref string filename, ref int position) {
+ internal string ExpandDataDirectories(ref string filename, ref int position)
+ {
string value = null;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
string datadir = null;
@@ -435,7 +505,8 @@ internal string ExpandDataDirectories(ref string filename, ref int position) {
int copyPosition = 0;
bool expanded = false;
- for(NameValuePair current = KeyChain; null != current; current = current.Next) {
+ for (NameValuePair current = KeyChain; null != current; current = current.Next)
+ {
value = current.Value;
// remove duplicate keyswords from connectionstring
@@ -446,47 +517,56 @@ internal string ExpandDataDirectories(ref string filename, ref int position) {
//}
// There is a set of keywords we explictly do NOT want to expand |DataDirectory| on
- if (UseOdbcRules) {
- switch(current.Name) {
- case DbConnectionOptionKeywords.Driver:
- case DbConnectionOptionKeywords.Pwd:
- case DbConnectionOptionKeywords.UID:
- break;
- default:
- value = ExpandDataDirectory(current.Name, value, ref datadir);
- break;
+ if (UseOdbcRules)
+ {
+ switch (current.Name)
+ {
+ case DbConnectionOptionKeywords.Driver:
+ case DbConnectionOptionKeywords.Pwd:
+ case DbConnectionOptionKeywords.UID:
+ break;
+ default:
+ value = ExpandDataDirectory(current.Name, value, ref datadir);
+ break;
}
}
- else {
- switch(current.Name) {
- case DbConnectionOptionKeywords.Provider:
- case DbConnectionOptionKeywords.DataProvider:
- case DbConnectionOptionKeywords.RemoteProvider:
- case DbConnectionOptionKeywords.ExtendedProperties:
- case DbConnectionOptionKeywords.UserID:
- case DbConnectionOptionKeywords.Password:
- case DbConnectionOptionKeywords.UID:
- case DbConnectionOptionKeywords.Pwd:
- break;
- default:
- value = ExpandDataDirectory(current.Name, value, ref datadir);
- break;
+ else
+ {
+ switch (current.Name)
+ {
+ case DbConnectionOptionKeywords.Provider:
+ case DbConnectionOptionKeywords.DataProvider:
+ case DbConnectionOptionKeywords.RemoteProvider:
+ case DbConnectionOptionKeywords.ExtendedProperties:
+ case DbConnectionOptionKeywords.UserID:
+ case DbConnectionOptionKeywords.Password:
+ case DbConnectionOptionKeywords.UID:
+ case DbConnectionOptionKeywords.Pwd:
+ break;
+ default:
+ value = ExpandDataDirectory(current.Name, value, ref datadir);
+ break;
}
}
- if (null == value) {
+ if (null == value)
+ {
value = current.Value;
}
- if (UseOdbcRules || (DbConnectionOptionKeywords.FileName != current.Name)) {
- if (value != current.Value) {
+ if (UseOdbcRules || (DbConnectionOptionKeywords.FileName != current.Name))
+ {
+ if (value != current.Value)
+ {
expanded = true;
AppendKeyValuePairBuilder(builder, current.Name, value, UseOdbcRules);
builder.Append(';');
}
- else {
+ else
+ {
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
}
- else {
+ else
+ {
// strip out 'File Name=myconnection.udl' for OleDb
// remembering is value for which UDL file to open
// and where to insert the strnig
@@ -497,37 +577,44 @@ internal string ExpandDataDirectories(ref string filename, ref int position) {
copyPosition += current.Length;
}
- if (expanded) {
+ if (expanded)
+ {
value = builder.ToString();
}
- else {
+ else
+ {
value = null;
}
return value;
}
- internal string ExpandKeyword(string keyword, string replacementValue) {
+ internal string ExpandKeyword(string keyword, string replacementValue)
+ {
// preserve duplicates, updated keyword value with replacement value
// if keyword not specified, append to end of the string
bool expanded = false;
int copyPosition = 0;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
- for(NameValuePair current = KeyChain; null != current; current = current.Next) {
- if ((current.Name == keyword) && (current.Value == this[keyword])) {
+ for (NameValuePair current = KeyChain; null != current; current = current.Next)
+ {
+ if ((current.Name == keyword) && (current.Value == this[keyword]))
+ {
// only replace the parse end-result value instead of all values
// so that when duplicate-keywords occur other original values remain in place
AppendKeyValuePairBuilder(builder, current.Name, replacementValue, UseOdbcRules);
builder.Append(';');
expanded = true;
}
- else {
+ else
+ {
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
copyPosition += current.Length;
}
- if (!expanded) {
+ if (!expanded)
+ {
// TODO: technically for ODBC it should be prepended but not using the method from ODBC
Debug.Assert(!UseOdbcRules, "ExpandKeyword not ready for Odbc");
AppendKeyValuePairBuilder(builder, keyword, replacementValue, UseOdbcRules);
@@ -554,22 +641,28 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash
}
#endif
- static private string GetKeyName(StringBuilder buffer) {
+ static private string GetKeyName(StringBuilder buffer)
+ {
int count = buffer.Length;
- while ((0 < count) && Char.IsWhiteSpace(buffer[count-1])) {
+ while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1]))
+ {
count--; // trailing whitespace
}
return buffer.ToString(0, count).ToLower(CultureInfo.InvariantCulture);
}
- static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace) {
+ static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace)
+ {
int count = buffer.Length;
int index = 0;
- if (trimWhitespace) {
- while ((index < count) && Char.IsWhiteSpace(buffer[index])) {
+ if (trimWhitespace)
+ {
+ while ((index < count) && Char.IsWhiteSpace(buffer[index]))
+ {
index++; // leading whitespace
}
- while ((0 < count) && Char.IsWhiteSpace(buffer[count-1])) {
+ while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1]))
+ {
count--; // trailing whitespace
}
}
@@ -577,8 +670,9 @@ static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace) {
}
// transistion states used for parsing
- private enum ParserState {
- NothingYet=1, //start point
+ private enum ParserState
+ {
+ NothingYet = 1, //start point
Key,
KeyEqual,
KeyEnd,
@@ -593,7 +687,8 @@ private enum ParserState {
NullTermination,
};
- static internal int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue) {
+ static internal int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue)
+ {
int startposition = currentPosition;
buffer.Length = 0;
@@ -604,158 +699,200 @@ static internal int GetKeyValuePair(string connectionString, int currentPosition
ParserState parserState = ParserState.NothingYet;
int length = connectionString.Length;
- for (; currentPosition < length; ++currentPosition) {
+ for (; currentPosition < length; ++currentPosition)
+ {
currentChar = connectionString[currentPosition];
- switch(parserState) {
- case ParserState.NothingYet: // [\\s;]*
- if ((';' == currentChar) || Char.IsWhiteSpace(currentChar)) {
- continue;
- }
- if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } // MDAC 83540
- if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
- startposition = currentPosition;
- if ('=' != currentChar) { // MDAC 86902
- parserState = ParserState.Key;
+ switch (parserState)
+ {
+ case ParserState.NothingYet: // [\\s;]*
+ if ((';' == currentChar) || Char.IsWhiteSpace(currentChar))
+ {
+ continue;
+ }
+ if ('\0' == currentChar)
+ { parserState = ParserState.NullTermination; continue; } // MDAC 83540
+ if (Char.IsControl(currentChar))
+ { throw ADP.ConnectionStringSyntax(startposition); }
+ startposition = currentPosition;
+ if ('=' != currentChar)
+ { // MDAC 86902
+ parserState = ParserState.Key;
+ break;
+ }
+ else
+ {
+ parserState = ParserState.KeyEqual;
+ continue;
+ }
+
+ case ParserState.Key: // (?([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
+ if ('=' == currentChar)
+ { parserState = ParserState.KeyEqual; continue; }
+ if (Char.IsWhiteSpace(currentChar))
+ { break; }
+ if (Char.IsControl(currentChar))
+ { throw ADP.ConnectionStringSyntax(startposition); }
break;
- }
- else {
- parserState = ParserState.KeyEqual;
- continue;
- }
- case ParserState.Key: // (?([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
- if ('=' == currentChar) { parserState = ParserState.KeyEqual; continue; }
- if (Char.IsWhiteSpace(currentChar)) { break; }
- if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
- break;
+ case ParserState.KeyEqual: // \\s*=(?!=)\\s*
+ if (!useOdbcRules && '=' == currentChar)
+ { parserState = ParserState.Key; break; }
+ keyname = GetKeyName(buffer);
+ if (ADP.IsEmpty(keyname))
+ { throw ADP.ConnectionStringSyntax(startposition); }
+ buffer.Length = 0;
+ parserState = ParserState.KeyEnd;
+ goto case ParserState.KeyEnd;
+
+ case ParserState.KeyEnd:
+ if (Char.IsWhiteSpace(currentChar))
+ { continue; }
+ if (useOdbcRules)
+ {
+ if ('{' == currentChar)
+ { parserState = ParserState.BraceQuoteValue; break; }
+ }
+ else
+ {
+ if ('\'' == currentChar)
+ { parserState = ParserState.SingleQuoteValue; continue; }
+ if ('"' == currentChar)
+ { parserState = ParserState.DoubleQuoteValue; continue; }
+ }
+ if (';' == currentChar)
+ { goto ParserExit; }
+ if ('\0' == currentChar)
+ { goto ParserExit; }
+ if (Char.IsControl(currentChar))
+ { throw ADP.ConnectionStringSyntax(startposition); }
+ parserState = ParserState.UnquotedValue;
+ break;
- case ParserState.KeyEqual: // \\s*=(?!=)\\s*
- if (!useOdbcRules && '=' == currentChar) { parserState = ParserState.Key; break; }
- keyname = GetKeyName(buffer);
- if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
- buffer.Length = 0;
- parserState = ParserState.KeyEnd;
- goto case ParserState.KeyEnd;
+ case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(? myConnectionNames = new List();
- foreach(System.Configuration.ConnectionStringSetting setting in System.Configuration.ConfigurationManager.ConnectionStrings) {
- if (myProviderName.EndsWith(setting.ProviderName)) {
- myConnectionNames.Add(setting.ConnectionName);
+ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
+ StandardValuesCollection standardValues = null;
+ if (null != context) {
+ DbConnectionStringBuilder instance = (context.Instance as DbConnectionStringBuilder);
+ if (null != instance) {
+ string myProviderName = instance.GetType().Namespace;
+
+ List myConnectionNames = new List();
+ foreach(System.Configuration.ConnectionStringSetting setting in System.Configuration.ConfigurationManager.ConnectionStrings) {
+ if (myProviderName.EndsWith(setting.ProviderName)) {
+ myConnectionNames.Add(setting.ConnectionName);
+ }
}
+ standardValues = new StandardValuesCollection(myConnectionNames);
}
- standardValues = new StandardValuesCollection(myConnectionNames);
}
+ return standardValues;
}
- return standardValues;
}
- }
-*/
+ */
+
-
[Serializable()]
- internal sealed class ReadOnlyCollection : System.Collections.ICollection, ICollection {
+ internal sealed class ReadOnlyCollection : System.Collections.ICollection, ICollection
+ {
private T[] _items;
- internal ReadOnlyCollection(T[] items) {
+ internal ReadOnlyCollection(T[] items)
+ {
_items = items;
#if DEBUG
for(int i = 0; i < items.Length; ++i) {
@@ -62,85 +63,106 @@ internal ReadOnlyCollection(T[] items) {
#endif
}
- public void CopyTo(T[] array, int arrayIndex) {
+ public void CopyTo(T[] array, int arrayIndex)
+ {
Array.Copy(_items, 0, array, arrayIndex, _items.Length);
}
- void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) {
+ void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
+ {
Array.Copy(_items, 0, array, arrayIndex, _items.Length);
}
- IEnumerator IEnumerable.GetEnumerator() {
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return new Enumerator(_items);
}
- public System.Collections.IEnumerator GetEnumerator() {
+ public System.Collections.IEnumerator GetEnumerator()
+ {
return new Enumerator(_items);
}
- bool System.Collections.ICollection.IsSynchronized {
+ bool System.Collections.ICollection.IsSynchronized
+ {
get { return false; }
}
- Object System.Collections.ICollection.SyncRoot {
+ Object System.Collections.ICollection.SyncRoot
+ {
get { return _items; }
}
- bool ICollection.IsReadOnly {
- get { return true;}
+ bool ICollection.IsReadOnly
+ {
+ get { return true; }
}
- void ICollection.Add(T value) {
+ void ICollection.Add(T value)
+ {
throw new NotSupportedException();
}
- void ICollection.Clear() {
+ void ICollection.Clear()
+ {
throw new NotSupportedException();
}
- bool ICollection.Contains(T value) {
+ bool ICollection.Contains(T value)
+ {
return Array.IndexOf(_items, value) >= 0;
}
- bool ICollection.Remove(T value) {
+ bool ICollection.Remove(T value)
+ {
throw new NotSupportedException();
}
- public int Count {
+ public int Count
+ {
get { return _items.Length; }
}
[Serializable()]
- internal struct Enumerator : IEnumerator, System.Collections.IEnumerator { // based on List.Enumerator
+ internal struct Enumerator : IEnumerator, System.Collections.IEnumerator
+ { // based on List.Enumerator
private K[] _items;
private int _index;
- internal Enumerator(K[] items) {
+ internal Enumerator(K[] items)
+ {
_items = items;
_index = -1;
}
- public void Dispose() {
+ public void Dispose()
+ {
}
- public bool MoveNext() {
+ public bool MoveNext()
+ {
return (++_index < _items.Length);
}
- public K Current {
- get {
+ public K Current
+ {
+ get
+ {
return _items[_index];
}
}
- Object System.Collections.IEnumerator.Current {
- get {
+ Object System.Collections.IEnumerator.Current
+ {
+ get
+ {
return _items[_index];
}
}
- void System.Collections.IEnumerator.Reset() {
+ void System.Collections.IEnumerator.Reset()
+ {
_index = -1;
}
}
@@ -274,7 +296,7 @@ internal static bool IsValidPoolBlockingPeriodValue(PoolBlockingPeriod value)
internal static string PoolBlockingPeriodToString(PoolBlockingPeriod value)
{
Debug.Assert(IsValidPoolBlockingPeriodValue(value));
-
+
if (value == PoolBlockingPeriod.AlwaysBlock)
{
return PoolBlockingPeriodAlwaysBlockString;
@@ -506,7 +528,7 @@ internal static bool TryConvertToAuthenticationType(string value, out SqlAuthent
bool isSuccess = false;
- if (StringComparer.InvariantCultureIgnoreCase.Equals(value, SqlPasswordString)
+ if (StringComparer.InvariantCultureIgnoreCase.Equals(value, SqlPasswordString)
|| StringComparer.InvariantCultureIgnoreCase.Equals(value, Convert.ToString(SqlAuthenticationMethod.SqlPassword, CultureInfo.InvariantCulture)))
{
result = SqlAuthenticationMethod.SqlPassword;
@@ -556,18 +578,22 @@ internal static bool TryConvertToAuthenticationType(string value, out SqlAuthent
///
///
///
- internal static bool TryConvertToColumnEncryptionSetting(string value, out SqlConnectionColumnEncryptionSetting result) {
+ internal static bool TryConvertToColumnEncryptionSetting(string value, out SqlConnectionColumnEncryptionSetting result)
+ {
bool isSuccess = false;
- if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ColumnEncryptionSettingEnabledString)) {
+ if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ColumnEncryptionSettingEnabledString))
+ {
result = SqlConnectionColumnEncryptionSetting.Enabled;
isSuccess = true;
}
- else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ColumnEncryptionSettingDisabledString)) {
+ else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ColumnEncryptionSettingDisabledString))
+ {
result = SqlConnectionColumnEncryptionSetting.Disabled;
isSuccess = true;
}
- else {
+ else
+ {
result = DbConnectionStringDefaults.ColumnEncryptionSetting;
}
@@ -579,7 +605,8 @@ internal static bool TryConvertToColumnEncryptionSetting(string value, out SqlCo
///
///
///
- internal static bool IsValidColumnEncryptionSetting(SqlConnectionColumnEncryptionSetting value) {
+ internal static bool IsValidColumnEncryptionSetting(SqlConnectionColumnEncryptionSetting value)
+ {
Debug.Assert(Enum.GetNames(typeof(SqlConnectionColumnEncryptionSetting)).Length == 2, "SqlConnectionColumnEncryptionSetting enum has changed, update needed");
return value == SqlConnectionColumnEncryptionSetting.Enabled || value == SqlConnectionColumnEncryptionSetting.Disabled;
}
@@ -589,10 +616,12 @@ internal static bool IsValidColumnEncryptionSetting(SqlConnectionColumnEncryptio
///
///
///
- internal static string ColumnEncryptionSettingToString(SqlConnectionColumnEncryptionSetting value) {
+ internal static string ColumnEncryptionSettingToString(SqlConnectionColumnEncryptionSetting value)
+ {
Debug.Assert(IsValidColumnEncryptionSetting(value), "value is not a valid connection level column encryption setting.");
- switch (value) {
+ switch (value)
+ {
case SqlConnectionColumnEncryptionSetting.Enabled:
return ColumnEncryptionSettingEnabledString;
case SqlConnectionColumnEncryptionSetting.Disabled:
@@ -603,7 +632,8 @@ internal static string ColumnEncryptionSettingToString(SqlConnectionColumnEncryp
}
}
- internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value) {
+ internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value)
+ {
Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 5, "SqlAuthenticationMethod enum has changed, update needed");
return value == SqlAuthenticationMethod.SqlPassword
|| value == SqlAuthenticationMethod.ActiveDirectoryPassword
@@ -629,11 +659,11 @@ internal static string AuthenticationTypeToString(SqlAuthenticationMethod value)
return ActiveDirectoryIntegratedString;
case SqlAuthenticationMethod.ActiveDirectoryInteractive:
return ActiveDirectoryInteractiveString;
-#if ADONET_CERT_AUTH
+#if ADONET_CERT_AUTH
case SqlAuthenticationMethod.SqlCertificate:
return SqlCertificateString;
-#endif
-
+#endif
+
default:
return null;
}
@@ -715,47 +745,58 @@ internal static SqlAuthenticationMethod ConvertToAuthenticationType(string keywo
///
///
///
- internal static SqlConnectionColumnEncryptionSetting ConvertToColumnEncryptionSetting(string keyword, object value) {
- if (null == value) {
+ internal static SqlConnectionColumnEncryptionSetting ConvertToColumnEncryptionSetting(string keyword, object value)
+ {
+ if (null == value)
+ {
return DbConnectionStringDefaults.ColumnEncryptionSetting;
}
string sValue = (value as string);
SqlConnectionColumnEncryptionSetting result;
- if (null != sValue) {
- if (TryConvertToColumnEncryptionSetting(sValue, out result)) {
+ if (null != sValue)
+ {
+ if (TryConvertToColumnEncryptionSetting(sValue, out result))
+ {
return result;
}
// try again after remove leading & trailing whitespaces.
sValue = sValue.Trim();
- if (TryConvertToColumnEncryptionSetting(sValue, out result)) {
+ if (TryConvertToColumnEncryptionSetting(sValue, out result))
+ {
return result;
}
// string values must be valid
throw ADP.InvalidConnectionOptionValue(keyword);
}
- else {
+ else
+ {
// the value is not string, try other options
SqlConnectionColumnEncryptionSetting eValue;
- if (value is SqlConnectionColumnEncryptionSetting) {
+ if (value is SqlConnectionColumnEncryptionSetting)
+ {
// quick path for the most common case
eValue = (SqlConnectionColumnEncryptionSetting)value;
}
- else if (value.GetType().IsEnum) {
+ else if (value.GetType().IsEnum)
+ {
// explicitly block scenarios in which user tries to use wrong enum types, like:
// builder["SqlConnectionColumnEncryptionSetting"] = EnvironmentVariableTarget.Process;
// workaround: explicitly cast non-SqlConnectionColumnEncryptionSetting enums to int
throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionColumnEncryptionSetting), null);
}
- else {
- try {
+ else
+ {
+ try
+ {
// Enum.ToObject allows only integral and enum values (enums are blocked above), rasing ArgumentException for the rest
eValue = (SqlConnectionColumnEncryptionSetting)Enum.ToObject(typeof(SqlConnectionColumnEncryptionSetting), value);
}
- catch (ArgumentException e) {
+ catch (ArgumentException e)
+ {
// to be consistent with the messages we send in case of wrong type usage, replace
// the error with our exception, and keep the original one as inner one for troubleshooting
throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionColumnEncryptionSetting), e);
@@ -763,216 +804,223 @@ internal static SqlConnectionColumnEncryptionSetting ConvertToColumnEncryptionSe
}
// ensure value is in valid range
- if (IsValidColumnEncryptionSetting(eValue)) {
+ if (IsValidColumnEncryptionSetting(eValue))
+ {
return eValue;
}
- else {
+ else
+ {
throw ADP.InvalidEnumerationValue(typeof(SqlConnectionColumnEncryptionSetting), (int)eValue);
}
}
}
- internal static bool IsValidCertificateValue(string value) {
+ internal static bool IsValidCertificateValue(string value)
+ {
return string.IsNullOrEmpty(value)
|| value.StartsWith("subject:", StringComparison.OrdinalIgnoreCase)
|| value.StartsWith("sha1:", StringComparison.OrdinalIgnoreCase);
}
}
- internal static class DbConnectionStringDefaults {
+ internal static class DbConnectionStringDefaults
+ {
// all
-// internal const string NamedConnection = "";
+ // internal const string NamedConnection = "";
// Odbc
- internal const string Driver = "";
- internal const string Dsn = "";
+ internal const string Driver = "";
+ internal const string Dsn = "";
// OleDb
- internal const bool AdoNetPooler = false;
- internal const string FileName = "";
- internal const int OleDbServices = ~(/*DBPROPVAL_OS_AGR_AFTERSESSION*/0x00000008 | /*DBPROPVAL_OS_CLIENTCURSOR*/0x00000004); // -13
- internal const string Provider = "";
+ internal const bool AdoNetPooler = false;
+ internal const string FileName = "";
+ internal const int OleDbServices = ~(/*DBPROPVAL_OS_AGR_AFTERSESSION*/0x00000008 | /*DBPROPVAL_OS_CLIENTCURSOR*/0x00000004); // -13
+ internal const string Provider = "";
// OracleClient
- internal const bool Unicode = false;
- internal const bool OmitOracleConnectionName = false;
+ internal const bool Unicode = false;
+ internal const bool OmitOracleConnectionName = false;
// SqlClient
- internal const ApplicationIntent ApplicationIntent = Microsoft.Data.SqlClient.ApplicationIntent.ReadWrite;
- internal const string ApplicationName = "Framework Microsoft SqlClient Data Provider";
- internal const bool AsynchronousProcessing = false;
- internal const string AttachDBFilename = "";
- internal const int ConnectTimeout = 15;
- internal const bool ConnectionReset = true;
- internal const bool ContextConnection = false;
- internal const string CurrentLanguage = "";
- internal const string DataSource = "";
- internal const bool Encrypt = false;
- internal const bool Enlist = true;
- internal const string FailoverPartner = "";
- internal const string InitialCatalog = "";
- internal const bool IntegratedSecurity = false;
- internal const int LoadBalanceTimeout = 0; // default of 0 means don't use
- internal const bool MultipleActiveResultSets = false;
- internal const bool MultiSubnetFailover = false;
+ internal const ApplicationIntent ApplicationIntent = Microsoft.Data.SqlClient.ApplicationIntent.ReadWrite;
+ internal const string ApplicationName = "Framework Microsoft SqlClient Data Provider";
+ internal const bool AsynchronousProcessing = false;
+ internal const string AttachDBFilename = "";
+ internal const int ConnectTimeout = 15;
+ internal const bool ConnectionReset = true;
+ internal const bool ContextConnection = false;
+ internal const string CurrentLanguage = "";
+ internal const string DataSource = "";
+ internal const bool Encrypt = false;
+ internal const bool Enlist = true;
+ internal const string FailoverPartner = "";
+ internal const string InitialCatalog = "";
+ internal const bool IntegratedSecurity = false;
+ internal const int LoadBalanceTimeout = 0; // default of 0 means don't use
+ internal const bool MultipleActiveResultSets = false;
+ internal const bool MultiSubnetFailover = false;
internal static readonly bool TransparentNetworkIPResolution = LocalAppContextSwitches.DisableTNIRByDefault ? false : true;
- internal const int MaxPoolSize = 100;
- internal const int MinPoolSize = 0;
- internal const string NetworkLibrary = "";
- internal const int PacketSize = 8000;
- internal const string Password = "";
- internal const bool PersistSecurityInfo = false;
- internal const bool Pooling = true;
- internal const bool TrustServerCertificate = false;
- internal const string TypeSystemVersion = "Latest";
- internal const string UserID = "";
- internal const bool UserInstance = false;
- internal const bool Replication = false;
- internal const string WorkstationID = "";
- internal const string TransactionBinding = "Implicit Unbind";
- internal const int ConnectRetryCount = 1;
- internal const int ConnectRetryInterval = 10;
+ internal const int MaxPoolSize = 100;
+ internal const int MinPoolSize = 0;
+ internal const string NetworkLibrary = "";
+ internal const int PacketSize = 8000;
+ internal const string Password = "";
+ internal const bool PersistSecurityInfo = false;
+ internal const bool Pooling = true;
+ internal const bool TrustServerCertificate = false;
+ internal const string TypeSystemVersion = "Latest";
+ internal const string UserID = "";
+ internal const bool UserInstance = false;
+ internal const bool Replication = false;
+ internal const string WorkstationID = "";
+ internal const string TransactionBinding = "Implicit Unbind";
+ internal const int ConnectRetryCount = 1;
+ internal const int ConnectRetryInterval = 10;
internal static readonly SqlAuthenticationMethod Authentication = SqlAuthenticationMethod.NotSpecified;
internal static readonly SqlConnectionColumnEncryptionSetting ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Disabled;
internal const string EnclaveAttestationUrl = "";
- internal const string Certificate = "";
+ internal const string Certificate = "";
internal const PoolBlockingPeriod PoolBlockingPeriod = SqlClient.PoolBlockingPeriod.Auto;
}
- internal static class DbConnectionOptionKeywords {
+ internal static class DbConnectionOptionKeywords
+ {
// Odbc
- internal const string Driver = "driver";
- internal const string Pwd = "pwd";
- internal const string UID = "uid";
+ internal const string Driver = "driver";
+ internal const string Pwd = "pwd";
+ internal const string UID = "uid";
// OleDb
- internal const string DataProvider = "data provider";
- internal const string ExtendedProperties = "extended properties";
- internal const string FileName = "file name";
- internal const string Provider = "provider";
- internal const string RemoteProvider = "remote provider";
+ internal const string DataProvider = "data provider";
+ internal const string ExtendedProperties = "extended properties";
+ internal const string FileName = "file name";
+ internal const string Provider = "provider";
+ internal const string RemoteProvider = "remote provider";
// common keywords (OleDb, OracleClient, SqlClient)
- internal const string Password = "password";
- internal const string UserID = "user id";
+ internal const string Password = "password";
+ internal const string UserID = "user id";
}
- internal static class DbConnectionStringKeywords {
+ internal static class DbConnectionStringKeywords
+ {
// all
-// internal const string NamedConnection = "Named Connection";
+ // internal const string NamedConnection = "Named Connection";
// Odbc
- internal const string Driver = "Driver";
- internal const string Dsn = "Dsn";
- internal const string FileDsn = "FileDsn";
- internal const string SaveFile = "SaveFile";
+ internal const string Driver = "Driver";
+ internal const string Dsn = "Dsn";
+ internal const string FileDsn = "FileDsn";
+ internal const string SaveFile = "SaveFile";
// OleDb
- internal const string FileName = "File Name";
- internal const string OleDbServices = "OLE DB Services";
- internal const string Provider = "Provider";
+ internal const string FileName = "File Name";
+ internal const string OleDbServices = "OLE DB Services";
+ internal const string Provider = "Provider";
// OracleClient
- internal const string Unicode = "Unicode";
- internal const string OmitOracleConnectionName = "Omit Oracle Connection Name";
+ internal const string Unicode = "Unicode";
+ internal const string OmitOracleConnectionName = "Omit Oracle Connection Name";
// SqlClient
- internal const string ApplicationIntent = "ApplicationIntent";
- internal const string ApplicationName = "Application Name";
- internal const string AsynchronousProcessing = "Asynchronous Processing";
- internal const string AttachDBFilename = "AttachDbFilename";
- internal const string ConnectTimeout = "Connect Timeout";
- internal const string ConnectionReset = "Connection Reset";
- internal const string ContextConnection = "Context Connection";
- internal const string CurrentLanguage = "Current Language";
- internal const string Encrypt = "Encrypt";
- internal const string FailoverPartner = "Failover Partner";
- internal const string InitialCatalog = "Initial Catalog";
- internal const string MultipleActiveResultSets = "MultipleActiveResultSets";
- internal const string MultiSubnetFailover = "MultiSubnetFailover";
+ internal const string ApplicationIntent = "ApplicationIntent";
+ internal const string ApplicationName = "Application Name";
+ internal const string AsynchronousProcessing = "Asynchronous Processing";
+ internal const string AttachDBFilename = "AttachDbFilename";
+ internal const string ConnectTimeout = "Connect Timeout";
+ internal const string ConnectionReset = "Connection Reset";
+ internal const string ContextConnection = "Context Connection";
+ internal const string CurrentLanguage = "Current Language";
+ internal const string Encrypt = "Encrypt";
+ internal const string FailoverPartner = "Failover Partner";
+ internal const string InitialCatalog = "Initial Catalog";
+ internal const string MultipleActiveResultSets = "MultipleActiveResultSets";
+ internal const string MultiSubnetFailover = "MultiSubnetFailover";
internal const string TransparentNetworkIPResolution = "TransparentNetworkIPResolution";
- internal const string NetworkLibrary = "Network Library";
- internal const string PacketSize = "Packet Size";
- internal const string Replication = "Replication";
- internal const string TransactionBinding = "Transaction Binding";
- internal const string TrustServerCertificate = "TrustServerCertificate";
- internal const string TypeSystemVersion = "Type System Version";
- internal const string UserInstance = "User Instance";
- internal const string WorkstationID = "Workstation ID";
- internal const string ConnectRetryCount = "ConnectRetryCount";
- internal const string ConnectRetryInterval = "ConnectRetryInterval";
- internal const string Authentication = "Authentication";
- internal const string Certificate = "Certificate";
- internal const string ColumnEncryptionSetting = "Column Encryption Setting";
- internal const string EnclaveAttestationUrl = "Enclave Attestation Url";
- internal const string PoolBlockingPeriod = "PoolBlockingPeriod";
+ internal const string NetworkLibrary = "Network Library";
+ internal const string PacketSize = "Packet Size";
+ internal const string Replication = "Replication";
+ internal const string TransactionBinding = "Transaction Binding";
+ internal const string TrustServerCertificate = "TrustServerCertificate";
+ internal const string TypeSystemVersion = "Type System Version";
+ internal const string UserInstance = "User Instance";
+ internal const string WorkstationID = "Workstation ID";
+ internal const string ConnectRetryCount = "ConnectRetryCount";
+ internal const string ConnectRetryInterval = "ConnectRetryInterval";
+ internal const string Authentication = "Authentication";
+ internal const string Certificate = "Certificate";
+ internal const string ColumnEncryptionSetting = "Column Encryption Setting";
+ internal const string EnclaveAttestationUrl = "Enclave Attestation Url";
+ internal const string PoolBlockingPeriod = "PoolBlockingPeriod";
// common keywords (OleDb, OracleClient, SqlClient)
- internal const string DataSource = "Data Source";
- internal const string IntegratedSecurity = "Integrated Security";
- internal const string Password = "Password";
- internal const string PersistSecurityInfo = "Persist Security Info";
- internal const string UserID = "User ID";
+ internal const string DataSource = "Data Source";
+ internal const string IntegratedSecurity = "Integrated Security";
+ internal const string Password = "Password";
+ internal const string PersistSecurityInfo = "Persist Security Info";
+ internal const string UserID = "User ID";
// managed pooling (OracleClient, SqlClient)
- internal const string Enlist = "Enlist";
- internal const string LoadBalanceTimeout = "Load Balance Timeout";
- internal const string MaxPoolSize = "Max Pool Size";
- internal const string Pooling = "Pooling";
- internal const string MinPoolSize = "Min Pool Size";
+ internal const string Enlist = "Enlist";
+ internal const string LoadBalanceTimeout = "Load Balance Timeout";
+ internal const string MaxPoolSize = "Max Pool Size";
+ internal const string Pooling = "Pooling";
+ internal const string MinPoolSize = "Min Pool Size";
}
- internal static class DbConnectionStringSynonyms {
+ internal static class DbConnectionStringSynonyms
+ {
//internal const string AsynchronousProcessing = Async;
- internal const string Async = "async";
+ internal const string Async = "async";
//internal const string ApplicationName = APP;
- internal const string APP = "app";
+ internal const string APP = "app";
//internal const string AttachDBFilename = EXTENDEDPROPERTIES+","+INITIALFILENAME;
- internal const string EXTENDEDPROPERTIES = "extended properties";
- internal const string INITIALFILENAME = "initial file name";
+ internal const string EXTENDEDPROPERTIES = "extended properties";
+ internal const string INITIALFILENAME = "initial file name";
//internal const string ConnectTimeout = CONNECTIONTIMEOUT+","+TIMEOUT;
- internal const string CONNECTIONTIMEOUT = "connection timeout";
- internal const string TIMEOUT = "timeout";
+ internal const string CONNECTIONTIMEOUT = "connection timeout";
+ internal const string TIMEOUT = "timeout";
//internal const string CurrentLanguage = LANGUAGE;
- internal const string LANGUAGE = "language";
+ internal const string LANGUAGE = "language";
//internal const string OraDataSource = SERVER;
//internal const string SqlDataSource = ADDR+","+ADDRESS+","+SERVER+","+NETWORKADDRESS;
- internal const string ADDR = "addr";
- internal const string ADDRESS = "address";
- internal const string SERVER = "server";
- internal const string NETWORKADDRESS = "network address";
+ internal const string ADDR = "addr";
+ internal const string ADDRESS = "address";
+ internal const string SERVER = "server";
+ internal const string NETWORKADDRESS = "network address";
//internal const string InitialCatalog = DATABASE;
- internal const string DATABASE = "database";
+ internal const string DATABASE = "database";
//internal const string IntegratedSecurity = TRUSTEDCONNECTION;
- internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in everett
+ internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in everett
//internal const string LoadBalanceTimeout = ConnectionLifetime;
- internal const string ConnectionLifetime = "connection lifetime";
+ internal const string ConnectionLifetime = "connection lifetime";
//internal const string NetworkLibrary = NET+","+NETWORK;
- internal const string NET = "net";
- internal const string NETWORK = "network";
+ internal const string NET = "net";
+ internal const string NETWORK = "network";
internal const string WorkaroundOracleBug914652 = "Workaround Oracle Bug 914652";
//internal const string Password = Pwd;
- internal const string Pwd = "pwd";
+ internal const string Pwd = "pwd";
//internal const string PersistSecurityInfo = PERSISTSECURITYINFO;
- internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
+ internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
//internal const string UserID = UID+","+User;
- internal const string UID = "uid";
- internal const string User = "user";
+ internal const string UID = "uid";
+ internal const string User = "user";
//internal const string WorkstationID = WSID;
- internal const string WSID = "wsid";
+ internal const string WSID = "wsid";
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/GreenMethods.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/GreenMethods.cs
index 1626128f7b..276de8d3e8 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/GreenMethods.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/GreenMethods.cs
@@ -6,7 +6,8 @@
using System.Reflection;
using Microsoft.Data.SqlClient;
-namespace Microsoft.Data.Common {
+namespace Microsoft.Data.Common
+{
internal static class GreenMethods {
private const string ExtensionAssemblyRef = "System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKey;
@@ -47,4 +48,4 @@ private static object MicrosoftDataSqlClientSqlProviderServices_Instance_GetValu
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/NameValuePair.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/NameValuePair.cs
index 691a9a18c2..1d5d12f79a 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/NameValuePair.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/NameValuePair.cs
@@ -2,30 +2,34 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.Common {
+namespace Microsoft.Data.Common
+{
using System;
- using Microsoft.Data.Common;
using System.Diagnostics;
using System.Runtime.Serialization;
[Serializable] // MDAC 83147
- sealed internal class NameValuePair {
+ sealed internal class NameValuePair
+ {
readonly private string _name;
readonly private string _value;
- [OptionalField(VersionAdded=2)]
+ [OptionalField(VersionAdded = 2)]
readonly private int _length;
private NameValuePair _next;
- internal NameValuePair(string name, string value, int length) {
+ internal NameValuePair(string name, string value, int length)
+ {
System.Diagnostics.Debug.Assert(!ADP.IsEmpty(name), "empty keyname");
_name = name;
_value = value;
_length = length;
}
- internal int Length {
- get {
+ internal int Length
+ {
+ get
+ {
// this property won't exist when deserialized from Everett to Whidbey
// it shouldn't matter for DbConnectionString/DbDataPermission
// which should only use Length during construction
@@ -34,24 +38,32 @@ internal int Length {
return _length;
}
}
- internal string Name {
- get {
+ internal string Name
+ {
+ get
+ {
return _name;
}
}
- internal NameValuePair Next {
- get {
+ internal NameValuePair Next
+ {
+ get
+ {
return _next;
}
- set {
- if ((null != _next) || (null == value)) {
+ set
+ {
+ if ((null != _next) || (null == value))
+ {
throw ADP.InternalError(ADP.InternalErrorCode.NameValuePairNext);
}
_next = value;
}
}
- internal string Value {
- get {
+ internal string Value
+ {
+ get
+ {
return _value;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/NativeMethods.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/NativeMethods.cs
index e4847d3401..15cff6b235 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/NativeMethods.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/NativeMethods.cs
@@ -6,9 +6,11 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
-namespace Microsoft.Data.Common {
+namespace Microsoft.Data.Common
+{
- internal static class NativeMethods {
+ internal static class NativeMethods
+ {
//[Guid("0c733a1e-2a1c-11ce-ade5-00aa0044773d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport]
//internal interface ISourcesRowset {
@@ -22,8 +24,11 @@ internal static class NativeMethods {
//}
[Guid("0C733A5E-2A1C-11CE-ADE5-00AA0044773D"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown), ComImport]
- internal interface ITransactionJoin {
- [ Obsolete("not used", true)] [PreserveSig] int GetOptionsObject(
+ internal interface ITransactionJoin
+ {
+ [Obsolete("not used", true)]
+ [PreserveSig]
+ int GetOptionsObject(
/*deleted parameter signature*/);
void JoinTransaction(
@@ -32,38 +37,38 @@ void JoinTransaction(
[In] Int32 isoFlags,
[In] IntPtr pOtherOptions);
}
-
- [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Machine)]
static internal extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, IntPtr dwNumberOfBytesToMap);
// OpenFileMappingA contains a security venerability, in the unicode->ansi conversion
// Its possible to spoof the directory and construct ../ sequeences, See FxCop Warrning
// Specify marshaling for pinvoke string arguments
- [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Ansi, BestFitMapping=false, ThrowOnUnmappableChar=true)]
-// [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
+ [DllImport(ExternDll.Kernel32, CharSet = System.Runtime.InteropServices.CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
+ // [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
[ResourceExposure(ResourceScope.Machine)]
static internal extern IntPtr OpenFileMappingA(int dwDesiredAccess, bool bInheritHandle, [MarshalAs(UnmanagedType.LPStr)] string lpName);
// CreateFileMappingA contains a security venerability, in the unicode->ansi conversion
// Its possible to spoof the directory and construct ../ sequeences, See FxCop Warrning
// Specify marshaling for pinvoke string arguments
- [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Ansi, BestFitMapping=false, ThrowOnUnmappableChar=true)]
-// [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
+ [DllImport(ExternDll.Kernel32, CharSet = System.Runtime.InteropServices.CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
+ // [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
[ResourceExposure(ResourceScope.Machine)]
static internal extern IntPtr CreateFileMappingA(IntPtr hFile, IntPtr pAttr, int flProtect, int dwMaximumSizeHigh, int dwMaximumSizeLow, [MarshalAs(UnmanagedType.LPStr)] string lpName);
- [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Machine)]
static internal extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
- [DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.Machine)]
static internal extern bool CloseHandle(IntPtr handle);
- [DllImport(ExternDll.Advapi32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
- static internal extern bool AllocateAndInitializeSid(
+ static internal extern bool AllocateAndInitializeSid(
IntPtr pIdentifierAuthority, // authority
byte nSubAuthorityCount, // count of subauthorities
int dwSubAuthority0, // subauthority 0
@@ -74,43 +79,43 @@ static internal extern bool AllocateAndInitializeSid(
int dwSubAuthority5, // subauthority 5
int dwSubAuthority6, // subauthority 6
int dwSubAuthority7, // subauthority 7
- ref IntPtr pSid ); // SID
+ ref IntPtr pSid); // SID
+
-
- [DllImport(ExternDll.Advapi32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern int GetLengthSid(
IntPtr pSid); // SID to query
- [DllImport(ExternDll.Advapi32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern bool InitializeAcl(
IntPtr pAcl, // ACL
int nAclLength, // size of ACL
- int dwAclRevision ); // revision level of ACL
+ int dwAclRevision); // revision level of ACL
- [DllImport(ExternDll.Advapi32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern bool AddAccessDeniedAce(
IntPtr pAcl, // access control list
int dwAceRevision, // ACL revision level
int AccessMask, // access mask
- IntPtr pSid ); // security identifier
+ IntPtr pSid); // security identifier
- [DllImport(ExternDll.Advapi32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern bool AddAccessAllowedAce(
IntPtr pAcl, // access control list
int dwAceRevision, // ACL revision level
uint AccessMask, // access mask
- IntPtr pSid ); // security identifier
-
- [DllImport(ExternDll.Advapi32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ IntPtr pSid); // security identifier
+
+ [DllImport(ExternDll.Advapi32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern bool InitializeSecurityDescriptor(
IntPtr pSecurityDescriptor, // SD
- int dwRevision ); // revision level
- [DllImport(ExternDll.Advapi32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ int dwRevision); // revision level
+ [DllImport(ExternDll.Advapi32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern bool SetSecurityDescriptorDacl(
IntPtr pSecurityDescriptor, // SD
@@ -118,7 +123,7 @@ static internal extern bool SetSecurityDescriptorDacl(
IntPtr pDacl, // DACL
bool bDaclDefaulted); // default DACL
- [DllImport(ExternDll.Advapi32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern IntPtr FreeSid(
IntPtr pSid); // SID to free
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SQLResource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SQLResource.cs
index 8cba8e509b..7a3b6bf4bc 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SQLResource.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SQLResource.cs
@@ -2,92 +2,75 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//**************************************************************************
-// @File: SQLResource.cs
-//
-// Create by: JunFang
-//
-// Purpose: Implementation of utilities in COM+ SQL Types Library.
-// Includes interface INullable, exceptions SqlNullValueException
-// and SqlTruncateException, and SQLDebug class.
-//
-// Notes:
-//
-// History:
-//
-// 10/22/99 JunFang Created.
-//
-// @EndHeader@
-//**************************************************************************
-
-namespace Microsoft.Data.SqlTypes {
+namespace Microsoft.Data.SqlTypes
+{
using System;
using Microsoft.Data;
- using System.Globalization;
- internal sealed class SQLResource {
-
- private SQLResource() { /* prevent utility class from being insantiated*/ }
-
- internal static readonly String NullString = StringsHelper.GetString(Strings.SqlMisc_NullString);
+ internal sealed class SQLResource
+ {
- internal static readonly String MessageString = StringsHelper.GetString(Strings.SqlMisc_MessageString);
+ private SQLResource() { /* prevent utility class from being insantiated*/ }
- internal static readonly String ArithOverflowMessage = StringsHelper.GetString(Strings.SqlMisc_ArithOverflowMessage);
+ internal static readonly String NullString = StringsHelper.GetString(Strings.SqlMisc_NullString);
- internal static readonly String DivideByZeroMessage = StringsHelper.GetString(Strings.SqlMisc_DivideByZeroMessage);
+ internal static readonly String MessageString = StringsHelper.GetString(Strings.SqlMisc_MessageString);
- internal static readonly String NullValueMessage = StringsHelper.GetString(Strings.SqlMisc_NullValueMessage);
+ internal static readonly String ArithOverflowMessage = StringsHelper.GetString(Strings.SqlMisc_ArithOverflowMessage);
- internal static readonly String TruncationMessage = StringsHelper.GetString(Strings.SqlMisc_TruncationMessage);
+ internal static readonly String DivideByZeroMessage = StringsHelper.GetString(Strings.SqlMisc_DivideByZeroMessage);
- internal static readonly String DateTimeOverflowMessage = StringsHelper.GetString(Strings.SqlMisc_DateTimeOverflowMessage);
+ internal static readonly String NullValueMessage = StringsHelper.GetString(Strings.SqlMisc_NullValueMessage);
- internal static readonly String ConcatDiffCollationMessage = StringsHelper.GetString(Strings.SqlMisc_ConcatDiffCollationMessage);
+ internal static readonly String TruncationMessage = StringsHelper.GetString(Strings.SqlMisc_TruncationMessage);
+
+ internal static readonly String DateTimeOverflowMessage = StringsHelper.GetString(Strings.SqlMisc_DateTimeOverflowMessage);
+
+ internal static readonly String ConcatDiffCollationMessage = StringsHelper.GetString(Strings.SqlMisc_ConcatDiffCollationMessage);
internal static readonly String CompareDiffCollationMessage = StringsHelper.GetString(Strings.SqlMisc_CompareDiffCollationMessage);
- internal static readonly String InvalidFlagMessage = StringsHelper.GetString(Strings.SqlMisc_InvalidFlagMessage);
+ internal static readonly String InvalidFlagMessage = StringsHelper.GetString(Strings.SqlMisc_InvalidFlagMessage);
- internal static readonly String NumeToDecOverflowMessage = StringsHelper.GetString(Strings.SqlMisc_NumeToDecOverflowMessage);
+ internal static readonly String NumeToDecOverflowMessage = StringsHelper.GetString(Strings.SqlMisc_NumeToDecOverflowMessage);
- internal static readonly String ConversionOverflowMessage = StringsHelper.GetString(Strings.SqlMisc_ConversionOverflowMessage);
+ internal static readonly String ConversionOverflowMessage = StringsHelper.GetString(Strings.SqlMisc_ConversionOverflowMessage);
- internal static readonly String InvalidDateTimeMessage = StringsHelper.GetString(Strings.SqlMisc_InvalidDateTimeMessage);
+ internal static readonly String InvalidDateTimeMessage = StringsHelper.GetString(Strings.SqlMisc_InvalidDateTimeMessage);
- internal static readonly String TimeZoneSpecifiedMessage = StringsHelper.GetString(Strings.SqlMisc_TimeZoneSpecifiedMessage);
+ internal static readonly String TimeZoneSpecifiedMessage = StringsHelper.GetString(Strings.SqlMisc_TimeZoneSpecifiedMessage);
- internal static readonly String InvalidArraySizeMessage = StringsHelper.GetString(Strings.SqlMisc_InvalidArraySizeMessage);
+ internal static readonly String InvalidArraySizeMessage = StringsHelper.GetString(Strings.SqlMisc_InvalidArraySizeMessage);
- internal static readonly String InvalidPrecScaleMessage = StringsHelper.GetString(Strings.SqlMisc_InvalidPrecScaleMessage);
+ internal static readonly String InvalidPrecScaleMessage = StringsHelper.GetString(Strings.SqlMisc_InvalidPrecScaleMessage);
- internal static readonly String FormatMessage = StringsHelper.GetString(Strings.SqlMisc_FormatMessage);
+ internal static readonly String FormatMessage = StringsHelper.GetString(Strings.SqlMisc_FormatMessage);
- internal static readonly String NotFilledMessage = StringsHelper.GetString(Strings.SqlMisc_NotFilledMessage);
+ internal static readonly String NotFilledMessage = StringsHelper.GetString(Strings.SqlMisc_NotFilledMessage);
- internal static readonly String AlreadyFilledMessage = StringsHelper.GetString(Strings.SqlMisc_AlreadyFilledMessage);
+ internal static readonly String AlreadyFilledMessage = StringsHelper.GetString(Strings.SqlMisc_AlreadyFilledMessage);
- internal static readonly String ClosedXmlReaderMessage = StringsHelper.GetString(Strings.SqlMisc_ClosedXmlReaderMessage);
+ internal static readonly String ClosedXmlReaderMessage = StringsHelper.GetString(Strings.SqlMisc_ClosedXmlReaderMessage);
internal static String InvalidOpStreamClosed(String method)
{
- return StringsHelper.GetString(Strings.SqlMisc_InvalidOpStreamClosed, method);
+ return StringsHelper.GetString(Strings.SqlMisc_InvalidOpStreamClosed, method);
}
internal static String InvalidOpStreamNonWritable(String method)
{
- return StringsHelper.GetString(Strings.SqlMisc_InvalidOpStreamNonWritable, method);
+ return StringsHelper.GetString(Strings.SqlMisc_InvalidOpStreamNonWritable, method);
}
internal static String InvalidOpStreamNonReadable(String method)
{
- return StringsHelper.GetString(Strings.SqlMisc_InvalidOpStreamNonReadable, method);
+ return StringsHelper.GetString(Strings.SqlMisc_InvalidOpStreamNonReadable, method);
}
internal static String InvalidOpStreamNonSeekable(String method)
{
- return StringsHelper.GetString(Strings.SqlMisc_InvalidOpStreamNonSeekable, method);
+ return StringsHelper.GetString(Strings.SqlMisc_InvalidOpStreamNonSeekable, method);
}
} // SqlResource
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SafeNativeMethods.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SafeNativeMethods.cs
index d6a029f538..558363d47c 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SafeNativeMethods.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/SafeNativeMethods.cs
@@ -3,35 +3,35 @@
// See the LICENSE file in the project root for more information.
using System;
-using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
using System.Security;
-using System.Security.Permissions;
using System.Text;
using System.Threading;
-using System.Runtime.ConstrainedExecution;
-using System.Runtime.Versioning;
-namespace Microsoft.Data.Common {
+namespace Microsoft.Data.Common
+{
[SuppressUnmanagedCodeSecurityAttribute()]
- internal static class SafeNativeMethods {
-
- [DllImport(ExternDll.Ole32, SetLastError=false)]
+ internal static class SafeNativeMethods
+ {
+
+ [DllImport(ExternDll.Ole32, SetLastError = false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern IntPtr CoTaskMemAlloc(IntPtr cb);
- [DllImport(ExternDll.Ole32, SetLastError=false)]
+ [DllImport(ExternDll.Ole32, SetLastError = false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
static internal extern void CoTaskMemFree(IntPtr handle);
- [DllImport(ExternDll.Kernel32, CharSet=CharSet.Unicode, PreserveSig=true)]
+ [DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode, PreserveSig = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern int GetUserDefaultLCID();
- [DllImport(ExternDll.Kernel32, PreserveSig=true)]
+ [DllImport(ExternDll.Kernel32, PreserveSig = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
static internal extern void ZeroMemory(IntPtr dest, IntPtr length);
@@ -50,12 +50,13 @@ static internal unsafe IntPtr InterlockedExchangePointer(
IntPtr lpAddress,
IntPtr lpValue)
{
- IntPtr previousPtr;
- IntPtr actualPtr = *(IntPtr *)lpAddress.ToPointer();
+ IntPtr previousPtr;
+ IntPtr actualPtr = *(IntPtr*)lpAddress.ToPointer();
- do {
+ do
+ {
previousPtr = actualPtr;
- actualPtr = Interlocked.CompareExchange(ref *(IntPtr *)lpAddress.ToPointer(), lpValue, previousPtr);
+ actualPtr = Interlocked.CompareExchange(ref *(IntPtr*)lpAddress.ToPointer(), lpValue, previousPtr);
}
while (actualPtr != previousPtr);
@@ -63,36 +64,36 @@ static internal unsafe IntPtr InterlockedExchangePointer(
}
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/getcomputernameex.asp
- [DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode, EntryPoint="GetComputerNameExW", SetLastError=true)]
+ [DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode, EntryPoint = "GetComputerNameExW", SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
static internal extern int GetComputerNameEx(int nameType, StringBuilder nameBuffer, ref int bufferSize);
- [DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Kernel32, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
static internal extern int GetCurrentProcessId();
- [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto, BestFitMapping=false, ThrowOnUnmappableChar=true)]
-// [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)]
+ [DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
+ // [DllImport(ExternDll.Kernel32, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
static internal extern IntPtr GetModuleHandle([MarshalAs(UnmanagedType.LPTStr), In] string moduleName/*lpctstr*/);
[DllImport(ExternDll.Kernel32, CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)]
-// [DllImport(ExternDll.Kernel32, CharSet=CharSet.Ansi)]
+ // [DllImport(ExternDll.Kernel32, CharSet=CharSet.Ansi)]
[ResourceExposure(ResourceScope.None)]
static internal extern IntPtr GetProcAddress(IntPtr HModule, [MarshalAs(UnmanagedType.LPStr), In] string funcName/*lpcstr*/);
- [DllImport(ExternDll.Kernel32, SetLastError=true)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern IntPtr LocalAlloc(int flags, IntPtr countOfBytes);
- [DllImport(ExternDll.Kernel32, SetLastError=true)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
static internal extern IntPtr LocalFree(IntPtr handle);
- [DllImport(ExternDll.Oleaut32, CharSet=CharSet.Unicode)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
+ [DllImport(ExternDll.Oleaut32, CharSet = CharSet.Unicode)]
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
internal static extern IntPtr SysAllocStringLen(String src, int len); // BSTR
@@ -102,17 +103,17 @@ static internal unsafe IntPtr InterlockedExchangePointer(
internal static extern void SysFreeString(IntPtr bstr);
// only using this to clear existing error info with null
- [DllImport(ExternDll.Oleaut32, CharSet=CharSet.Unicode, PreserveSig=false)]
+ [DllImport(ExternDll.Oleaut32, CharSet = CharSet.Unicode, PreserveSig = false)]
// TLS values are preserved between threads, need to check that we use this API to clear the error state only.
[ResourceExposure(ResourceScope.Process)]
static private extern void SetErrorInfo(Int32 dwReserved, IntPtr pIErrorInfo);
- [DllImport(ExternDll.Kernel32, SetLastError=true)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.Machine)]
static internal extern int ReleaseSemaphore(IntPtr handle, int releaseCount, IntPtr previousCount);
- [DllImport(ExternDll.Kernel32, SetLastError=true)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern int WaitForMultipleObjectsEx(uint nCount, IntPtr lpHandles, bool bWaitAll, uint dwMilliseconds, bool bAlertable);
@@ -122,24 +123,26 @@ static internal unsafe IntPtr InterlockedExchangePointer(
[ResourceExposure(ResourceScope.None)]
static internal extern int WaitForSingleObjectEx(IntPtr lpHandles, uint dwMilliseconds, bool bAlertable);
- [DllImport(ExternDll.Ole32, PreserveSig=false)]
+ [DllImport(ExternDll.Ole32, PreserveSig = false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
static internal extern void PropVariantClear(IntPtr pObject);
- [DllImport(ExternDll.Oleaut32, PreserveSig=false)]
+ [DllImport(ExternDll.Oleaut32, PreserveSig = false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
static internal extern void VariantClear(IntPtr pObject);
- sealed internal class Wrapper {
+ sealed internal class Wrapper
+ {
private Wrapper() { }
// SxS: clearing error information is considered safe
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
- static internal void ClearErrorInfo() { // MDAC 68199
+ static internal void ClearErrorInfo()
+ { // MDAC 68199
SafeNativeMethods.SetErrorInfo(0, ADP.PtrZero);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/System.Data_BID.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/System.Data_BID.cs
index 69aa6737a6..ac7996d1b7 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/System.Data_BID.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/System.Data_BID.cs
@@ -16,19 +16,19 @@
+ "oledb= System.Data.OleDb;"
+ "prov = Microsoft.Data.ProviderBase;"
+ "sc = System.Data.Sql;"
- + "sql = Microsoft.Data.SqlClient;"
- + "cqt = System.Data.Common.CommandTrees;"
- + "cqti = System.Data.Common.CommandTrees.Internal;"
+ + "sql = Microsoft.Data.SqlClient;"
+ + "cqt = System.Data.Common.CommandTrees;"
+ + "cqti = System.Data.Common.CommandTrees.Internal;"
+ "esql = System.Data.Common.EntitySql;"
+ "ec = System.Data.EntityClient;"
+ "dobj = System.Data.Objects;"
+ "md = System.Data.Metadata;"
+ "ra = System.Data.Query.ResultAssembly;"
+ "pc = System.Data.Query.PlanCompiler;"
- + "iqt = System.Data.Query.InternalTrees;"
- + "mp = System.Data.Mapping;"
- + "upd = System.Data.Mapping.Update;"
- + "vgen = System.Data.Mapping.ViewGeneration;"
+ + "iqt = System.Data.Query.InternalTrees;"
+ + "mp = System.Data.Mapping;"
+ + "upd = System.Data.Mapping.Update;"
+ + "vgen = System.Data.Mapping.ViewGeneration;"
)]
//
@@ -66,196 +66,251 @@ internal static partial class Bid
//
[BidMethod]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1) {
- if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1);
+ internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1)
+ {
+ if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1);
}
[BidMethod]
- internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2) {
- if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1,a2);
+ internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2)
+ {
+ if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3) {
- if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1,a2,a3);
+ internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3)
+ {
+ if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3);
}
[BidMethod]
- internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4) {
- if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1,a2,a3,a4);
+ internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4)
+ {
+ if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4);
}
[BidMethod]
internal static void PoolerTrace(
- string fmtPrintfW,
- System.Int32 a1,
- [BidArgumentType(typeof(String))] System.Exception a2) {
- if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1,a2.ToString());
+ string fmtPrintfW,
+ System.Int32 a1,
+ [BidArgumentType(typeof(String))] System.Exception a2)
+ {
+ if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2.ToString());
}
[BidMethod]
- internal static void PoolerScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1) {
- if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1);
- } else {
+ internal static void PoolerScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1)
+ {
+ if ((modFlags & Microsoft.Data.ProviderBase.DbConnectionPool.PoolerTracePoints) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData) {
+ internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ {
NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, fmtPrintfW2);
- } else {
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData) {
+ internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ {
NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1);
- } else {
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData) {
+ internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ {
NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, fmtPrintfW2, fmtPrintfW3);
- } else {
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData) {
+ internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ {
NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, fmtPrintfW2);
- } else {
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData) {
+ internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ {
NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2);
- } else {
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData) {
+ internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ {
NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, fmtPrintfW2, fmtPrintfW3, fmtPrintfW4);
- } else {
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, System.Int32 a2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData) {
+ internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, System.Int32 a2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ {
NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, fmtPrintfW2, a2);
- } else {
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, string fmtPrintfW3, System.Int32 a4) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData) {
+ internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, string fmtPrintfW3, System.Int32 a4)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ {
NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, fmtPrintfW2, fmtPrintfW3, a4);
- } else {
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW);
+ internal static void NotificationsTrace(string fmtPrintfW)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, fmtPrintfW2);
+ internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, fmtPrintfW2);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1);
+ internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, System.Boolean a1) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1);
+ internal static void NotificationsTrace(string fmtPrintfW, System.Boolean a1)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2, System.Int32 a1) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, fmtPrintfW2, a1);
+ internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2, System.Int32 a1)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, fmtPrintfW2, a1);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, string fmtPrintfW2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, fmtPrintfW2);
+ internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, string fmtPrintfW2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, fmtPrintfW2);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
+ internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, System.Boolean a2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
+ internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, System.Boolean a2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, System.String a1, System.String a2) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
+ internal static void NotificationsTrace(string fmtPrintfW, System.String a1, System.String a2)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3, System.Int32 a1) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, fmtPrintfW2, fmtPrintfW3, a1);
+ internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3, System.Int32 a1)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, fmtPrintfW2, fmtPrintfW3, a1);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, System.Boolean a1, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, fmtPrintfW2, fmtPrintfW3, fmtPrintfW4);
+ internal static void NotificationsTrace(string fmtPrintfW, System.Boolean a1, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, fmtPrintfW2, fmtPrintfW3, fmtPrintfW4);
}
[BidMethod]
- internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4) {
- if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, fmtPrintfW2, fmtPrintfW3, fmtPrintfW4);
+ internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4)
+ {
+ if ((modFlags & Microsoft.Data.SqlClient.SqlDependency.NotificationsTracePoints) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, fmtPrintfW2, fmtPrintfW3, fmtPrintfW4);
}
[BidMethod]
[BidArgumentType(typeof(string))] // format string should have a string spec (%ls) for an Activity ID argument as last
- internal static void CorrelationTrace(string fmtPrintfW, System.Int32 a1) {
+ internal static void CorrelationTrace(string fmtPrintfW, System.Int32 a1)
+ {
if ((modFlags & Microsoft.Data.Common.ActivityCorrelator.CorrelationTracePoints) != 0
- && (modFlags & Bid.ApiGroup.Trace) != 0 && modID != NoData) {
+ && (modFlags & Bid.ApiGroup.Trace) != 0 && modID != NoData)
+ {
Microsoft.Data.Common.ActivityCorrelator.ActivityId actId = Microsoft.Data.Common.ActivityCorrelator.Next();
NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, actId.ToString());
}
@@ -266,7 +321,8 @@ internal static void CorrelationTrace(string fmtPrintfW, System.Int32 a1) {
internal static void CorrelationTrace(string fmtPrintfW)
{
if ((modFlags & Microsoft.Data.Common.ActivityCorrelator.CorrelationTracePoints) != 0
- && (modFlags & Bid.ApiGroup.Trace) != 0 && modID != NoData) {
+ && (modFlags & Bid.ApiGroup.Trace) != 0 && modID != NoData)
+ {
Microsoft.Data.Common.ActivityCorrelator.ActivityId actId = Microsoft.Data.Common.ActivityCorrelator.Next();
NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, actId.ToString());
}
@@ -274,9 +330,11 @@ internal static void CorrelationTrace(string fmtPrintfW)
[BidMethod]
[BidArgumentType(typeof(string))] // format string should have a string spec (%ls) for an Activity ID argument as last
- internal static void CorrelationTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2) {
+ internal static void CorrelationTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2)
+ {
if ((modFlags & Microsoft.Data.Common.ActivityCorrelator.CorrelationTracePoints) != 0
- && (modFlags & Bid.ApiGroup.Trace) != 0 && modID != NoData) {
+ && (modFlags & Bid.ApiGroup.Trace) != 0 && modID != NoData)
+ {
Microsoft.Data.Common.ActivityCorrelator.ActivityId actId = Microsoft.Data.Common.ActivityCorrelator.Next();
NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, actId.ToString());
}
@@ -333,204 +391,243 @@ internal static void CorrelationTrace(string fmtPrintfW, System.Int32 a1, System
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.String a1, System.String a2) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2);
+ internal static void Trace(string fmtPrintfW, System.String a1, System.String a2)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1,a2,a3);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4, System.Int32 a5) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1,a2,a3,a4,a5);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4, System.Int32 a5)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4, a5);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.UInt32 a4, System.Int32 a5, System.UInt32 a6, System.UInt32 a7) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1,a2,a3,a4,a5,a6,a7);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.UInt32 a4, System.Int32 a5, System.UInt32 a6, System.UInt32 a7)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4, a5, a6, a7);
}
[BidMethod]
internal static void ScopeEnter(
- out IntPtr hScp,
- string fmtPrintfW,
+ out IntPtr hScp,
+ string fmtPrintfW,
System.Int32 a1,
- [BidArgumentType(typeof(String))] System.Guid a2) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1, a2.ToString());
- } else {
+ [BidArgumentType(typeof(String))] System.Guid a2)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2.ToString());
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2,a3);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2, a3);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2, System.Int32 a3) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2,a3);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2, System.Int32 a3)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2, a3);
+ }
+ else
+ {
hScp = NoData;
}
- }
-
+ }
+
//
// Trace overloads
//
[BidMethod]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal static void Trace(string fmtPrintfW, System.IntPtr a1) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1);
+ internal static void Trace(string fmtPrintfW, System.IntPtr a1)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.IntPtr a2, System.IntPtr a3) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.IntPtr a2, System.IntPtr a3)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.IntPtr a2) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.IntPtr a2)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.Int32 a4) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.Int32 a4)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4, System.String a5, System.Int32 a6) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4,a5,a6);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4, System.String a5, System.Int32 a6)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4, a5, a6);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Boolean a2) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Boolean a2)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4,a5,a6,a7);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4, a5, a6, a7);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3, System.Int32 a4, System.Boolean a5) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4,a5);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3, System.Int32 a4, System.Boolean a5)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4, a5);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int64 a2) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int64 a2)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3 );
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.String a4, System.Int32 a5, System.Int64 a6) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4,a5,a6);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.String a4, System.Int32 a5, System.Int64 a6)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4, a5, a6);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int64 a2, System.Int32 a3, System.Int32 a4) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int64 a2, System.Int32 a3, System.Int32 a4)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.Int32 a4) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.Int32 a4)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.String a5, System.String a6, System.String a7, System.Int32 a8) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4,a5,a6,a7,a8);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.String a5, System.String a6, System.String a7, System.Int32 a8)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4, a5, a6, a7, a8);
}
[BidMethod]
- internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4) {
- if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
- NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1,a2,a3,a4);
+ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4)
+ {
+ if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData)
+ NativeMethods.Trace(modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW, a1, a2, a3, a4);
}
@@ -538,73 +635,105 @@ internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2,
// ScopeEnter overloads
//
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2,a3);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2, a3);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2,a3);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2, a3);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2,a3);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2, a3);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2,a3,a4);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2, a3, a4);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2,a3);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2, a3);
+ }
+ else
+ {
hScp = NoData;
}
}
[BidMethod]
- internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3, System.Int32 a4) {
- if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData) {
- NativeMethods.ScopeEnter (modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW,a1,a2,a3,a4);
- } else {
+ internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3, System.Int32 a4)
+ {
+ if ((modFlags & ApiGroup.Scope) != 0 && modID != NoData)
+ {
+ NativeMethods.ScopeEnter(modID, UIntPtr.Zero, UIntPtr.Zero, out hScp, fmtPrintfW, a1, a2, a3, a4);
+ }
+ else
+ {
hScp = NoData;
}
}
@@ -619,203 +748,250 @@ private static partial class NativeMethods
// Manually edited wrappers
//
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4, System.Int32 a5);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4, System.Int32 a5);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.UInt32 a4, System.Int32 a5, System.UInt32 a6, System.UInt32 a7);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.UInt32 a4, System.Int32 a5, System.UInt32 a6, System.UInt32 a7);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.String a1, System.String a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.String a1, System.String a2);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.String a1, System.String a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.String a1, System.String a2);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2, System.Int32 a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2, System.Int32 a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.String a1, System.String a2, System.String a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.String a1, System.String a2, System.String a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.Int32 a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.Int32 a4);
//
// Trace
//
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.IntPtr a1);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.IntPtr a1);
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Boolean a1);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Boolean a1);
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, string fmtPrintfW2, System.Int32 a1);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, string fmtPrintfW2, System.Int32 a1);
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2);
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")] extern
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.IntPtr a2, System.IntPtr a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.IntPtr a2, System.IntPtr a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.IntPtr a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.IntPtr a2);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.Int32 a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.Int32 a4);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4, System.String a5, System.Int32 a6);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4, System.String a5, System.Int32 a6);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Boolean a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Boolean a2);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.String a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.String a4);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Boolean a1, System.String a2, System.String a3, System.String a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Boolean a1, System.String a2, System.String a3, System.String a4);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3, System.Int32 a4, System.Boolean a5);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3, System.Int32 a4, System.Boolean a5);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int64 a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int64 a2);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW1, string fmtPrintfW2, string fmtPrintfW3, System.Int64 a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW1, string fmtPrintfW2, string fmtPrintfW3, System.Int64 a4);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.String a4, System.Int32 a5, System.Int64 a6);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.String a4, System.Int32 a5, System.Int64 a6);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int64 a2, System.Int32 a3, System.Int32 a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int64 a2, System.Int32 a3, System.Int32 a4);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.Int32 a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.Int32 a4);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.String a5, System.String a6, System.String a7, System.Int32 a8);
-
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.String a5, System.String a6, System.String a7, System.Int32 a8);
+
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern
- internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidTraceCW")]
+ extern
+ internal static void Trace(IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4);
//
// ScopeEnter
//
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")] extern
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, string a1);
-
+
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3);
[ResourceExposure(ResourceScope.None)]
- [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidScopeEnterCW")] extern
- internal static void ScopeEnter (IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3, System.Int32 a4);
+ [DllImport(dllName, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl, EntryPoint = "DllBidScopeEnterCW")]
+ extern
+ internal static void ScopeEnter(IntPtr hID, UIntPtr src, UIntPtr info, out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3, System.Int32 a4);
} // Native
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/UnsafeNativeMethods.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/UnsafeNativeMethods.cs
index a89e6d4778..a742620575 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/UnsafeNativeMethods.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/UnsafeNativeMethods.cs
@@ -3,25 +3,22 @@
// See the LICENSE file in the project root for more information.
using System;
-using System.Data.Odbc;
-using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Security;
-using System.Security.Permissions;
-using System.Text;
-using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
-//using Microsoft.Data.Odbc;
+using System.Security;
-namespace Microsoft.Data.Common {
+namespace Microsoft.Data.Common
+{
[SuppressUnmanagedCodeSecurityAttribute()]
- internal static class UnsafeNativeMethods {
+ internal static class UnsafeNativeMethods
+ {
[Guid("00000567-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity]
- internal interface ADORecordConstruction {
+ internal interface ADORecordConstruction
+ {
- [return:MarshalAs(UnmanagedType.Interface)] object get_Row ();
+ [return: MarshalAs(UnmanagedType.Interface)] object get_Row();
//void put_Row(
// [In, MarshalAs(UnmanagedType.Interface)] object pRow);
@@ -31,13 +28,15 @@ internal interface ADORecordConstruction {
}
[Guid("00000283-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity]
- internal interface ADORecordsetConstruction {
+ internal interface ADORecordsetConstruction
+ {
- [return:MarshalAs(UnmanagedType.Interface)] object get_Rowset();
+ [return: MarshalAs(UnmanagedType.Interface)] object get_Rowset();
- [ Obsolete("not used", true)] void put_Rowset (/*deleted parameters signature*/);
+ [Obsolete("not used", true)] void put_Rowset(/*deleted parameters signature*/);
- /*[return:MarshalAs(UnmanagedType.SysInt)]*/ IntPtr get_Chapter();
+ /*[return:MarshalAs(UnmanagedType.SysInt)]*/
+ IntPtr get_Chapter();
//[[PreserveSig]
//iint put_Chapter (
@@ -57,11 +56,12 @@ internal interface ADORecordsetConstruction {
[Guid("0C733A64-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
- internal interface ICommandWithParameters {
+ internal interface ICommandWithParameters
+ {
- [ Obsolete("not used", true)] void GetParameterInfo(/*deleted parameters signature*/);
+ [Obsolete("not used", true)] void GetParameterInfo(/*deleted parameters signature*/);
- [ Obsolete("not used", true)] void MapParameterNames(/*deleted parameter signature*/);
+ [Obsolete("not used", true)] void MapParameterNames(/*deleted parameter signature*/);
/*[local]
HRESULT SetParameterInfo(
@@ -76,13 +76,15 @@ HRESULT SetParameterInfo(
}
[Guid("2206CCB1-19C1-11D1-89E0-00C04FD7A829"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
- internal interface IDataInitialize {
+ internal interface IDataInitialize
+ {
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal struct Trustee {
+ internal struct Trustee
+ {
internal IntPtr _pMultipleTrustee; // PTRUSTEE
internal int _MultipleTrusteeOperation; // MULTIPLE_TRUSTEE_OPERATION
internal int _TrusteeForm; // TRUSTEE_FORM
@@ -90,46 +92,47 @@ internal struct Trustee {
[MarshalAs(UnmanagedType.LPTStr)]
internal string _name;
- internal Trustee(string name) {
- _pMultipleTrustee = IntPtr.Zero;
+ internal Trustee(string name)
+ {
+ _pMultipleTrustee = IntPtr.Zero;
_MultipleTrusteeOperation = 0; // NO_MULTIPLE_TRUSTEE
- _TrusteeForm = 1; // TRUSTEE_IS_NAME
- _TrusteeType = 1; // TRUSTEE_IS_USER
- _name = name;
+ _TrusteeForm = 1; // TRUSTEE_IS_NAME
+ _TrusteeType = 1; // TRUSTEE_IS_USER
+ _name = name;
}
}
- [DllImport(ExternDll.Advapi32, CharSet=CharSet.Unicode)]
+ [DllImport(ExternDll.Advapi32, CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
- static internal extern uint GetEffectiveRightsFromAclW (byte[] pAcl, ref Trustee pTrustee, out uint pAccessMask);
+ static internal extern uint GetEffectiveRightsFromAclW(byte[] pAcl, ref Trustee pTrustee, out uint pAccessMask);
- [DllImport(ExternDll.Advapi32, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
- [return:MarshalAs(UnmanagedType.Bool)]
- static internal extern bool CheckTokenMembership (IntPtr tokenHandle, byte[] sidToCheck, out bool isMember);
+ [return: MarshalAs(UnmanagedType.Bool)]
+ static internal extern bool CheckTokenMembership(IntPtr tokenHandle, byte[] sidToCheck, out bool isMember);
- [DllImport(ExternDll.Advapi32, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
- [return:MarshalAs(UnmanagedType.Bool)]
+ [return: MarshalAs(UnmanagedType.Bool)]
static internal extern bool ConvertSidToStringSidW(IntPtr sid, out IntPtr stringSid);
- [DllImport(ExternDll.Advapi32, EntryPoint="CreateWellKnownSid", SetLastError=true, CharSet=CharSet.Unicode)]
+ [DllImport(ExternDll.Advapi32, EntryPoint = "CreateWellKnownSid", SetLastError = true, CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern int CreateWellKnownSid(
int sidType,
byte[] domainSid,
[Out] byte[] resultSid,
- ref uint resultSidLength );
+ ref uint resultSidLength);
- [DllImport(ExternDll.Advapi32, SetLastError=true)]
+ [DllImport(ExternDll.Advapi32, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
- [return:MarshalAs(UnmanagedType.Bool)]
+ [return: MarshalAs(UnmanagedType.Bool)]
static internal extern bool GetTokenInformation(IntPtr tokenHandle, uint token_class, IntPtr tokenStruct, uint tokenInformationLength, ref uint tokenString);
- [DllImport(ExternDll.Kernel32, CharSet=CharSet.Unicode)]
+ [DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
internal static extern int lstrlenW(IntPtr ptr);
-
+
/* For debugging purposes...
[DllImport(ExternDll.Advapi32)]
[return:MarshalAs(UnmanagedType.I4)]
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs
index 5aded4b3a1..2340a7c2e2 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs
@@ -7,11 +7,12 @@
using System.Data;
using System.Diagnostics;
using System.Globalization;
-using System.Runtime.Serialization;
-namespace Microsoft.Data {
+namespace Microsoft.Data
+{
- internal static class ExceptionBuilder {
+ internal static class ExceptionBuilder
+ {
// The class defines the exceptions that are specific to the DataSet.
// The class contains functions that take the proper informational variables and then construct
// the appropriate exception with an error string obtained from the resource Data.txt.
@@ -23,16 +24,21 @@ internal static class ExceptionBuilder {
[BidMethod] // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it
static private void TraceException(
- string trace,
- [BidArgumentType(typeof(String))] Exception e) {
+ string trace,
+ [BidArgumentType(typeof(String))] Exception e)
+ {
Debug.Assert(null != e, "TraceException: null Exception");
- if (null != e) {
+ if (null != e)
+ {
Bid.Trace(trace, e.Message);
- if (Bid.AdvancedOn) {
- try {
+ if (Bid.AdvancedOn)
+ {
+ try
+ {
Bid.Trace(", StackTrace='%ls'", Environment.StackTrace);
}
- catch(System.Security.SecurityException) {
+ catch (System.Security.SecurityException)
+ {
// if you don't have permission - you don't get the stack trace
}
}
@@ -40,62 +46,74 @@ static private void TraceException(
}
}
- static internal void TraceExceptionAsReturnValue(Exception e) {
+ static internal void TraceExceptionAsReturnValue(Exception e)
+ {
TraceException(" Message='%ls'", e);
}
- static internal void TraceExceptionForCapture(Exception e) {
+ static internal void TraceExceptionForCapture(Exception e)
+ {
TraceException(" Message='%ls'", e);
}
- static internal void TraceExceptionWithoutRethrow(Exception e) {
+ static internal void TraceExceptionWithoutRethrow(Exception e)
+ {
TraceException(" Message='%ls'", e);
}
//
// COM+ exceptions
//
- static internal ArgumentException _Argument(string error) {
+ static internal ArgumentException _Argument(string error)
+ {
ArgumentException e = new ArgumentException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static internal ArgumentException _Argument(string paramName, string error) {
+ static internal ArgumentException _Argument(string paramName, string error)
+ {
ArgumentException e = new ArgumentException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static internal ArgumentException _Argument(string error, Exception innerException) {
+ static internal ArgumentException _Argument(string error, Exception innerException)
+ {
ArgumentException e = new ArgumentException(error, innerException);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private ArgumentNullException _ArgumentNull(string paramName, string msg) {
+ static private ArgumentNullException _ArgumentNull(string paramName, string msg)
+ {
ArgumentNullException e = new ArgumentNullException(paramName, msg);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static internal ArgumentOutOfRangeException _ArgumentOutOfRange(string paramName, string msg) {
+ static internal ArgumentOutOfRangeException _ArgumentOutOfRange(string paramName, string msg)
+ {
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(paramName, msg);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private IndexOutOfRangeException _IndexOutOfRange(string error) {
+ static private IndexOutOfRangeException _IndexOutOfRange(string error)
+ {
IndexOutOfRangeException e = new IndexOutOfRangeException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private InvalidOperationException _InvalidOperation(string error) {
+ static private InvalidOperationException _InvalidOperation(string error)
+ {
InvalidOperationException e = new InvalidOperationException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private InvalidEnumArgumentException _InvalidEnumArgumentException(string error) {
+ static private InvalidEnumArgumentException _InvalidEnumArgumentException(string error)
+ {
InvalidEnumArgumentException e = new InvalidEnumArgumentException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private InvalidEnumArgumentException _InvalidEnumArgumentException(T value) {
+ static private InvalidEnumArgumentException _InvalidEnumArgumentException(T value)
+ {
string msg = StringsHelper.GetString(Strings.ADP_InvalidEnumerationValue, typeof(T).Name, value.ToString());
return _InvalidEnumArgumentException(msg);
}
@@ -103,7 +121,8 @@ static private InvalidEnumArgumentException _InvalidEnumArgumentException(T v
//
// System.Data exceptions
//
- static private DataException _Data(string error) {
+ static private DataException _Data(string error)
+ {
DataException e = new DataException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
@@ -118,52 +137,62 @@ static private void ThrowDataException(string error, Exception innerException)
ExceptionBuilder.TraceExceptionAsReturnValue(e);
throw e;
}
- static private ConstraintException _Constraint(string error) {
+ static private ConstraintException _Constraint(string error)
+ {
ConstraintException e = new ConstraintException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private InvalidConstraintException _InvalidConstraint(string error) {
+ static private InvalidConstraintException _InvalidConstraint(string error)
+ {
InvalidConstraintException e = new InvalidConstraintException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private DeletedRowInaccessibleException _DeletedRowInaccessible(string error) {
+ static private DeletedRowInaccessibleException _DeletedRowInaccessible(string error)
+ {
DeletedRowInaccessibleException e = new DeletedRowInaccessibleException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private DuplicateNameException _DuplicateName(string error) {
+ static private DuplicateNameException _DuplicateName(string error)
+ {
DuplicateNameException e = new DuplicateNameException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private InRowChangingEventException _InRowChangingEvent(string error) {
+ static private InRowChangingEventException _InRowChangingEvent(string error)
+ {
InRowChangingEventException e = new InRowChangingEventException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private MissingPrimaryKeyException _MissingPrimaryKey(string error) {
+ static private MissingPrimaryKeyException _MissingPrimaryKey(string error)
+ {
MissingPrimaryKeyException e = new MissingPrimaryKeyException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private NoNullAllowedException _NoNullAllowed(string error) {
+ static private NoNullAllowedException _NoNullAllowed(string error)
+ {
NoNullAllowedException e = new NoNullAllowedException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private ReadOnlyException _ReadOnly(string error) {
+ static private ReadOnlyException _ReadOnly(string error)
+ {
ReadOnlyException e = new ReadOnlyException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private RowNotInTableException _RowNotInTable(string error) {
+ static private RowNotInTableException _RowNotInTable(string error)
+ {
RowNotInTableException e = new RowNotInTableException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
}
- static private VersionNotFoundException _VersionNotFound(string error) {
+ static private VersionNotFoundException _VersionNotFound(string error)
+ {
VersionNotFoundException e = new VersionNotFoundException(error);
ExceptionBuilder.TraceExceptionAsReturnValue(e);
return e;
@@ -172,16 +201,20 @@ static private VersionNotFoundException _VersionNotFound(string error) {
// Consider: whether we need to keep our own texts from Data_ArgumentNull and Data_ArgumentOutOfRange?
// Unfortunately ours and the system ones are not consisten between each other. Try to raise this isue in "URT user comunity"
- static public Exception ArgumentNull(string paramName) {
+ static public Exception ArgumentNull(string paramName)
+ {
return _ArgumentNull(paramName, StringsHelper.GetString(Strings.Data_ArgumentNull, paramName));
}
- static public Exception ArgumentOutOfRange(string paramName) {
+ static public Exception ArgumentOutOfRange(string paramName)
+ {
return _ArgumentOutOfRange(paramName, StringsHelper.GetString(Strings.Data_ArgumentOutOfRange, paramName));
}
- static public Exception BadObjectPropertyAccess(string error) {
+ static public Exception BadObjectPropertyAccess(string error)
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataConstraint_BadObjectPropertyAccess, error));
}
- static public Exception ArgumentContainsNull(string paramName) {
+ static public Exception ArgumentContainsNull(string paramName)
+ {
return _Argument(paramName, StringsHelper.GetString(Strings.Data_ArgumentContainsNull, paramName));
}
@@ -190,16 +223,20 @@ static public Exception ArgumentContainsNull(string paramName) {
// Collections
//
- static public Exception CannotModifyCollection() {
+ static public Exception CannotModifyCollection()
+ {
return _Argument(StringsHelper.GetString(Strings.Data_CannotModifyCollection));
}
- static public Exception CaseInsensitiveNameConflict(string name) {
+ static public Exception CaseInsensitiveNameConflict(string name)
+ {
return _Argument(StringsHelper.GetString(Strings.Data_CaseInsensitiveNameConflict, name));
}
- static public Exception NamespaceNameConflict(string name) {
+ static public Exception NamespaceNameConflict(string name)
+ {
return _Argument(StringsHelper.GetString(Strings.Data_NamespaceNameConflict, name));
}
- static public Exception InvalidOffsetLength() {
+ static public Exception InvalidOffsetLength()
+ {
return _Argument(StringsHelper.GetString(Strings.Data_InvalidOffsetLength));
}
@@ -207,74 +244,92 @@ static public Exception InvalidOffsetLength() {
// DataColumnCollection
//
- static public Exception ColumnNotInTheTable(string column, string table) {
+ static public Exception ColumnNotInTheTable(string column, string table)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_NotInTheTable, column, table));
}
- static public Exception ColumnNotInAnyTable() {
+ static public Exception ColumnNotInAnyTable()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_NotInAnyTable));
}
- static public Exception ColumnOutOfRange(int index) {
+ static public Exception ColumnOutOfRange(int index)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataColumns_OutOfRange, (index).ToString(CultureInfo.InvariantCulture)));
}
- static public Exception ColumnOutOfRange(string column) {
+ static public Exception ColumnOutOfRange(string column)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataColumns_OutOfRange, column));
}
- static public Exception CannotAddColumn1(string column) {
+ static public Exception CannotAddColumn1(string column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_Add1, column));
}
- static public Exception CannotAddColumn2(string column) {
+ static public Exception CannotAddColumn2(string column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_Add2, column));
}
- static public Exception CannotAddColumn3() {
+ static public Exception CannotAddColumn3()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_Add3));
}
- static public Exception CannotAddColumn4(string column) {
+ static public Exception CannotAddColumn4(string column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_Add4, column));
}
- static public Exception CannotAddDuplicate(string column) {
+ static public Exception CannotAddDuplicate(string column)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataColumns_AddDuplicate, column));
}
- static public Exception CannotAddDuplicate2(string table) {
+ static public Exception CannotAddDuplicate2(string table)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataColumns_AddDuplicate2, table));
}
- static public Exception CannotAddDuplicate3(string table) {
+ static public Exception CannotAddDuplicate3(string table)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataColumns_AddDuplicate3, table));
}
- static public Exception CannotRemoveColumn() {
+ static public Exception CannotRemoveColumn()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_Remove));
}
- static public Exception CannotRemovePrimaryKey() {
+ static public Exception CannotRemovePrimaryKey()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_RemovePrimaryKey));
}
- static public Exception CannotRemoveChildKey(string relation) {
+ static public Exception CannotRemoveChildKey(string relation)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_RemoveChildKey, relation));
}
- static public Exception CannotRemoveConstraint(string constraint, string table) {
+ static public Exception CannotRemoveConstraint(string constraint, string table)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_RemoveConstraint, constraint, table));
}
- static public Exception CannotRemoveExpression(string column, string expression) {
+ static public Exception CannotRemoveExpression(string column, string expression)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_RemoveExpression, column, expression));
}
- static public Exception ColumnNotInTheUnderlyingTable(string column, string table) {
+ static public Exception ColumnNotInTheUnderlyingTable(string column, string table)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_NotInTheUnderlyingTable, column, table));
}
- static public Exception InvalidOrdinal(string name, int ordinal) {
+ static public Exception InvalidOrdinal(string name, int ordinal)
+ {
return _ArgumentOutOfRange(name, StringsHelper.GetString(Strings.DataColumn_OrdinalExceedMaximun, (ordinal).ToString(CultureInfo.InvariantCulture)));
}
@@ -282,109 +337,137 @@ static public Exception InvalidOrdinal(string name, int ordinal) {
// _Constraint and ConstrainsCollection
//
- static public Exception AddPrimaryKeyConstraint() {
+ static public Exception AddPrimaryKeyConstraint()
+ {
return _Argument(StringsHelper.GetString(Strings.DataConstraint_AddPrimaryKeyConstraint));
}
- static public Exception NoConstraintName() {
+ static public Exception NoConstraintName()
+ {
return _Argument(StringsHelper.GetString(Strings.DataConstraint_NoName));
}
- static public Exception ConstraintViolation(string constraint) {
+ static public Exception ConstraintViolation(string constraint)
+ {
return _Constraint(StringsHelper.GetString(Strings.DataConstraint_Violation, constraint));
}
- static public Exception ConstraintNotInTheTable(string constraint) {
- return _Argument(StringsHelper.GetString(Strings.DataConstraint_NotInTheTable,constraint));
+ static public Exception ConstraintNotInTheTable(string constraint)
+ {
+ return _Argument(StringsHelper.GetString(Strings.DataConstraint_NotInTheTable, constraint));
}
- static public string KeysToString(object[] keys) {
+ static public string KeysToString(object[] keys)
+ {
string values = String.Empty;
- for (int i = 0; i < keys.Length; i++) {
+ for (int i = 0; i < keys.Length; i++)
+ {
values += Convert.ToString(keys[i], null) + (i < keys.Length - 1 ? ", " : String.Empty);
}
return values;
}
- static public string UniqueConstraintViolationText(DataColumn[] columns, object[] values) {
- if (columns.Length > 1) {
+ static public string UniqueConstraintViolationText(DataColumn[] columns, object[] values)
+ {
+ if (columns.Length > 1)
+ {
string columnNames = String.Empty;
- for (int i = 0; i < columns.Length; i++) {
+ for (int i = 0; i < columns.Length; i++)
+ {
columnNames += columns[i].ColumnName + (i < columns.Length - 1 ? ", " : "");
}
return StringsHelper.GetString(Strings.DataConstraint_ViolationValue, columnNames, KeysToString(values));
}
- else {
+ else
+ {
return StringsHelper.GetString(Strings.DataConstraint_ViolationValue, columns[0].ColumnName, Convert.ToString(values[0], null));
}
}
- static public Exception ConstraintViolation(DataColumn[] columns, object[] values) {
+ static public Exception ConstraintViolation(DataColumn[] columns, object[] values)
+ {
return _Constraint(UniqueConstraintViolationText(columns, values));
}
- static public Exception ConstraintOutOfRange(int index) {
+ static public Exception ConstraintOutOfRange(int index)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataConstraint_OutOfRange, (index).ToString(CultureInfo.InvariantCulture)));
}
- static public Exception DuplicateConstraint(string constraint) {
+ static public Exception DuplicateConstraint(string constraint)
+ {
return _Data(StringsHelper.GetString(Strings.DataConstraint_Duplicate, constraint));
}
- static public Exception DuplicateConstraintName(string constraint) {
+ static public Exception DuplicateConstraintName(string constraint)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataConstraint_DuplicateName, constraint));
}
- static public Exception NeededForForeignKeyConstraint(UniqueConstraint key, ForeignKeyConstraint fk) {
+ static public Exception NeededForForeignKeyConstraint(UniqueConstraint key, ForeignKeyConstraint fk)
+ {
return _Argument(StringsHelper.GetString(Strings.DataConstraint_NeededForForeignKeyConstraint, key.ConstraintName, fk.ConstraintName));
}
- static public Exception UniqueConstraintViolation() {
+ static public Exception UniqueConstraintViolation()
+ {
return _Argument(StringsHelper.GetString(Strings.DataConstraint_UniqueViolation));
}
- static public Exception ConstraintForeignTable() {
+ static public Exception ConstraintForeignTable()
+ {
return _Argument(StringsHelper.GetString(Strings.DataConstraint_ForeignTable));
}
- static public Exception ConstraintParentValues() {
+ static public Exception ConstraintParentValues()
+ {
return _Argument(StringsHelper.GetString(Strings.DataConstraint_ParentValues));
}
- static public Exception ConstraintAddFailed(DataTable table) {
+ static public Exception ConstraintAddFailed(DataTable table)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataConstraint_AddFailed, table.TableName));
}
- static public Exception ConstraintRemoveFailed() {
+ static public Exception ConstraintRemoveFailed()
+ {
return _Argument(StringsHelper.GetString(Strings.DataConstraint_RemoveFailed));
}
- static public Exception FailedCascadeDelete(string constraint) {
+ static public Exception FailedCascadeDelete(string constraint)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataConstraint_CascadeDelete, constraint));
}
- static public Exception FailedCascadeUpdate(string constraint) {
+ static public Exception FailedCascadeUpdate(string constraint)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataConstraint_CascadeUpdate, constraint));
}
- static public Exception FailedClearParentTable(string table, string constraint, string childTable) {
+ static public Exception FailedClearParentTable(string table, string constraint, string childTable)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataConstraint_ClearParentTable, table, constraint, childTable));
}
- static public Exception ForeignKeyViolation(string constraint, object[] keys) {
+ static public Exception ForeignKeyViolation(string constraint, object[] keys)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataConstraint_ForeignKeyViolation, constraint, KeysToString(keys)));
}
- static public Exception RemoveParentRow(ForeignKeyConstraint constraint) {
+ static public Exception RemoveParentRow(ForeignKeyConstraint constraint)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataConstraint_RemoveParentRow, constraint.ConstraintName));
}
- static public string MaxLengthViolationText(string columnName) {
+ static public string MaxLengthViolationText(string columnName)
+ {
return StringsHelper.GetString(Strings.DataColumn_ExceedMaxLength, columnName);
}
- static public string NotAllowDBNullViolationText(string columnName) {
+ static public string NotAllowDBNullViolationText(string columnName)
+ {
return StringsHelper.GetString(Strings.DataColumn_NotAllowDBNull, columnName);
}
- static public Exception CantAddConstraintToMultipleNestedTable(string tableName) {
+ static public Exception CantAddConstraintToMultipleNestedTable(string tableName)
+ {
return _Argument(StringsHelper.GetString(Strings.DataConstraint_CantAddConstraintToMultipleNestedTable, tableName));
}
@@ -392,154 +475,195 @@ static public Exception CantAddConstraintToMultipleNestedTable(string tableName)
// DataColumn Set Properties conflicts
//
- static public Exception AutoIncrementAndExpression() {
+ static public Exception AutoIncrementAndExpression()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_AutoIncrementAndExpression));
}
- static public Exception AutoIncrementAndDefaultValue() {
+ static public Exception AutoIncrementAndDefaultValue()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_AutoIncrementAndDefaultValue));
}
- static public Exception AutoIncrementSeed() {
+ static public Exception AutoIncrementSeed()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_AutoIncrementSeed));
}
- static public Exception CantChangeDataType() {
+ static public Exception CantChangeDataType()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_ChangeDataType));
}
- static public Exception NullDataType() {
+ static public Exception NullDataType()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_NullDataType));
}
- static public Exception ColumnNameRequired() {
+ static public Exception ColumnNameRequired()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_NameRequired));
}
- static public Exception DefaultValueAndAutoIncrement() {
+ static public Exception DefaultValueAndAutoIncrement()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_DefaultValueAndAutoIncrement));
}
- static public Exception DefaultValueDataType(string column, Type defaultType, Type columnType, Exception inner) {
- if (column.Length == 0) {
+ static public Exception DefaultValueDataType(string column, Type defaultType, Type columnType, Exception inner)
+ {
+ if (column.Length == 0)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_DefaultValueDataType1, defaultType.FullName, columnType.FullName), inner);
}
- else {
+ else
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_DefaultValueDataType, column, defaultType.FullName, columnType.FullName), inner);
}
}
- static public Exception DefaultValueColumnDataType(string column, Type defaultType, Type columnType, Exception inner) {
+ static public Exception DefaultValueColumnDataType(string column, Type defaultType, Type columnType, Exception inner)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_DefaultValueColumnDataType, column, defaultType.FullName, columnType.FullName), inner);
}
- static public Exception ExpressionAndUnique() {
+ static public Exception ExpressionAndUnique()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_ExpressionAndUnique));
}
- static public Exception ExpressionAndReadOnly() {
+ static public Exception ExpressionAndReadOnly()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_ExpressionAndReadOnly));
}
- static public Exception ExpressionAndConstraint(DataColumn column, Constraint constraint) {
+ static public Exception ExpressionAndConstraint(DataColumn column, Constraint constraint)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_ExpressionAndConstraint, column.ColumnName, constraint.ConstraintName));
}
- static public Exception ExpressionInConstraint(DataColumn column) {
+ static public Exception ExpressionInConstraint(DataColumn column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_ExpressionInConstraint, column.ColumnName));
}
- static public Exception ExpressionCircular() {
+ static public Exception ExpressionCircular()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_ExpressionCircular));
}
- static public Exception NonUniqueValues(string column) {
+ static public Exception NonUniqueValues(string column)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataColumn_NonUniqueValues, column));
}
- static public Exception NullKeyValues(string column) {
+ static public Exception NullKeyValues(string column)
+ {
return _Data(StringsHelper.GetString(Strings.DataColumn_NullKeyValues, column));
}
- static public Exception NullValues(string column) {
+ static public Exception NullValues(string column)
+ {
return _NoNullAllowed(StringsHelper.GetString(Strings.DataColumn_NullValues, column));
}
- static public Exception ReadOnlyAndExpression() {
+ static public Exception ReadOnlyAndExpression()
+ {
return _ReadOnly(StringsHelper.GetString(Strings.DataColumn_ReadOnlyAndExpression));
}
- static public Exception ReadOnly(string column) {
+ static public Exception ReadOnly(string column)
+ {
return _ReadOnly(StringsHelper.GetString(Strings.DataColumn_ReadOnly, column));
}
- static public Exception UniqueAndExpression() {
+ static public Exception UniqueAndExpression()
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_UniqueAndExpression));
}
- static public Exception SetFailed(object value, DataColumn column, Type type, Exception innerException) {
+ static public Exception SetFailed(object value, DataColumn column, Type type, Exception innerException)
+ {
return _Argument(innerException.Message + StringsHelper.GetString(Strings.DataColumn_SetFailed, value.ToString(), column.ColumnName, type.Name), innerException);
}
- static public Exception CannotSetToNull(DataColumn column) {
+ static public Exception CannotSetToNull(DataColumn column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_CannotSetToNull, column.ColumnName));
}
- static public Exception LongerThanMaxLength(DataColumn column) {
+ static public Exception LongerThanMaxLength(DataColumn column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_LongerThanMaxLength, column.ColumnName));
}
- static public Exception CannotSetMaxLength(DataColumn column, int value) {
+ static public Exception CannotSetMaxLength(DataColumn column, int value)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_CannotSetMaxLength, column.ColumnName, value.ToString(CultureInfo.InvariantCulture)));
}
- static public Exception CannotSetMaxLength2(DataColumn column) {
+ static public Exception CannotSetMaxLength2(DataColumn column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_CannotSetMaxLength2, column.ColumnName));
}
- static public Exception CannotSetSimpleContentType(String columnName, Type type) {
+ static public Exception CannotSetSimpleContentType(String columnName, Type type)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_CannotSimpleContentType, columnName, type));
}
- static public Exception CannotSetSimpleContent(String columnName, Type type) {
+ static public Exception CannotSetSimpleContent(String columnName, Type type)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_CannotSimpleContent, columnName, type));
}
- static public Exception CannotChangeNamespace(String columnName) {
+ static public Exception CannotChangeNamespace(String columnName)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_CannotChangeNamespace, columnName));
}
- static public Exception HasToBeStringType(DataColumn column) {
+ static public Exception HasToBeStringType(DataColumn column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_HasToBeStringType, column.ColumnName));
}
- static public Exception AutoIncrementCannotSetIfHasData(string typeName) {
+ static public Exception AutoIncrementCannotSetIfHasData(string typeName)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_AutoIncrementCannotSetIfHasData, typeName));
}
- static public Exception INullableUDTwithoutStaticNull(string typeName) {
+ static public Exception INullableUDTwithoutStaticNull(string typeName)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_INullableUDTwithoutStaticNull, typeName));
}
- static public Exception IComparableNotImplemented(string typeName) {
+ static public Exception IComparableNotImplemented(string typeName)
+ {
return _Data(StringsHelper.GetString(Strings.DataStorage_IComparableNotDefined, typeName));
}
- static public Exception UDTImplementsIChangeTrackingButnotIRevertible(string typeName) {
+ static public Exception UDTImplementsIChangeTrackingButnotIRevertible(string typeName)
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataColumn_UDTImplementsIChangeTrackingButnotIRevertible, typeName));
}
- static public Exception SetAddedAndModifiedCalledOnnonUnchanged() {
+ static public Exception SetAddedAndModifiedCalledOnnonUnchanged()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataColumn_SetAddedAndModifiedCalledOnNonUnchanged));
}
- static public Exception InvalidDataColumnMapping(Type type) {
+ static public Exception InvalidDataColumnMapping(Type type)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumn_InvalidDataColumnMapping, type.AssemblyQualifiedName));
}
- static public Exception CannotSetDateTimeModeForNonDateTimeColumns() {
+ static public Exception CannotSetDateTimeModeForNonDateTimeColumns()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataColumn_CannotSetDateTimeModeForNonDateTimeColumns));
}
- static public Exception InvalidDateTimeMode(DataSetDateTime mode) {
+ static public Exception InvalidDateTimeMode(DataSetDateTime mode)
+ {
return _InvalidEnumArgumentException(mode);
}
- static public Exception CantChangeDateTimeMode(DataSetDateTime oldValue, DataSetDateTime newValue) {
+ static public Exception CantChangeDateTimeMode(DataSetDateTime oldValue, DataSetDateTime newValue)
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataColumn_DateTimeMode, oldValue.ToString(), newValue.ToString()));
}
- static public Exception ColumnTypeNotSupported() {
+ static public Exception ColumnTypeNotSupported()
+ {
return Microsoft.Data.Common.ADP.NotSupported(StringsHelper.GetString(Strings.DataColumn_NullableTypesNotSupported));
}
@@ -547,91 +671,113 @@ static public Exception ColumnTypeNotSupported() {
// DataView
//
- static public Exception SetFailed(string name) {
+ static public Exception SetFailed(string name)
+ {
return _Data(StringsHelper.GetString(Strings.DataView_SetFailed, name));
}
- static public Exception SetDataSetFailed() {
+ static public Exception SetDataSetFailed()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_SetDataSetFailed));
}
- static public Exception SetRowStateFilter() {
+ static public Exception SetRowStateFilter()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_SetRowStateFilter));
}
- static public Exception CanNotSetDataSet() {
+ static public Exception CanNotSetDataSet()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_CanNotSetDataSet));
}
- static public Exception CanNotUseDataViewManager() {
+ static public Exception CanNotUseDataViewManager()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_CanNotUseDataViewManager));
}
- static public Exception CanNotSetTable() {
+ static public Exception CanNotSetTable()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_CanNotSetTable));
}
- static public Exception CanNotUse() {
+ static public Exception CanNotUse()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_CanNotUse));
}
- static public Exception CanNotBindTable() {
+ static public Exception CanNotBindTable()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_CanNotBindTable));
}
- static public Exception SetTable() {
+ static public Exception SetTable()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_SetTable));
}
- static public Exception SetIListObject() {
+ static public Exception SetIListObject()
+ {
return _Argument(StringsHelper.GetString(Strings.DataView_SetIListObject));
}
- static public Exception AddNewNotAllowNull() {
+ static public Exception AddNewNotAllowNull()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_AddNewNotAllowNull));
}
- static public Exception NotOpen() {
+ static public Exception NotOpen()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_NotOpen));
}
- static public Exception CreateChildView() {
+ static public Exception CreateChildView()
+ {
return _Argument(StringsHelper.GetString(Strings.DataView_CreateChildView));
}
- static public Exception CanNotDelete() {
+ static public Exception CanNotDelete()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_CanNotDelete));
}
- static public Exception CanNotEdit() {
+ static public Exception CanNotEdit()
+ {
return _Data(StringsHelper.GetString(Strings.DataView_CanNotEdit));
}
- static public Exception GetElementIndex(Int32 index) {
+ static public Exception GetElementIndex(Int32 index)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataView_GetElementIndex, (index).ToString(CultureInfo.InvariantCulture)));
}
- static public Exception AddExternalObject() {
+ static public Exception AddExternalObject()
+ {
return _Argument(StringsHelper.GetString(Strings.DataView_AddExternalObject));
}
- static public Exception CanNotClear() {
+ static public Exception CanNotClear()
+ {
return _Argument(StringsHelper.GetString(Strings.DataView_CanNotClear));
}
- static public Exception InsertExternalObject() {
+ static public Exception InsertExternalObject()
+ {
return _Argument(StringsHelper.GetString(Strings.DataView_InsertExternalObject));
}
- static public Exception RemoveExternalObject() {
+ static public Exception RemoveExternalObject()
+ {
return _Argument(StringsHelper.GetString(Strings.DataView_RemoveExternalObject));
}
- static public Exception PropertyNotFound(string property, string table) {
+ static public Exception PropertyNotFound(string property, string table)
+ {
return _Argument(StringsHelper.GetString(Strings.DataROWView_PropertyNotFound, property, table));
}
- static public Exception ColumnToSortIsOutOfRange(string column) {
+ static public Exception ColumnToSortIsOutOfRange(string column)
+ {
return _Argument(StringsHelper.GetString(Strings.DataColumns_OutOfRange, column));
}
@@ -639,19 +785,23 @@ static public Exception ColumnToSortIsOutOfRange(string column) {
// Keys
//
- static public Exception KeyTableMismatch() {
+ static public Exception KeyTableMismatch()
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataKey_TableMismatch));
}
- static public Exception KeyNoColumns() {
+ static public Exception KeyNoColumns()
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataKey_NoColumns));
}
- static public Exception KeyTooManyColumns(int cols) {
+ static public Exception KeyTooManyColumns(int cols)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataKey_TooManyColumns, (cols).ToString(CultureInfo.InvariantCulture)));
}
- static public Exception KeyDuplicateColumns(string columnName) {
+ static public Exception KeyDuplicateColumns(string columnName)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataKey_DuplicateColumns, columnName));
}
@@ -659,80 +809,99 @@ static public Exception KeyDuplicateColumns(string columnName) {
// Relations, constraints
//
- static public Exception RelationDataSetMismatch() {
+ static public Exception RelationDataSetMismatch()
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataRelation_DataSetMismatch));
}
- static public Exception NoRelationName() {
+ static public Exception NoRelationName()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_NoName));
}
- static public Exception ColumnsTypeMismatch() {
+ static public Exception ColumnsTypeMismatch()
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataRelation_ColumnsTypeMismatch));
}
- static public Exception KeyLengthMismatch() {
+ static public Exception KeyLengthMismatch()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_KeyLengthMismatch));
}
- static public Exception KeyLengthZero() {
+ static public Exception KeyLengthZero()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_KeyZeroLength));
}
- static public Exception ForeignRelation() {
+ static public Exception ForeignRelation()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_ForeignDataSet));
}
- static public Exception KeyColumnsIdentical() {
+ static public Exception KeyColumnsIdentical()
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataRelation_KeyColumnsIdentical));
}
- static public Exception RelationForeignTable(string t1, string t2) {
+ static public Exception RelationForeignTable(string t1, string t2)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataRelation_ForeignTable, t1, t2));
}
- static public Exception GetParentRowTableMismatch(string t1, string t2) {
+ static public Exception GetParentRowTableMismatch(string t1, string t2)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataRelation_GetParentRowTableMismatch, t1, t2));
}
- static public Exception SetParentRowTableMismatch(string t1, string t2) {
+ static public Exception SetParentRowTableMismatch(string t1, string t2)
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataRelation_SetParentRowTableMismatch, t1, t2));
}
- static public Exception RelationForeignRow() {
+ static public Exception RelationForeignRow()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_ForeignRow));
}
- static public Exception RelationNestedReadOnly() {
+ static public Exception RelationNestedReadOnly()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_RelationNestedReadOnly));
}
- static public Exception TableCantBeNestedInTwoTables(string tableName) {
+ static public Exception TableCantBeNestedInTwoTables(string tableName)
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_TableCantBeNestedInTwoTables, tableName));
}
- static public Exception LoopInNestedRelations(string tableName) {
+ static public Exception LoopInNestedRelations(string tableName)
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_LoopInNestedRelations, tableName));
}
- static public Exception RelationDoesNotExist() {
+ static public Exception RelationDoesNotExist()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_DoesNotExist));
}
- static public Exception ParentRowNotInTheDataSet() {
+ static public Exception ParentRowNotInTheDataSet()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRow_ParentRowNotInTheDataSet));
}
- static public Exception ParentOrChildColumnsDoNotHaveDataSet() {
+ static public Exception ParentOrChildColumnsDoNotHaveDataSet()
+ {
return _InvalidConstraint(StringsHelper.GetString(Strings.DataRelation_ParentOrChildColumnsDoNotHaveDataSet));
}
- static public Exception InValidNestedRelation(string childTableName) {
+ static public Exception InValidNestedRelation(string childTableName)
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataRelation_InValidNestedRelation, childTableName));
}
- static public Exception InvalidParentNamespaceinNestedRelation(string childTableName) {
+ static public Exception InvalidParentNamespaceinNestedRelation(string childTableName)
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataRelation_InValidNamespaceInNestedRelation, childTableName));
}
@@ -740,100 +909,125 @@ static public Exception InvalidParentNamespaceinNestedRelation(string childTable
// Rows
//
- static public Exception RowNotInTheDataSet() {
+ static public Exception RowNotInTheDataSet()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRow_NotInTheDataSet));
}
- static public Exception RowNotInTheTable() {
+ static public Exception RowNotInTheTable()
+ {
return _RowNotInTable(StringsHelper.GetString(Strings.DataRow_NotInTheTable));
}
- static public Exception EditInRowChanging() {
+ static public Exception EditInRowChanging()
+ {
return _InRowChangingEvent(StringsHelper.GetString(Strings.DataRow_EditInRowChanging));
}
- static public Exception EndEditInRowChanging() {
+ static public Exception EndEditInRowChanging()
+ {
return _InRowChangingEvent(StringsHelper.GetString(Strings.DataRow_EndEditInRowChanging));
}
- static public Exception BeginEditInRowChanging() {
+ static public Exception BeginEditInRowChanging()
+ {
return _InRowChangingEvent(StringsHelper.GetString(Strings.DataRow_BeginEditInRowChanging));
}
- static public Exception CancelEditInRowChanging() {
+ static public Exception CancelEditInRowChanging()
+ {
return _InRowChangingEvent(StringsHelper.GetString(Strings.DataRow_CancelEditInRowChanging));
}
- static public Exception DeleteInRowDeleting() {
+ static public Exception DeleteInRowDeleting()
+ {
return _InRowChangingEvent(StringsHelper.GetString(Strings.DataRow_DeleteInRowDeleting));
}
- static public Exception ValueArrayLength() {
+ static public Exception ValueArrayLength()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRow_ValuesArrayLength));
}
- static public Exception NoCurrentData() {
+ static public Exception NoCurrentData()
+ {
return _VersionNotFound(StringsHelper.GetString(Strings.DataRow_NoCurrentData));
}
- static public Exception NoOriginalData() {
+ static public Exception NoOriginalData()
+ {
return _VersionNotFound(StringsHelper.GetString(Strings.DataRow_NoOriginalData));
}
- static public Exception NoProposedData() {
+ static public Exception NoProposedData()
+ {
return _VersionNotFound(StringsHelper.GetString(Strings.DataRow_NoProposedData));
}
- static public Exception RowRemovedFromTheTable() {
+ static public Exception RowRemovedFromTheTable()
+ {
return _RowNotInTable(StringsHelper.GetString(Strings.DataRow_RemovedFromTheTable));
}
- static public Exception DeletedRowInaccessible() {
+ static public Exception DeletedRowInaccessible()
+ {
return _DeletedRowInaccessible(StringsHelper.GetString(Strings.DataRow_DeletedRowInaccessible));
}
- static public Exception RowAlreadyDeleted() {
+ static public Exception RowAlreadyDeleted()
+ {
return _DeletedRowInaccessible(StringsHelper.GetString(Strings.DataRow_AlreadyDeleted));
}
- static public Exception RowEmpty() {
+ static public Exception RowEmpty()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRow_Empty));
}
- static public Exception InvalidRowVersion() {
+ static public Exception InvalidRowVersion()
+ {
return _Data(StringsHelper.GetString(Strings.DataRow_InvalidVersion));
}
- static public Exception RowOutOfRange() {
+ static public Exception RowOutOfRange()
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataRow_RowOutOfRange));
}
- static public Exception RowOutOfRange(int index) {
+ static public Exception RowOutOfRange(int index)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataRow_OutOfRange, (index).ToString(CultureInfo.InvariantCulture)));
}
- static public Exception RowInsertOutOfRange(int index) {
+ static public Exception RowInsertOutOfRange(int index)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataRow_RowInsertOutOfRange, (index).ToString(CultureInfo.InvariantCulture)));
}
- static public Exception RowInsertTwice(int index, string tableName) {
+ static public Exception RowInsertTwice(int index, string tableName)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataRow_RowInsertTwice, (index).ToString(CultureInfo.InvariantCulture), tableName));
}
- static public Exception RowInsertMissing( string tableName) {
+ static public Exception RowInsertMissing(string tableName)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataRow_RowInsertMissing, tableName));
}
- static public Exception RowAlreadyRemoved() {
+ static public Exception RowAlreadyRemoved()
+ {
return _Data(StringsHelper.GetString(Strings.DataRow_AlreadyRemoved));
}
- static public Exception MultipleParents() {
+ static public Exception MultipleParents()
+ {
return _Data(StringsHelper.GetString(Strings.DataRow_MultipleParents));
}
- static public Exception InvalidRowState(DataRowState state) {
+ static public Exception InvalidRowState(DataRowState state)
+ {
return _InvalidEnumArgumentException(state);
}
- static public Exception InvalidRowBitPattern() {
+ static public Exception InvalidRowBitPattern()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRow_InvalidRowBitPattern));
}
@@ -841,105 +1035,138 @@ static public Exception InvalidRowBitPattern() {
// DataSet
//
- static internal Exception SetDataSetNameToEmpty() {
+ static internal Exception SetDataSetNameToEmpty()
+ {
return _Argument(StringsHelper.GetString(Strings.DataSet_SetNameToEmpty));
}
- static internal Exception SetDataSetNameConflicting(string name) {
+ static internal Exception SetDataSetNameConflicting(string name)
+ {
return _Argument(StringsHelper.GetString(Strings.DataSet_SetDataSetNameConflicting, name));
}
- static public Exception DataSetUnsupportedSchema(string ns) {
+ static public Exception DataSetUnsupportedSchema(string ns)
+ {
return _Argument(StringsHelper.GetString(Strings.DataSet_UnsupportedSchema, ns));
}
- static public Exception MergeMissingDefinition(string obj) {
+ static public Exception MergeMissingDefinition(string obj)
+ {
return _Argument(StringsHelper.GetString(Strings.DataMerge_MissingDefinition, obj));
}
- static public Exception TablesInDifferentSets() {
+ static public Exception TablesInDifferentSets()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_TablesInDifferentSets));
}
- static public Exception RelationAlreadyExists() {
+ static public Exception RelationAlreadyExists()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_AlreadyExists));
}
- static public Exception RowAlreadyInOtherCollection() {
+ static public Exception RowAlreadyInOtherCollection()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRow_AlreadyInOtherCollection));
}
- static public Exception RowAlreadyInTheCollection() {
+ static public Exception RowAlreadyInTheCollection()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRow_AlreadyInTheCollection));
}
- static public Exception TableMissingPrimaryKey() {
+ static public Exception TableMissingPrimaryKey()
+ {
return _MissingPrimaryKey(StringsHelper.GetString(Strings.DataTable_MissingPrimaryKey));
}
- static public Exception RecordStateRange() {
+ static public Exception RecordStateRange()
+ {
return _Argument(StringsHelper.GetString(Strings.DataIndex_RecordStateRange));
}
- static public Exception IndexKeyLength(int length, int keyLength) {
- if(length == 0) {
+ static public Exception IndexKeyLength(int length, int keyLength)
+ {
+ if (length == 0)
+ {
return _Argument(StringsHelper.GetString(Strings.DataIndex_FindWithoutSortOrder));
}
- else {
+ else
+ {
return _Argument(StringsHelper.GetString(Strings.DataIndex_KeyLength, (length).ToString(CultureInfo.InvariantCulture), (keyLength).ToString(CultureInfo.InvariantCulture)));
}
}
- static public Exception RemovePrimaryKey(DataTable table) {
- if (table.TableName.Length == 0) {
+ static public Exception RemovePrimaryKey(DataTable table)
+ {
+ if (table.TableName.Length == 0)
+ {
return _Argument(StringsHelper.GetString(Strings.DataKey_RemovePrimaryKey));
}
- else {
+ else
+ {
return _Argument(StringsHelper.GetString(Strings.DataKey_RemovePrimaryKey1, table.TableName));
}
}
- static public Exception RelationAlreadyInOtherDataSet() {
+ static public Exception RelationAlreadyInOtherDataSet()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_AlreadyInOtherDataSet));
}
- static public Exception RelationAlreadyInTheDataSet() {
+ static public Exception RelationAlreadyInTheDataSet()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_AlreadyInTheDataSet));
}
- static public Exception RelationNotInTheDataSet(string relation) {
- return _Argument(StringsHelper.GetString(Strings.DataRelation_NotInTheDataSet,relation));
+ static public Exception RelationNotInTheDataSet(string relation)
+ {
+ return _Argument(StringsHelper.GetString(Strings.DataRelation_NotInTheDataSet, relation));
}
- static public Exception RelationOutOfRange(object index) {
+ static public Exception RelationOutOfRange(object index)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataRelation_OutOfRange, Convert.ToString(index, null)));
}
- static public Exception DuplicateRelation(string relation) {
+ static public Exception DuplicateRelation(string relation)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataRelation_DuplicateName, relation));
}
- static public Exception RelationTableNull() {
+ static public Exception RelationTableNull()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_TableNull));
}
- static public Exception RelationDataSetNull() {
+ static public Exception RelationDataSetNull()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_TableNull));
}
- static public Exception RelationTableWasRemoved() {
+ static public Exception RelationTableWasRemoved()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_TableWasRemoved));
}
- static public Exception ParentTableMismatch() {
+ static public Exception ParentTableMismatch()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_ParentTableMismatch));
}
- static public Exception ChildTableMismatch() {
+ static public Exception ChildTableMismatch()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_ChildTableMismatch));
}
- static public Exception EnforceConstraint() {
+ static public Exception EnforceConstraint()
+ {
return _Constraint(StringsHelper.GetString(Strings.Data_EnforceConstraints));
}
- static public Exception CaseLocaleMismatch() {
+ static public Exception CaseLocaleMismatch()
+ {
return _Argument(StringsHelper.GetString(Strings.DataRelation_CaseLocaleMismatch));
}
- static public Exception CannotChangeCaseLocale() {
+ static public Exception CannotChangeCaseLocale()
+ {
return CannotChangeCaseLocale(null);
}
- static public Exception CannotChangeCaseLocale(Exception innerException) {
+ static public Exception CannotChangeCaseLocale(Exception innerException)
+ {
return _Argument(StringsHelper.GetString(Strings.DataSet_CannotChangeCaseLocale), innerException);
}
- static public Exception CannotChangeSchemaSerializationMode() {
+ static public Exception CannotChangeSchemaSerializationMode()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataSet_CannotChangeSchemaSerializationMode));
}
- static public Exception InvalidSchemaSerializationMode(Type enumType, string mode) {
+ static public Exception InvalidSchemaSerializationMode(Type enumType, string mode)
+ {
return _InvalidEnumArgumentException(StringsHelper.GetString(Strings.ADP_InvalidEnumerationValue, enumType.Name, mode));
}
- static public Exception InvalidRemotingFormat(SerializationFormat mode) {
+ static public Exception InvalidRemotingFormat(SerializationFormat mode)
+ {
#if DEBUG
switch(mode) {
case SerializationFormat.Xml:
@@ -954,92 +1181,118 @@ static public Exception InvalidRemotingFormat(SerializationFormat mode) {
//
// DataTable and DataTableCollection
//
- static public Exception TableForeignPrimaryKey() {
+ static public Exception TableForeignPrimaryKey()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_ForeignPrimaryKey));
}
- static public Exception TableCannotAddToSimpleContent() {
+ static public Exception TableCannotAddToSimpleContent()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_CannotAddToSimpleContent));
}
- static public Exception NoTableName() {
+ static public Exception NoTableName()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_NoName));
}
- static public Exception MultipleTextOnlyColumns() {
+ static public Exception MultipleTextOnlyColumns()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_MultipleSimpleContentColumns));
}
- static public Exception InvalidSortString(string sort) {
+ static public Exception InvalidSortString(string sort)
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_InvalidSortString, sort));
}
- static public Exception DuplicateTableName(string table) {
+ static public Exception DuplicateTableName(string table)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataTable_DuplicateName, table));
}
- static public Exception DuplicateTableName2(string table, string ns) {
+ static public Exception DuplicateTableName2(string table, string ns)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataTable_DuplicateName2, table, ns));
}
- static public Exception SelfnestedDatasetConflictingName(string table) {
+ static public Exception SelfnestedDatasetConflictingName(string table)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataTable_SelfnestedDatasetConflictingName, table));
}
- static public Exception DatasetConflictingName(string table) {
+ static public Exception DatasetConflictingName(string table)
+ {
return _DuplicateName(StringsHelper.GetString(Strings.DataTable_DatasetConflictingName, table));
}
- static public Exception TableAlreadyInOtherDataSet() {
+ static public Exception TableAlreadyInOtherDataSet()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_AlreadyInOtherDataSet));
}
- static public Exception TableAlreadyInTheDataSet() {
+ static public Exception TableAlreadyInTheDataSet()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_AlreadyInTheDataSet));
}
- static public Exception TableOutOfRange(int index) {
+ static public Exception TableOutOfRange(int index)
+ {
return _IndexOutOfRange(StringsHelper.GetString(Strings.DataTable_OutOfRange, (index).ToString(CultureInfo.InvariantCulture)));
}
- static public Exception TableNotInTheDataSet(string table) {
+ static public Exception TableNotInTheDataSet(string table)
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_NotInTheDataSet, table));
}
- static public Exception TableInRelation() {
+ static public Exception TableInRelation()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_InRelation));
}
- static public Exception TableInConstraint(DataTable table, Constraint constraint) {
+ static public Exception TableInConstraint(DataTable table, Constraint constraint)
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_InConstraint, table.TableName, constraint.ConstraintName));
}
- static public Exception CanNotSerializeDataTableHierarchy() {
+ static public Exception CanNotSerializeDataTableHierarchy()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataTable_CanNotSerializeDataTableHierarchy));
}
- static public Exception CanNotRemoteDataTable() {
+ static public Exception CanNotRemoteDataTable()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataTable_CanNotRemoteDataTable));
}
- static public Exception CanNotSetRemotingFormat() {
+ static public Exception CanNotSetRemotingFormat()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_CanNotSetRemotingFormat));
}
- static public Exception CanNotSerializeDataTableWithEmptyName() {
+ static public Exception CanNotSerializeDataTableWithEmptyName()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataTable_CanNotSerializeDataTableWithEmptyName));
}
- static public Exception TableNotFound (string tableName) {
+ static public Exception TableNotFound(string tableName)
+ {
return _Argument(StringsHelper.GetString(Strings.DataTable_TableNotFound, tableName));
}
- static public Exception InvalidStorageType(TypeCode typecode) {
- return _Data(StringsHelper.GetString(Strings.DataStorage_InvalidStorageType, ((Enum) typecode).ToString()));
+ static public Exception InvalidStorageType(TypeCode typecode)
+ {
+ return _Data(StringsHelper.GetString(Strings.DataStorage_InvalidStorageType, ((Enum)typecode).ToString()));
}
- static public Exception RangeArgument(Int32 min, Int32 max) {
+ static public Exception RangeArgument(Int32 min, Int32 max)
+ {
return _Argument(StringsHelper.GetString(Strings.Range_Argument, (min).ToString(CultureInfo.InvariantCulture), (max).ToString(CultureInfo.InvariantCulture)));
}
- static public Exception NullRange() {
+ static public Exception NullRange()
+ {
return _Data(StringsHelper.GetString(Strings.Range_NullRange));
}
- static public Exception NegativeMinimumCapacity() {
+ static public Exception NegativeMinimumCapacity()
+ {
return _Argument(StringsHelper.GetString(Strings.RecordManager_MinimumCapacity));
}
- static public Exception ProblematicChars(char charValue) {
+ static public Exception ProblematicChars(char charValue)
+ {
string xchar = "0x" + ((UInt16)charValue).ToString("X", CultureInfo.InvariantCulture);
return _Argument(StringsHelper.GetString(Strings.DataStorage_ProblematicChars, xchar));
}
- static public Exception StorageSetFailed() {
+ static public Exception StorageSetFailed()
+ {
return _Argument(StringsHelper.GetString(Strings.DataStorage_SetInvalidDataType));
}
@@ -1047,128 +1300,159 @@ static public Exception StorageSetFailed() {
//
// XML schema
//
- static public Exception SimpleTypeNotSupported() {
+ static public Exception SimpleTypeNotSupported()
+ {
return _Data(StringsHelper.GetString(Strings.Xml_SimpleTypeNotSupported));
}
- static public Exception MissingAttribute(string attribute) {
+ static public Exception MissingAttribute(string attribute)
+ {
return MissingAttribute(String.Empty, attribute);
}
- static public Exception MissingAttribute(string element, string attribute) {
+ static public Exception MissingAttribute(string element, string attribute)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_MissingAttribute, element, attribute));
}
- static public Exception InvalidAttributeValue(string name, string value) {
+ static public Exception InvalidAttributeValue(string name, string value)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_ValueOutOfRange, name, value));
}
- static public Exception AttributeValues(string name, string value1, string value2) {
+ static public Exception AttributeValues(string name, string value1, string value2)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_AttributeValues, name, value1, value2));
}
- static public Exception ElementTypeNotFound(string name) {
+ static public Exception ElementTypeNotFound(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_ElementTypeNotFound, name));
}
- static public Exception RelationParentNameMissing(string rel) {
+ static public Exception RelationParentNameMissing(string rel)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_RelationParentNameMissing, rel));
}
- static public Exception RelationChildNameMissing(string rel) {
+ static public Exception RelationChildNameMissing(string rel)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_RelationChildNameMissing, rel));
}
- static public Exception RelationTableKeyMissing(string rel) {
+ static public Exception RelationTableKeyMissing(string rel)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_RelationTableKeyMissing, rel));
}
- static public Exception RelationChildKeyMissing(string rel) {
+ static public Exception RelationChildKeyMissing(string rel)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_RelationChildKeyMissing, rel));
}
- static public Exception UndefinedDatatype(string name) {
+ static public Exception UndefinedDatatype(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_UndefinedDatatype, name));
}
- static public Exception DatatypeNotDefined() {
+ static public Exception DatatypeNotDefined()
+ {
return _Data(StringsHelper.GetString(Strings.Xml_DatatypeNotDefined));
}
- static public Exception MismatchKeyLength() {
+ static public Exception MismatchKeyLength()
+ {
return _Data(StringsHelper.GetString(Strings.Xml_MismatchKeyLength));
}
- static public Exception InvalidField(string name) {
+ static public Exception InvalidField(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_InvalidField, name));
}
- static public Exception InvalidSelector(string name) {
+ static public Exception InvalidSelector(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_InvalidSelector, name));
}
- static public Exception CircularComplexType(string name) {
+ static public Exception CircularComplexType(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_CircularComplexType, name));
}
- static public Exception CannotInstantiateAbstract(string name) {
+ static public Exception CannotInstantiateAbstract(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_CannotInstantiateAbstract, name));
}
- static public Exception InvalidKey(string name) {
+ static public Exception InvalidKey(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_InvalidKey, name));
}
- static public Exception DiffgramMissingTable(string name) {
+ static public Exception DiffgramMissingTable(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_MissingTable, name));
}
- static public Exception DiffgramMissingSQL() {
+ static public Exception DiffgramMissingSQL()
+ {
return _Data(StringsHelper.GetString(Strings.Xml_MissingSQL));
}
- static public Exception DuplicateConstraintRead(string str) {
+ static public Exception DuplicateConstraintRead(string str)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_DuplicateConstraint, str));
}
- static public Exception ColumnTypeConflict(string name) {
+ static public Exception ColumnTypeConflict(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_ColumnConflict, name));
}
- static public Exception CannotConvert(string name, string type) {
+ static public Exception CannotConvert(string name, string type)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_CannotConvert, name, type));
}
- static public Exception InvalidPrefix(string name) {
+ static public Exception InvalidPrefix(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_InvalidPrefix, name));
}
- static public Exception CanNotDeserializeObjectType() {
+ static public Exception CanNotDeserializeObjectType()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.Xml_CanNotDeserializeObjectType));
}
- static public Exception IsDataSetAttributeMissingInSchema() {
+ static public Exception IsDataSetAttributeMissingInSchema()
+ {
return _Data(StringsHelper.GetString(Strings.Xml_IsDataSetAttributeMissingInSchema));
}
- static public Exception TooManyIsDataSetAtributeInSchema() {
+ static public Exception TooManyIsDataSetAtributeInSchema()
+ {
return _Data(StringsHelper.GetString(Strings.Xml_TooManyIsDataSetAtributeInSchema));
}
// XML save
- static public Exception NestedCircular(string name) {
+ static public Exception NestedCircular(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_NestedCircular, name));
}
- static public Exception MultipleParentRows(string tableQName) {
+ static public Exception MultipleParentRows(string tableQName)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_MultipleParentRows, tableQName));
}
- static public Exception PolymorphismNotSupported(string typeName) {
+ static public Exception PolymorphismNotSupported(string typeName)
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.Xml_PolymorphismNotSupported, typeName));
}
- static public Exception DataTableInferenceNotSupported() {
+ static public Exception DataTableInferenceNotSupported()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.Xml_DataTableInferenceNotSupported));
}
@@ -1184,62 +1468,75 @@ static internal void ThrowMultipleTargetConverter(Exception innerException)
//
// Merge
//
- static public Exception DuplicateDeclaration(string name) {
+ static public Exception DuplicateDeclaration(string name)
+ {
return _Data(StringsHelper.GetString(Strings.Xml_MergeDuplicateDeclaration, name));
}
//Read Xml data
- static public Exception FoundEntity() {
+ static public Exception FoundEntity()
+ {
return _Data(StringsHelper.GetString(Strings.Xml_FoundEntity));
}
// ATTENTION: name has to be localized string here:
- static public Exception MergeFailed(string name) {
+ static public Exception MergeFailed(string name)
+ {
return _Data(name);
}
// SqlConvert
- static public DataException ConvertFailed(Type type1, Type type2) {
+ static public DataException ConvertFailed(Type type1, Type type2)
+ {
return _Data(StringsHelper.GetString(Strings.SqlConvert_ConvertFailed, type1.FullName, type2.FullName));
}
// DataTableReader
- static public Exception InvalidDataTableReader(string tableName) {
+ static public Exception InvalidDataTableReader(string tableName)
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataTableReader_InvalidDataTableReader, tableName));
}
- static public Exception DataTableReaderSchemaIsInvalid(string tableName) {
+ static public Exception DataTableReaderSchemaIsInvalid(string tableName)
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.DataTableReader_SchemaInvalidDataTableReader, tableName));
}
- static public Exception CannotCreateDataReaderOnEmptyDataSet() {
+ static public Exception CannotCreateDataReaderOnEmptyDataSet()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTableReader_CannotCreateDataReaderOnEmptyDataSet));
}
- static public Exception DataTableReaderArgumentIsEmpty() {
+ static public Exception DataTableReaderArgumentIsEmpty()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTableReader_DataTableReaderArgumentIsEmpty));
}
- static public Exception ArgumentContainsNullValue() {
+ static public Exception ArgumentContainsNullValue()
+ {
return _Argument(StringsHelper.GetString(Strings.DataTableReader_ArgumentContainsNullValue));
}
- static public Exception InvalidCurrentRowInDataTableReader() {
+ static public Exception InvalidCurrentRowInDataTableReader()
+ {
return _DeletedRowInaccessible(StringsHelper.GetString(Strings.DataTableReader_InvalidRowInDataTableReader));
}
- static public Exception EmptyDataTableReader(string tableName) {
+ static public Exception EmptyDataTableReader(string tableName)
+ {
return _DeletedRowInaccessible(StringsHelper.GetString(Strings.DataTableReader_DataTableCleared, tableName));
}
//
- static internal Exception InvalidDuplicateNamedSimpleTypeDelaration(string stName, string errorStr) {
+ static internal Exception InvalidDuplicateNamedSimpleTypeDelaration(string stName, string errorStr)
+ {
return _Argument(StringsHelper.GetString(Strings.NamedSimpleType_InvalidDuplicateNamedSimpleTypeDelaration, stName, errorStr));
}
- static public Exception EnumeratorModified() {
+ static public Exception EnumeratorModified()
+ {
return _InvalidOperation(StringsHelper.GetString(Strings.RbTree_EnumerationBroken));
}
}// ExceptionBuilder
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs
index 5656a1207e..e2d947cab9 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs
@@ -2,8 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Data.Common;
-using Microsoft.Data.SqlClient;
using System;
using System.Diagnostics;
using System.IO;
@@ -13,6 +11,8 @@
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
+using Microsoft.Data.Common;
+using Microsoft.Data.SqlClient;
namespace Microsoft.Data.SqlClient
{
@@ -136,7 +136,8 @@ internal static bool NativeSetData(void* passedData, int passedSize)
{
bool success = false;
- while (0 != Interlocked.CompareExchange(ref thelock, 1, 0)) { // Spin until we have the lock.
+ while (0 != Interlocked.CompareExchange(ref thelock, 1, 0))
+ { // Spin until we have the lock.
Thread.Sleep(50); // Sleep with short-timeout to prevent starvation.
}
Trace.Assert(1 == thelock); // Now that we have the lock, lock should be equal to 1.
@@ -501,54 +502,54 @@ private static extern unsafe uint SNISecGenClientContextWrapper(
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket);
-
+
[DllImport(SNI, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr SNIClientCertificateFallbackWrapper(IntPtr pCallbackContext);
#endregion
internal static uint SNISecGetServerCertificate(SNIHandle pConnectionObject, ref X509Certificate2 certificate)
{
- System.UInt32 ret;
- CredHandle pSecHandle;
- X509Certificate pCertContext = null;
+ System.UInt32 ret;
+ CredHandle pSecHandle;
+ X509Certificate pCertContext = null;
- // provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions
- bool mustRelease = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- pConnectionObject.DangerousAddRef(ref mustRelease);
- Debug.Assert(mustRelease, "AddRef Failed!");
+ // provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions
+ bool mustRelease = false;
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ pConnectionObject.DangerousAddRef(ref mustRelease);
+ Debug.Assert(mustRelease, "AddRef Failed!");
- IntPtr secHandlePtr = Marshal.AllocHGlobal(Marshal.SizeOf());
+ IntPtr secHandlePtr = Marshal.AllocHGlobal(Marshal.SizeOf());
- ret = SNIGetInfoWrapper(pConnectionObject, QTypes.SNI_QUERY_CONN_SSL_SECCTXTHANDLE, ref secHandlePtr);
- //ERROR_SUCCESS
- if (0 == ret)
- {
+ ret = SNIGetInfoWrapper(pConnectionObject, QTypes.SNI_QUERY_CONN_SSL_SECCTXTHANDLE, ref secHandlePtr);
+ //ERROR_SUCCESS
+ if (0 == ret)
+ {
// Cast an unmanaged block to pSecHandle;
pSecHandle = Marshal.PtrToStructure(secHandlePtr);
// SEC_E_OK
if (0 == (ret = QueryContextAttributes(ref pSecHandle, ContextAttribute.SECPKG_ATTR_REMOTE_CERT_CONTEXT, pCertContext.Handle)))
{
- certificate = new X509Certificate2(pCertContext.Handle);
- }
- }
- Marshal.FreeHGlobal(secHandlePtr);
- }
- finally
- {
- if (pCertContext != null)
- {
- pCertContext.Dispose();
- }
- if (mustRelease)
- {
- pConnectionObject.DangerousRelease();
- }
- }
- return ret;
+ certificate = new X509Certificate2(pCertContext.Handle);
+ }
+ }
+ Marshal.FreeHGlobal(secHandlePtr);
+ }
+ finally
+ {
+ if (pCertContext != null)
+ {
+ pCertContext.Dispose();
+ }
+ if (mustRelease)
+ {
+ pConnectionObject.DangerousRelease();
+ }
+ }
+ return ret;
}
internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId)
@@ -624,7 +625,7 @@ internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string cons
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
- internal static uint SNIAddProvider(SNIHandle pConn,
+ internal static uint SNIAddProvider(SNIHandle pConn,
ProviderEnum providerEnum,
AuthProviderInfo authInfo)
{
@@ -667,9 +668,9 @@ internal static uint SNIAddProvider(SNIHandle pConn,
SNICTAIPProviderInfo ctaipInfo = new SNICTAIPProviderInfo();
ctaipInfo.prgbAddress = authInfo.originalNetworkAddress[0];
- ctaipInfo.cbAddress = (byte) authInfo.originalNetworkAddress.Length;
+ ctaipInfo.cbAddress = (byte)authInfo.originalNetworkAddress.Length;
ctaipInfo.fFromDataSecurityProxy = authInfo.fromDataSecurityProxy;
-
+
ret = SNIAddProviderWrapper(pConn, providerEnum, ref ctaipInfo);
if (ret == ERROR_SUCCESS)
@@ -712,7 +713,7 @@ internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int
// to loose encryption algorithm is changed it should be done in both in this method as well as TdsParserStaticMethods.EncryptPassword.
// Up to current release, it is also guaranteed that both password and new change password will fit into a single login packet whose size is fixed to 4096
// So, there is no splitting logic is needed.
- internal static void SNIPacketSetData (SNIPacket packet,
+ internal static void SNIPacketSetData(SNIPacket packet,
Byte[] data,
Int32 length,
SecureString[] passwords, // pointer to the passwords which need to be written out to SNI Packet
@@ -727,12 +728,13 @@ Int32[] passwordOffsets // Offset into data buffer where the password to be w
// provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions
RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
+ try
+ {
unsafe
{
- fixed (byte* pin_data = &data[0]) { }
+ fixed (byte* pin_data = &data[0])
+ { }
if (passwords != null)
{
// Process SecureString
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/OperationAbortedException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/OperationAbortedException.cs
index ed0005fff6..5c5e0fc3bc 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/OperationAbortedException.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/OperationAbortedException.cs
@@ -2,30 +2,34 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data {
+namespace Microsoft.Data
+{
using System;
- using Microsoft.Data;
- using Microsoft.Data.Common;
- using System.Diagnostics;
- using System.Globalization;
using System.Runtime.Serialization;
+ using Microsoft.Data.Common;
[Serializable]
- public sealed class OperationAbortedException : SystemException {
- private OperationAbortedException(string message, Exception innerException) : base(message, innerException) {
+ public sealed class OperationAbortedException : SystemException
+ {
+ private OperationAbortedException(string message, Exception innerException) : base(message, innerException)
+ {
HResult = HResults.OperationAborted;
}
- private OperationAbortedException(SerializationInfo si, StreamingContext sc) : base(si, sc) {
+ private OperationAbortedException(SerializationInfo si, StreamingContext sc) : base(si, sc)
+ {
}
- static internal OperationAbortedException Aborted(Exception inner) {
+ static internal OperationAbortedException Aborted(Exception inner)
+ {
OperationAbortedException e;
- if (inner == null) {
+ if (inner == null)
+ {
e = new OperationAbortedException(StringsHelper.GetString(Strings.ADP_OperationAborted), null);
}
- else {
+ else
+ {
e = new OperationAbortedException(StringsHelper.GetString(Strings.ADP_OperationAbortedExceptionMessage), inner);
}
ADP.TraceExceptionAsReturnValue(e);
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DataReaderContainer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DataReaderContainer.cs
index 9474f47a84..7ad9077248 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DataReaderContainer.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DataReaderContainer.cs
@@ -2,35 +2,43 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
- internal abstract class DataReaderContainer {
+ internal abstract class DataReaderContainer
+ {
protected readonly IDataReader _dataReader;
protected int _fieldCount;
- static internal DataReaderContainer Create(IDataReader dataReader, bool returnProviderSpecificTypes) {
- if (returnProviderSpecificTypes) {
+ static internal DataReaderContainer Create(IDataReader dataReader, bool returnProviderSpecificTypes)
+ {
+ if (returnProviderSpecificTypes)
+ {
DbDataReader providerSpecificDataReader = (dataReader as DbDataReader);
- if (null != providerSpecificDataReader) {
+ if (null != providerSpecificDataReader)
+ {
return new ProviderSpecificDataReader(dataReader, providerSpecificDataReader);
}
}
return new CommonLanguageSubsetDataReader(dataReader);
}
- protected DataReaderContainer(IDataReader dataReader) {
+ protected DataReaderContainer(IDataReader dataReader)
+ {
Debug.Assert(null != dataReader, "null dataReader");
_dataReader = dataReader;
}
- internal int FieldCount {
- get {
+ internal int FieldCount
+ {
+ get
+ {
return _fieldCount;
}
}
@@ -42,87 +50,110 @@ internal int FieldCount {
internal abstract object GetValue(int ordinal);
internal abstract int GetValues(object[] values);
- internal string GetName(int ordinal) {
+ internal string GetName(int ordinal)
+ {
string fieldName = _dataReader.GetName(ordinal);
Debug.Assert(null != fieldName, "null GetName");
return ((null != fieldName) ? fieldName : "");
}
- internal DataTable GetSchemaTable() {
+ internal DataTable GetSchemaTable()
+ {
return _dataReader.GetSchemaTable();
}
- internal bool NextResult() {
+ internal bool NextResult()
+ {
_fieldCount = 0;
- if (_dataReader.NextResult()) {
+ if (_dataReader.NextResult())
+ {
_fieldCount = VisibleFieldCount;
return true;
}
return false;
}
- internal bool Read() {
+ internal bool Read()
+ {
return _dataReader.Read();
}
- private sealed class ProviderSpecificDataReader : DataReaderContainer {
+ private sealed class ProviderSpecificDataReader : DataReaderContainer
+ {
private DbDataReader _providerSpecificDataReader;
- internal ProviderSpecificDataReader(IDataReader dataReader, DbDataReader dbDataReader) : base(dataReader) {
+ internal ProviderSpecificDataReader(IDataReader dataReader, DbDataReader dbDataReader) : base(dataReader)
+ {
Debug.Assert(null != dataReader, "null dbDataReader");
_providerSpecificDataReader = dbDataReader;
_fieldCount = VisibleFieldCount;
}
- internal override bool ReturnProviderSpecificTypes {
- get {
+ internal override bool ReturnProviderSpecificTypes
+ {
+ get
+ {
return true;
}
}
- protected override int VisibleFieldCount {
- get {
+ protected override int VisibleFieldCount
+ {
+ get
+ {
int fieldCount = _providerSpecificDataReader.VisibleFieldCount;
Debug.Assert(0 <= fieldCount, "negative FieldCount");
return ((0 <= fieldCount) ? fieldCount : 0);
}
}
- internal override Type GetFieldType(int ordinal) {
+ internal override Type GetFieldType(int ordinal)
+ {
Type fieldType = _providerSpecificDataReader.GetProviderSpecificFieldType(ordinal);
Debug.Assert(null != fieldType, "null FieldType");
return fieldType;
}
- internal override object GetValue(int ordinal) {
+ internal override object GetValue(int ordinal)
+ {
return _providerSpecificDataReader.GetProviderSpecificValue(ordinal);
}
- internal override int GetValues(object[] values) {
+ internal override int GetValues(object[] values)
+ {
return _providerSpecificDataReader.GetProviderSpecificValues(values);
}
}
- private sealed class CommonLanguageSubsetDataReader : DataReaderContainer {
+ private sealed class CommonLanguageSubsetDataReader : DataReaderContainer
+ {
- internal CommonLanguageSubsetDataReader(IDataReader dataReader ) : base(dataReader) {
+ internal CommonLanguageSubsetDataReader(IDataReader dataReader) : base(dataReader)
+ {
_fieldCount = VisibleFieldCount;
}
- internal override bool ReturnProviderSpecificTypes {
- get {
+ internal override bool ReturnProviderSpecificTypes
+ {
+ get
+ {
return false;
}
}
- protected override int VisibleFieldCount {
- get {
+ protected override int VisibleFieldCount
+ {
+ get
+ {
int fieldCount = _dataReader.FieldCount;
Debug.Assert(0 <= fieldCount, "negative FieldCount");
return ((0 <= fieldCount) ? fieldCount : 0);
}
}
- internal override Type GetFieldType(int ordinal) {
+ internal override Type GetFieldType(int ordinal)
+ {
return _dataReader.GetFieldType(ordinal);
}
- internal override object GetValue(int ordinal) {
+ internal override object GetValue(int ordinal)
+ {
return _dataReader.GetValue(ordinal);
}
- internal override int GetValues(object[] values) {
+ internal override int GetValues(object[] values)
+ {
return _dataReader.GetValues(values);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs
index 82603d49ce..4c85388f56 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs
@@ -5,582 +5,690 @@
namespace Microsoft.Data.ProviderBase
{
using System;
- using Microsoft.Data.Common;
using System.Diagnostics;
using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
- using System.Security;
- using System.Security.Permissions;
- using System.Threading;
+ using Microsoft.Data.Common;
// DbBuffer is abstract to require derived class to exist
// so that when debugging, we can tell the difference between one DbBuffer and another
- internal abstract class DbBuffer : SafeHandle {
+ internal abstract class DbBuffer : SafeHandle
+ {
internal const int LMEM_FIXED = 0x0000;
internal const int LMEM_MOVEABLE = 0x0002;
internal const int LMEM_ZEROINIT = 0x0040;
private readonly int _bufferLength;
-
- private DbBuffer(int initialSize, bool zeroBuffer) : base(IntPtr.Zero, true) {
- if (0 < initialSize) {
+
+ private DbBuffer(int initialSize, bool zeroBuffer) : base(IntPtr.Zero, true)
+ {
+ if (0 < initialSize)
+ {
int flags = ((zeroBuffer) ? LMEM_ZEROINIT : LMEM_FIXED);
_bufferLength = initialSize;
RuntimeHelpers.PrepareConstrainedRegions();
- try {} finally {
+ try
+ { }
+ finally
+ {
base.handle = SafeNativeMethods.LocalAlloc(flags, (IntPtr)initialSize);
}
- if (IntPtr.Zero == base.handle) {
+ if (IntPtr.Zero == base.handle)
+ {
throw new OutOfMemoryException();
}
}
}
- protected DbBuffer(int initialSize) : this(initialSize, true) {
+ protected DbBuffer(int initialSize) : this(initialSize, true)
+ {
}
- protected DbBuffer(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHandleValue, ownsHandle) {
+ protected DbBuffer(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHandleValue, ownsHandle)
+ {
}
private int BaseOffset { get { return 0; } }
- public override bool IsInvalid {
- get {
+ public override bool IsInvalid
+ {
+ get
+ {
return (IntPtr.Zero == base.handle);
}
}
- internal int Length {
- get {
+ internal int Length
+ {
+ get
+ {
return _bufferLength;
}
}
- internal string PtrToStringUni(int offset) {
+ internal string PtrToStringUni(int offset)
+ {
offset += BaseOffset;
Validate(offset, 2);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
-
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
+
string value = null;
- bool mustRelease = false;
+ bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
-
+
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
int length = UnsafeNativeMethods.lstrlenW(ptr);
- Validate(offset, (2*(length+1)));
+ Validate(offset, (2 * (length + 1)));
value = Marshal.PtrToStringUni(ptr, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
-
+
return value;
}
- internal String PtrToStringUni(int offset, int length) {
+ internal String PtrToStringUni(int offset, int length)
+ {
offset += BaseOffset;
- Validate(offset, 2*length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Validate(offset, 2 * length);
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
string value = null;
- bool mustRelease = false;
+ bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
value = Marshal.PtrToStringUni(ptr, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return value;
}
- internal byte ReadByte(int offset) {
+ internal byte ReadByte(int offset)
+ {
offset += BaseOffset;
ValidateCheck(offset, 1);
- Debug.Assert(0 == offset%4, "invalid alignment");
+ Debug.Assert(0 == offset % 4, "invalid alignment");
byte value;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
value = Marshal.ReadByte(ptr, offset);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return value;
}
- internal byte[] ReadBytes(int offset, int length) {
+ internal byte[] ReadBytes(int offset, int length)
+ {
byte[] value = new byte[length];
return ReadBytes(offset, value, 0, length);
}
- internal byte[] ReadBytes(int offset, byte[] destination, int startIndex, int length) {
+ internal byte[] ReadBytes(int offset, byte[] destination, int startIndex, int length)
+ {
offset += BaseOffset;
Validate(offset, length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
Debug.Assert(null != destination, "null destination");
Debug.Assert(startIndex + length <= destination.Length, "destination too small");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.Copy(ptr, destination, startIndex, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return destination;
}
- internal Char ReadChar(int offset) {
+ internal Char ReadChar(int offset)
+ {
short value = ReadInt16(offset);
return unchecked((char)value);
}
- internal char[] ReadChars(int offset, char[] destination, int startIndex, int length) {
+ internal char[] ReadChars(int offset, char[] destination, int startIndex, int length)
+ {
offset += BaseOffset;
- Validate(offset, 2*length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Validate(offset, 2 * length);
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
Debug.Assert(null != destination, "null destination");
Debug.Assert(startIndex + length <= destination.Length, "destination too small");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.Copy(ptr, destination, startIndex, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return destination;
}
- internal Double ReadDouble(int offset) {
+ internal Double ReadDouble(int offset)
+ {
Int64 value = ReadInt64(offset);
return BitConverter.Int64BitsToDouble(value);
}
- internal Int16 ReadInt16(int offset) {
+ internal Int16 ReadInt16(int offset)
+ {
offset += BaseOffset;
ValidateCheck(offset, 2);
- Debug.Assert(0 == offset%2, "invalid alignment");
+ Debug.Assert(0 == offset % 2, "invalid alignment");
short value;
- bool mustRelease = false;
+ bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
value = Marshal.ReadInt16(ptr, offset);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return value;
}
- internal void ReadInt16Array(int offset, short[] destination, int startIndex, int length) {
+ internal void ReadInt16Array(int offset, short[] destination, int startIndex, int length)
+ {
offset += BaseOffset;
- Validate(offset, 2*length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Validate(offset, 2 * length);
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
Debug.Assert(null != destination, "null destination");
Debug.Assert(startIndex + length <= destination.Length, "destination too small");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.Copy(ptr, destination, startIndex, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal Int32 ReadInt32(int offset) {
+ internal Int32 ReadInt32(int offset)
+ {
offset += BaseOffset;
ValidateCheck(offset, 4);
- Debug.Assert(0 == offset%4, "invalid alignment");
+ Debug.Assert(0 == offset % 4, "invalid alignment");
- int value;
+ int value;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
value = Marshal.ReadInt32(ptr, offset);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return value;
}
- internal void ReadInt32Array(int offset, int[] destination, int startIndex, int length) {
+ internal void ReadInt32Array(int offset, int[] destination, int startIndex, int length)
+ {
offset += BaseOffset;
- Validate(offset, 4*length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Validate(offset, 4 * length);
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
Debug.Assert(null != destination, "null destination");
Debug.Assert(startIndex + length <= destination.Length, "destination too small");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.Copy(ptr, destination, startIndex, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal Int64 ReadInt64(int offset) {
+ internal Int64 ReadInt64(int offset)
+ {
offset += BaseOffset;
ValidateCheck(offset, 8);
- Debug.Assert(0 == offset%IntPtr.Size, "invalid alignment");
+ Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
long value;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
value = Marshal.ReadInt64(ptr, offset);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return value;
}
- internal IntPtr ReadIntPtr(int offset) {
+ internal IntPtr ReadIntPtr(int offset)
+ {
offset += BaseOffset;
ValidateCheck(offset, IntPtr.Size);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
IntPtr value;
- bool mustRelease = false;
+ bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
value = Marshal.ReadIntPtr(ptr, offset);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return value;
}
- internal unsafe Single ReadSingle(int offset) {
+ internal unsafe Single ReadSingle(int offset)
+ {
Int32 value = ReadInt32(offset);
return *(Single*)&value;
}
- override protected bool ReleaseHandle() {
+ override protected bool ReleaseHandle()
+ {
// NOTE: The SafeHandle class guarantees this will be called exactly once.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
- if (IntPtr.Zero != ptr) {
+ if (IntPtr.Zero != ptr)
+ {
SafeNativeMethods.LocalFree(ptr);
}
return true;
}
- private void StructureToPtr(int offset, object structure) {
+ private void StructureToPtr(int offset, object structure)
+ {
Debug.Assert(null != structure, "null structure");
offset += BaseOffset;
ValidateCheck(offset, Marshal.SizeOf(structure.GetType()));
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.StructureToPtr(structure, ptr, false/*fDeleteOld*/);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteByte(int offset, byte value) {
+ internal void WriteByte(int offset, byte value)
+ {
offset += BaseOffset;
ValidateCheck(offset, 1);
- Debug.Assert(0 == offset%4, "invalid alignment");
+ Debug.Assert(0 == offset % 4, "invalid alignment");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
Marshal.WriteByte(ptr, offset, value);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteBytes(int offset, byte[] source, int startIndex, int length) {
+ internal void WriteBytes(int offset, byte[] source, int startIndex, int length)
+ {
offset += BaseOffset;
Validate(offset, length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
Debug.Assert(null != source, "null source");
Debug.Assert(startIndex + length <= source.Length, "source too small");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.Copy(source, startIndex, ptr, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteCharArray(int offset, char[] source, int startIndex, int length) {
+ internal void WriteCharArray(int offset, char[] source, int startIndex, int length)
+ {
offset += BaseOffset;
- Validate(offset, 2*length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Validate(offset, 2 * length);
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
Debug.Assert(null != source, "null source");
Debug.Assert(startIndex + length <= source.Length, "source too small");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.Copy(source, startIndex, ptr, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteDouble(int offset, Double value) {
+ internal void WriteDouble(int offset, Double value)
+ {
WriteInt64(offset, BitConverter.DoubleToInt64Bits(value));
}
- internal void WriteInt16(int offset, short value) {
+ internal void WriteInt16(int offset, short value)
+ {
offset += BaseOffset;
ValidateCheck(offset, 2);
- Debug.Assert(0 == offset%2, "invalid alignment");
+ Debug.Assert(0 == offset % 2, "invalid alignment");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
Marshal.WriteInt16(ptr, offset, value);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteInt16Array(int offset, short[] source, int startIndex, int length) {
+ internal void WriteInt16Array(int offset, short[] source, int startIndex, int length)
+ {
offset += BaseOffset;
- Validate(offset, 2*length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Validate(offset, 2 * length);
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
Debug.Assert(null != source, "null source");
Debug.Assert(startIndex + length <= source.Length, "source too small");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.Copy(source, startIndex, ptr, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteInt32(int offset, int value) {
+ internal void WriteInt32(int offset, int value)
+ {
offset += BaseOffset;
ValidateCheck(offset, 4);
- Debug.Assert(0 == offset%4, "invalid alignment");
+ Debug.Assert(0 == offset % 4, "invalid alignment");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
Marshal.WriteInt32(ptr, offset, value);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteInt32Array(int offset, int[] source, int startIndex, int length) {
+ internal void WriteInt32Array(int offset, int[] source, int startIndex, int length)
+ {
offset += BaseOffset;
- Validate(offset, 4*length);
- Debug.Assert(0 == offset%ADP.PtrSize, "invalid alignment");
+ Validate(offset, 4 * length);
+ Debug.Assert(0 == offset % ADP.PtrSize, "invalid alignment");
Debug.Assert(null != source, "null source");
Debug.Assert(startIndex + length <= source.Length, "source too small");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = ADP.IntPtrOffset(DangerousGetHandle(), offset);
Marshal.Copy(source, startIndex, ptr, length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteInt64(int offset, long value) {
+ internal void WriteInt64(int offset, long value)
+ {
offset += BaseOffset;
ValidateCheck(offset, 8);
- Debug.Assert(0 == offset%IntPtr.Size, "invalid alignment");
+ Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
Marshal.WriteInt64(ptr, offset, value);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal void WriteIntPtr(int offset, IntPtr value) {
+ internal void WriteIntPtr(int offset, IntPtr value)
+ {
offset += BaseOffset;
ValidateCheck(offset, IntPtr.Size);
- Debug.Assert(0 == offset%IntPtr.Size, "invalid alignment");
+ Debug.Assert(0 == offset % IntPtr.Size, "invalid alignment");
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
Marshal.WriteIntPtr(ptr, offset, value);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal unsafe void WriteSingle(int offset, Single value) {
+ internal unsafe void WriteSingle(int offset, Single value)
+ {
WriteInt32(offset, *(Int32*)&value);
}
- internal void ZeroMemory() {
+ internal void ZeroMemory()
+ {
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
IntPtr ptr = DangerousGetHandle();
SafeNativeMethods.ZeroMemory(ptr, (IntPtr)Length);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
}
- internal Guid ReadGuid(int offset) {
+ internal Guid ReadGuid(int offset)
+ {
// faster than Marshal.PtrToStructure(offset, typeof(Guid))
byte[] buffer = new byte[16];
ReadBytes(offset, buffer, 0, 16);
return new Guid(buffer);
}
- internal void WriteGuid(int offset, Guid value) {
+ internal void WriteGuid(int offset, Guid value)
+ {
// faster than Marshal.Copy(value.GetByteArray()
StructureToPtr(offset, value);
}
- internal DateTime ReadDate(int offset) {
+ internal DateTime ReadDate(int offset)
+ {
short[] buffer = new short[3];
ReadInt16Array(offset, buffer, 0, 3);
return new DateTime(
@@ -588,7 +696,8 @@ internal DateTime ReadDate(int offset) {
unchecked((ushort)buffer[1]), // Month
unchecked((ushort)buffer[2])); // Day
}
- internal void WriteDate(int offset, DateTime value) {
+ internal void WriteDate(int offset, DateTime value)
+ {
short[] buffer = new short[3] {
unchecked((short)value.Year),
unchecked((short)value.Month),
@@ -597,7 +706,8 @@ internal void WriteDate(int offset, DateTime value) {
WriteInt16Array(offset, buffer, 0, 3);
}
- internal TimeSpan ReadTime(int offset) {
+ internal TimeSpan ReadTime(int offset)
+ {
short[] buffer = new short[3];
ReadInt16Array(offset, buffer, 0, 3);
return new TimeSpan(
@@ -605,7 +715,8 @@ internal TimeSpan ReadTime(int offset) {
unchecked((ushort)buffer[1]), // Minutes
unchecked((ushort)buffer[2])); // Seconds
}
- internal void WriteTime(int offset, TimeSpan value) {
+ internal void WriteTime(int offset, TimeSpan value)
+ {
short[] buffer = new short[3] {
unchecked((short)value.Hours),
unchecked((short)value.Minutes),
@@ -614,7 +725,8 @@ internal void WriteTime(int offset, TimeSpan value) {
WriteInt16Array(offset, buffer, 0, 3);
}
- internal DateTime ReadDateTime(int offset) {
+ internal DateTime ReadDateTime(int offset)
+ {
short[] buffer = new short[6];
ReadInt16Array(offset, buffer, 0, 6);
int ticks = ReadInt32(offset + 12);
@@ -627,8 +739,9 @@ internal DateTime ReadDateTime(int offset) {
unchecked((ushort)buffer[5])); // Seconds
return value.AddTicks(ticks / 100);
}
- internal void WriteDateTime(int offset, DateTime value) {
- int ticks = (int)(value.Ticks % 10000000L)*100;
+ internal void WriteDateTime(int offset, DateTime value)
+ {
+ int ticks = (int)(value.Ticks % 10000000L) * 100;
short[] buffer = new short[6] {
unchecked((short)value.Year),
unchecked((short)value.Month),
@@ -641,31 +754,35 @@ internal void WriteDateTime(int offset, DateTime value) {
WriteInt32(offset + 12, ticks);
}
- internal Decimal ReadNumeric(int offset) {
+ internal Decimal ReadNumeric(int offset)
+ {
byte[] bits = new byte[20];
ReadBytes(offset, bits, 1, 19);
int[] buffer = new int[4];
- buffer[3] = ((int) bits[2]) << 16; // scale
- if (0 == bits[3]) {
+ buffer[3] = ((int)bits[2]) << 16; // scale
+ if (0 == bits[3])
+ {
buffer[3] |= unchecked((int)0x80000000); //sign
}
- buffer[0] = BitConverter.ToInt32(bits, 4); // low
- buffer[1] = BitConverter.ToInt32(bits, 8); // mid
+ buffer[0] = BitConverter.ToInt32(bits, 4); // low
+ buffer[1] = BitConverter.ToInt32(bits, 8); // mid
buffer[2] = BitConverter.ToInt32(bits, 12); // high
- if (0 != BitConverter.ToInt32(bits, 16)) {
+ if (0 != BitConverter.ToInt32(bits, 16))
+ {
throw ADP.NumericToDecimalOverflow();
}
return new Decimal(buffer);
}
- internal void WriteNumeric(int offset, Decimal value, byte precision) {
+ internal void WriteNumeric(int offset, Decimal value, byte precision)
+ {
int[] tmp = Decimal.GetBits(value);
byte[] buffer = new byte[20];
buffer[1] = precision;
Buffer.BlockCopy(tmp, 14, buffer, 2, 2); // copy sign and scale
- buffer[3] = (Byte) ((0 == buffer[3]) ? 1 : 0); // flip sign for native
+ buffer[3] = (Byte)((0 == buffer[3]) ? 1 : 0); // flip sign for native
Buffer.BlockCopy(tmp, 0, buffer, 4, 12);
buffer[16] = 0;
buffer[17] = 0;
@@ -675,12 +792,15 @@ internal void WriteNumeric(int offset, Decimal value, byte precision) {
}
[ConditionalAttribute("DEBUG")]
- protected void ValidateCheck(int offset, int count) {
+ protected void ValidateCheck(int offset, int count)
+ {
Validate(offset, count);
}
- protected void Validate(int offset, int count) {
- if ((offset < 0) || (count < 0) || (Length < checked(offset + count))) {
+ protected void Validate(int offset, int count)
+ {
+ if ((offset < 0) || (count < 0) || (Length < checked(offset + count)))
+ {
throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs
index ec8ba4a6b3..3cc0501354 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs
@@ -4,114 +4,133 @@
namespace Microsoft.Data.ProviderBase
{
-
- using System;
- using System.ComponentModel;
- using Microsoft.Data;
- using Microsoft.Data.Common;
+ using System.Data;
+ using System.Data.Common;
using System.Diagnostics;
- using System.Globalization;
- using System.Threading;
using System.Threading.Tasks;
+ using Microsoft.Data.Common;
using SysTx = System.Transactions;
- using System.Data;
- using System.Data.Common;
- abstract internal class DbConnectionClosed : DbConnectionInternal {
+ abstract internal class DbConnectionClosed : DbConnectionInternal
+ {
// Construct an "empty" connection
- protected DbConnectionClosed(ConnectionState state, bool hidePassword, bool allowSetConnectionString) : base(state, hidePassword, allowSetConnectionString) {
+ protected DbConnectionClosed(ConnectionState state, bool hidePassword, bool allowSetConnectionString) : base(state, hidePassword, allowSetConnectionString)
+ {
}
- override public string ServerVersion {
- get {
+ override public string ServerVersion
+ {
+ get
+ {
throw ADP.ClosedConnectionError();
}
}
- override protected void Activate(SysTx.Transaction transaction) {
+ override protected void Activate(SysTx.Transaction transaction)
+ {
throw ADP.ClosedConnectionError();
}
- override public DbTransaction BeginTransaction(IsolationLevel il) {
+ override public DbTransaction BeginTransaction(IsolationLevel il)
+ {
throw ADP.ClosedConnectionError();
}
- override public void ChangeDatabase(string database) {
+ override public void ChangeDatabase(string database)
+ {
throw ADP.ClosedConnectionError();
}
- internal override void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory) {
+ internal override void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
+ {
// not much to do here...
}
- override protected void Deactivate() {
+ override protected void Deactivate()
+ {
throw ADP.ClosedConnectionError();
}
- override public void EnlistTransaction(SysTx.Transaction transaction) {
+ override public void EnlistTransaction(SysTx.Transaction transaction)
+ {
throw ADP.ClosedConnectionError();
}
- override protected internal DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions) {
+ override protected internal DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions)
+ {
throw ADP.ClosedConnectionError();
}
- protected override DbReferenceCollection CreateReferenceCollection() {
+ protected override DbReferenceCollection CreateReferenceCollection()
+ {
throw ADP.ClosedConnectionError();
}
- internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) {
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions)
+ {
return base.TryOpenConnectionInternal(outerConnection, connectionFactory, retry, userOptions);
}
}
- abstract internal class DbConnectionBusy : DbConnectionClosed {
+ abstract internal class DbConnectionBusy : DbConnectionClosed
+ {
- protected DbConnectionBusy(ConnectionState state) : base(state, true, false) {
+ protected DbConnectionBusy(ConnectionState state) : base(state, true, false)
+ {
}
- internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) {
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions)
+ {
throw ADP.ConnectionAlreadyOpen(State);
}
}
- sealed internal class DbConnectionClosedBusy : DbConnectionBusy {
+ sealed internal class DbConnectionClosedBusy : DbConnectionBusy
+ {
// Closed Connection, Currently Busy - changing connection string
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedBusy(); // singleton object
- private DbConnectionClosedBusy() : base(ConnectionState.Closed) {
+ private DbConnectionClosedBusy() : base(ConnectionState.Closed)
+ {
}
}
- sealed internal class DbConnectionOpenBusy : DbConnectionBusy {
+ sealed internal class DbConnectionOpenBusy : DbConnectionBusy
+ {
// Open Connection, Currently Busy - closing connection
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionOpenBusy(); // singleton object
- private DbConnectionOpenBusy() : base(ConnectionState.Open) {
+ private DbConnectionOpenBusy() : base(ConnectionState.Open)
+ {
}
}
- sealed internal class DbConnectionClosedConnecting : DbConnectionBusy {
+ sealed internal class DbConnectionClosedConnecting : DbConnectionBusy
+ {
// Closed Connection, Currently Connecting
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedConnecting(); // singleton object
- private DbConnectionClosedConnecting() : base(ConnectionState.Connecting) {
+ private DbConnectionClosedConnecting() : base(ConnectionState.Connecting)
+ {
}
internal override void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
{
connectionFactory.SetInnerConnectionTo(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
-
- internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) {
+
+ internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions)
+ {
return TryOpenConnection(outerConnection, connectionFactory, retry, userOptions);
}
- internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) {
+ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions)
+ {
- if (retry == null || !retry.Task.IsCompleted) {
+ if (retry == null || !retry.Task.IsCompleted)
+ {
// retry is null if this is a synchronous call
// if someone calls Open or OpenAsync while in this state,
@@ -123,7 +142,8 @@ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnect
// we are completing an asynchronous open
Debug.Assert(retry.Task.Status == TaskStatus.RanToCompletion, "retry task must be completed successfully");
DbConnectionInternal openConnection = retry.Task.Result;
- if (null == openConnection) {
+ if (null == openConnection)
+ {
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull);
}
@@ -133,24 +153,29 @@ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnect
}
}
- sealed internal class DbConnectionClosedNeverOpened : DbConnectionClosed {
+ sealed internal class DbConnectionClosedNeverOpened : DbConnectionClosed
+ {
// Closed Connection, Has Never Been Opened
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedNeverOpened(); // singleton object
- private DbConnectionClosedNeverOpened() : base(ConnectionState.Closed, false, true) {
+ private DbConnectionClosedNeverOpened() : base(ConnectionState.Closed, false, true)
+ {
}
}
- sealed internal class DbConnectionClosedPreviouslyOpened : DbConnectionClosed {
+ sealed internal class DbConnectionClosedPreviouslyOpened : DbConnectionClosed
+ {
// Closed Connection, Has Previously Been Opened
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedPreviouslyOpened(); // singleton object
- private DbConnectionClosedPreviouslyOpened() : base(ConnectionState.Closed, true, true) {
+ private DbConnectionClosedPreviouslyOpened() : base(ConnectionState.Closed, true, true)
+ {
}
- internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) {
+ internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions)
+ {
return TryOpenConnection(outerConnection, connectionFactory, retry, userOptions);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs
index 0fa180c355..ddb3dfd2a2 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs
@@ -2,27 +2,28 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
using System.Collections.Generic;
+ using System.Data;
+ using System.Data.Common;
using System.Diagnostics;
- using Microsoft.Data.Common;
- using System.Linq;
using System.Threading;
using System.Threading.Tasks;
- using System.Data.Common;
- using System.Data;
+ using Microsoft.Data.Common;
- internal abstract class DbConnectionFactory {
- private Dictionary _connectionPoolGroups;
+ internal abstract class DbConnectionFactory
+ {
+ private Dictionary _connectionPoolGroups;
private readonly List _poolsToRelease;
private readonly List _poolGroupsToRelease;
private readonly DbConnectionPoolCounters _performanceCounters;
private readonly Timer _pruningTimer;
- private const int PruningDueTime =4*60*1000; // 4 minutes
- private const int PruningPeriod = 30*1000; // thirty seconds
+ private const int PruningDueTime = 4 * 60 * 1000; // 4 minutes
+ private const int PruningPeriod = 30 * 1000; // thirty seconds
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
@@ -33,9 +34,10 @@ internal abstract class DbConnectionFactory {
static Task[] s_pendingOpenNonPooled = new Task[Environment.ProcessorCount];
static Task s_completedTask;
- protected DbConnectionFactory() : this (DbConnectionPoolCountersNoCounters.SingletonInstance) { }
+ protected DbConnectionFactory() : this(DbConnectionPoolCountersNoCounters.SingletonInstance) { }
- protected DbConnectionFactory(DbConnectionPoolCounters performanceCounters) {
+ protected DbConnectionFactory(DbConnectionPoolCounters performanceCounters)
+ {
_performanceCounters = performanceCounters;
_connectionPoolGroups = new Dictionary();
_poolsToRelease = new List();
@@ -43,83 +45,103 @@ protected DbConnectionFactory(DbConnectionPoolCounters performanceCounters) {
_pruningTimer = CreatePruningTimer();
}
- internal DbConnectionPoolCounters PerformanceCounters {
+ internal DbConnectionPoolCounters PerformanceCounters
+ {
get { return _performanceCounters; }
}
- abstract public DbProviderFactory ProviderFactory {
+ abstract public DbProviderFactory ProviderFactory
+ {
get;
}
- internal int ObjectID {
- get {
+ internal int ObjectID
+ {
+ get
+ {
return _objectID;
}
}
- public void ClearAllPools() {
+ public void ClearAllPools()
+ {
IntPtr hscp;
Bid.ScopeEnter(out hscp, " ");
- try {
+ try
+ {
Dictionary connectionPoolGroups = _connectionPoolGroups;
- foreach (KeyValuePair entry in connectionPoolGroups) {
+ foreach (KeyValuePair entry in connectionPoolGroups)
+ {
DbConnectionPoolGroup poolGroup = entry.Value;
- if (null != poolGroup) {
+ if (null != poolGroup)
+ {
poolGroup.Clear();
}
}
}
- finally {
+ finally
+ {
Bid.ScopeLeave(ref hscp);
}
}
- public void ClearPool(DbConnection connection) {
+ public void ClearPool(DbConnection connection)
+ {
ADP.CheckArgumentNull(connection, "connection");
IntPtr hscp;
- Bid.ScopeEnter(out hscp, " %d#" , GetObjectId(connection));
- try {
+ Bid.ScopeEnter(out hscp, " %d#", GetObjectId(connection));
+ try
+ {
DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection);
- if (null != poolGroup) {
+ if (null != poolGroup)
+ {
poolGroup.Clear();
}
}
- finally {
+ finally
+ {
Bid.ScopeLeave(ref hscp);
}
}
- public void ClearPool(DbConnectionPoolKey key) {
+ public void ClearPool(DbConnectionPoolKey key)
+ {
Debug.Assert(key != null, "key cannot be null");
ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString");
IntPtr hscp;
Bid.ScopeEnter(out hscp, " connectionString");
- try {
+ try
+ {
DbConnectionPoolGroup poolGroup;
Dictionary connectionPoolGroups = _connectionPoolGroups;
- if (connectionPoolGroups.TryGetValue(key, out poolGroup)) {
+ if (connectionPoolGroups.TryGetValue(key, out poolGroup))
+ {
poolGroup.Clear();
}
}
- finally {
+ finally
+ {
Bid.ScopeLeave(ref hscp);
}
}
- internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions){
+ internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions)
+ {
return null;
}
- virtual protected DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory) {
+ virtual protected DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory)
+ {
// providers that support GetSchema must override this with a method that creates a meta data
// factory appropriate for them.
cacheMetaDataFactory = false;
throw ADP.NotSupported();
}
- internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) {
+ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
+ {
Debug.Assert(null != owningConnection, "null owningConnection?");
Debug.Assert(null != poolGroup, "null poolGroup?");
@@ -128,7 +150,8 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne
DbConnectionPoolKey poolKey = poolGroup.PoolKey;
DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions);
- if (null != newConnection) {
+ if (null != newConnection)
+ {
PerformanceCounters.HardConnectsPerSecond.Increment();
newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters);
}
@@ -136,12 +159,14 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne
return newConnection;
}
- internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) {
+ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
+ {
Debug.Assert(null != pool, "null pool?");
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo;
DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions);
- if (null != newConnection) {
+ if (null != newConnection)
+ {
PerformanceCounters.HardConnectsPerSecond.Increment();
newConnection.MakePooledConnection(pool);
}
@@ -149,21 +174,26 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo
return newConnection;
}
- virtual internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo (DbConnectionOptions connectionOptions) {
+ virtual internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
+ {
return null;
}
- private Timer CreatePruningTimer() {
+ private Timer CreatePruningTimer()
+ {
TimerCallback callback = new TimerCallback(PruneConnectionPoolGroups);
return new Timer(callback, null, PruningDueTime, PruningPeriod);
}
- protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key) {
+ protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key)
+ {
Debug.Assert(key != null, "key cannot be null");
- if (!ADP.IsEmpty(key.ConnectionString)) {
+ if (!ADP.IsEmpty(key.ConnectionString))
+ {
DbConnectionPoolGroup connectionPoolGroup;
Dictionary connectionPoolGroups = _connectionPoolGroups;
- if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) {
+ if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
+ {
return connectionPoolGroup.ConnectionOptions;
}
}
@@ -173,7 +203,8 @@ protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key) {
// GetCompletedTask must be called from within s_pendingOpenPooled lock
static Task GetCompletedTask()
{
- if (s_completedTask == null) {
+ if (s_completedTask == null)
+ {
TaskCompletionSource source = new TaskCompletionSource();
source.SetResult(null);
s_completedTask = source.Task;
@@ -181,7 +212,8 @@ static Task GetCompletedTask()
return s_completedTask;
}
- internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection) {
+ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
+ {
Debug.Assert(null != owningConnection, "null owningConnection?");
DbConnectionPoolGroup poolGroup;
@@ -201,36 +233,44 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour
int retriesLeft = 10;
int timeBetweenRetriesMilliseconds = 1;
- do {
+ do
+ {
poolGroup = GetConnectionPoolGroup(owningConnection);
// Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread.
connectionPool = GetConnectionPool(owningConnection, poolGroup);
- if (null == connectionPool) {
+ if (null == connectionPool)
+ {
// If GetConnectionPool returns null, we can be certain that
// this connection should not be pooled via DbConnectionPool
// or have a disabled pool entry.
poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled
- if (retry != null) {
+ if (retry != null)
+ {
Task newTask;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
- lock (s_pendingOpenNonPooled) {
+ lock (s_pendingOpenNonPooled)
+ {
// look for an available task slot (completed or empty)
int idx;
- for (idx=0; idx {
+ newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) =>
+ {
System.Transactions.Transaction originalTransaction = ADP.GetCurrentTransaction();
try
{
ADP.SetCurrentTransaction(retry.Task.AsyncState as System.Transactions.Transaction);
var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
- if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open)) {
+ if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
+ {
oldConnection.PrepareForReplaceConnection();
oldConnection.Dispose();
}
return newConnection;
- } finally {
+ }
+ finally
+ {
ADP.SetCurrentTransaction(originalTransaction);
}
}, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
@@ -260,24 +304,32 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour
}
// Set up the timeout (if needed)
- if (owningConnection.ConnectionTimeout > 0) {
+ if (owningConnection.ConnectionTimeout > 0)
+ {
int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000;
cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds);
}
// once the task is done, propagate the final results to the original caller
- newTask.ContinueWith((task) => {
+ newTask.ContinueWith((task) =>
+ {
cancellationTokenSource.Dispose();
- if (task.IsCanceled) {
+ if (task.IsCanceled)
+ {
retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout()));
- } else if (task.IsFaulted) {
+ }
+ else if (task.IsFaulted)
+ {
retry.TrySetException(task.Exception.InnerException);
}
- else {
- if (retry.TrySetResult(task.Result)) {
+ else
+ {
+ if (retry.TrySetResult(task.Result))
+ {
PerformanceCounters.NumberOfNonPooledConnections.Increment();
}
- else {
+ else
+ {
// The outer TaskCompletionSource was already completed
// Which means that we don't know if someone has messed with the outer connection in the middle of creation
// So the best thing to do now is to destroy the newly created connection
@@ -293,25 +345,32 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour
connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
PerformanceCounters.NumberOfNonPooledConnections.Increment();
}
- else {
- if (((SqlClient.SqlConnection)owningConnection).ForceNewConnection) {
+ else
+ {
+ if (((SqlClient.SqlConnection)owningConnection).ForceNewConnection)
+ {
Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection");
connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection);
}
- else {
- if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection)) {
+ else
+ {
+ if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection))
+ {
return false;
}
}
- if (connection == null) {
+ if (connection == null)
+ {
// connection creation failed on semaphore waiting or if max pool reached
- if (connectionPool.IsRunning) {
+ if (connectionPool.IsRunning)
+ {
// If GetConnection failed while the pool is running, the pool timeout occurred.
Bid.Trace(" %d#, GetConnection failed because a pool timeout occurred.\n", ObjectID);
throw ADP.PooledOpenTimeout();
}
- else {
+ else
+ {
// We've hit the race condition, where the pool was shut down after we got it from the group.
// Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated
// before retrying.
@@ -322,7 +381,8 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour
}
} while (connection == null && retriesLeft-- > 0);
- if (connection == null) {
+ if (connection == null)
+ {
// exhausted all retries or timed out - give up
Bid.Trace(" %d#, GetConnection failed because a pool timeout occurred and all retries were exhausted.\n", ObjectID);
throw ADP.PooledOpenTimeout();
@@ -331,7 +391,8 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour
return true;
}
- private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup) {
+ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup)
+ {
// if poolgroup is disabled, it will be replaced with a new entry
Debug.Assert(null != owningObject, "null owningObject?");
@@ -346,7 +407,8 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti
// re-create the pool entry whenever it's disabled.
// however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work
- if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) {
+ if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))
+ {
Bid.Trace(" %d#, DisabledPoolGroup=%d#\n", ObjectID, connectionPoolGroup.ObjectID);
// reusing existing pool option in case user originally used SetConnectionPoolOptions
@@ -364,59 +426,71 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti
return connectionPool;
}
- internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions) {
- if (ADP.IsEmpty(key.ConnectionString)) {
+ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions)
+ {
+ if (ADP.IsEmpty(key.ConnectionString))
+ {
return (DbConnectionPoolGroup)null;
}
DbConnectionPoolGroup connectionPoolGroup;
Dictionary connectionPoolGroups = _connectionPoolGroups;
- if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))) {
+ if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)))
+ {
// If we can't find an entry for the connection string in
// our collection of pool entries, then we need to create a
// new pool entry and add it to our collection.
DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions);
- if (null == connectionOptions) {
+ if (null == connectionOptions)
+ {
throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing);
}
string expandedConnectionString = key.ConnectionString;
- if (null == userConnectionOptions) { // we only allow one expansion on the connection string
+ if (null == userConnectionOptions)
+ { // we only allow one expansion on the connection string
userConnectionOptions = connectionOptions;
expandedConnectionString = connectionOptions.Expand();
// if the expanded string is same instance (default implementation), the use the already created options
- if ((object)expandedConnectionString != (object)key.ConnectionString) {
+ if ((object)expandedConnectionString != (object)key.ConnectionString)
+ {
// CONSIDER: caching the original string to reduce future parsing
- DbConnectionPoolKey newKey = (DbConnectionPoolKey) ((ICloneable) key).Clone();
+ DbConnectionPoolKey newKey = (DbConnectionPoolKey)((ICloneable)key).Clone();
newKey.ConnectionString = expandedConnectionString;
return GetConnectionPoolGroup(newKey, null, ref userConnectionOptions);
}
}
// We don't support connection pooling on Win9x; it lacks too many of the APIs we require.
- if ((null == poolOptions) && ADP.IsWindowsNT) {
- if (null != connectionPoolGroup) {
+ if ((null == poolOptions) && ADP.IsWindowsNT)
+ {
+ if (null != connectionPoolGroup)
+ {
// reusing existing pool option in case user originally used SetConnectionPoolOptions
poolOptions = connectionPoolGroup.PoolGroupOptions;
}
- else {
+ else
+ {
// Note: may return null for non-pooled connections
poolOptions = CreateConnectionPoolGroupOptions(connectionOptions);
}
}
- lock (this) {
+ lock (this)
+ {
connectionPoolGroups = _connectionPoolGroups;
- if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) {
+ if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
+ {
DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions);
newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions);
// build new dictionary with space for new connection string
- Dictionary newConnectionPoolGroups = new Dictionary(1+connectionPoolGroups.Count);
- foreach (KeyValuePair entry in connectionPoolGroups) {
+ Dictionary newConnectionPoolGroups = new Dictionary(1 + connectionPoolGroups.Count);
+ foreach (KeyValuePair entry in connectionPoolGroups)
+ {
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
@@ -426,21 +500,24 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key,
connectionPoolGroup = newConnectionPoolGroup;
_connectionPoolGroups = newConnectionPoolGroups;
}
- else {
+ else
+ {
Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered");
}
}
Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?");
Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?");
}
- else if (null == userConnectionOptions) {
+ else if (null == userConnectionOptions)
+ {
userConnectionOptions = connectionPoolGroup.ConnectionOptions;
}
return connectionPoolGroup;
}
- internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPoolGroup,DbConnectionInternal internalConnection){
- Debug.Assert (connectionPoolGroup != null, "connectionPoolGroup may not be null.");
+ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPoolGroup, DbConnectionInternal internalConnection)
+ {
+ Debug.Assert(connectionPoolGroup != null, "connectionPoolGroup may not be null.");
// get the matadatafactory from the pool entry. If it does not already have one
// create one and save it on the pool entry
@@ -448,19 +525,23 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo
// consider serializing this so we don't construct multiple metadata factories
// if two threads happen to hit this at the same time. One will be GC'd
- if (metaDataFactory == null){
+ if (metaDataFactory == null)
+ {
bool allowCache = false;
metaDataFactory = CreateMetaDataFactory(internalConnection, out allowCache);
- if (allowCache) {
+ if (allowCache)
+ {
connectionPoolGroup.MetaDataFactory = metaDataFactory;
}
}
return metaDataFactory;
}
- private void PruneConnectionPoolGroups(object state) {
+ private void PruneConnectionPoolGroups(object state)
+ {
// when debugging this method, expect multiple threads at the same time
- if (Bid.AdvancedOn) {
+ if (Bid.AdvancedOn)
+ {
Bid.Trace(" %d#\n", ObjectID);
}
@@ -468,16 +549,22 @@ private void PruneConnectionPoolGroups(object state) {
// pool, when the pool is finally empty, we dispose of it. If the
// pool isn't empty, it's because there are active connections or
// distributed transactions that need it.
- lock (_poolsToRelease) {
- if (0 != _poolsToRelease.Count) {
+ lock (_poolsToRelease)
+ {
+ if (0 != _poolsToRelease.Count)
+ {
DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray();
- foreach (DbConnectionPool pool in poolsToRelease) {
- if (null != pool) {
+ foreach (DbConnectionPool pool in poolsToRelease)
+ {
+ if (null != pool)
+ {
pool.Clear();
- if (0 == pool.Count) {
+ if (0 == pool.Count)
+ {
_poolsToRelease.Remove(pool);
- if (Bid.AdvancedOn) {
+ if (Bid.AdvancedOn)
+ {
Bid.Trace(" %d#, ReleasePool=%d#\n", ObjectID, pool.ObjectID);
}
PerformanceCounters.NumberOfInactiveConnectionPools.Decrement();
@@ -490,16 +577,22 @@ private void PruneConnectionPoolGroups(object state) {
// Next, walk the pool entry release list and dispose of each
// pool entry when it is finally empty. If the pool entry isn't
// empty, it's because there are active pools that need it.
- lock (_poolGroupsToRelease) {
- if (0 != _poolGroupsToRelease.Count) {
+ lock (_poolGroupsToRelease)
+ {
+ if (0 != _poolGroupsToRelease.Count)
+ {
DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray();
- foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease) {
- if (null != poolGroup) {
+ foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease)
+ {
+ if (null != poolGroup)
+ {
int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease
- if (0 == poolsLeft) {
+ if (0 == poolsLeft)
+ {
_poolGroupsToRelease.Remove(poolGroup);
- if (Bid.AdvancedOn) {
+ if (Bid.AdvancedOn)
+ {
Bid.Trace(" %d#, ReleasePoolGroup=%d#\n", ObjectID, poolGroup.ObjectID);
}
PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement();
@@ -512,22 +605,27 @@ private void PruneConnectionPoolGroups(object state) {
// Finally, we walk through the collection of connection pool entries
// and prune each one. This will cause any empty pools to be put
// into the release list.
- lock (this) {
+ lock (this)
+ {
Dictionary connectionPoolGroups = _connectionPoolGroups;
Dictionary newConnectionPoolGroups = new Dictionary(connectionPoolGroups.Count);
- foreach (KeyValuePair entry in connectionPoolGroups) {
- if (null != entry.Value) {
+ foreach (KeyValuePair entry in connectionPoolGroups)
+ {
+ if (null != entry.Value)
+ {
Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered");
// entries start active and go idle during prune if all pools are gone
// move idle entries from last prune pass to a queue for pending release
// otherwise process entry which may move it from active to idle
- if (entry.Value.Prune()) { // may add entries to _poolsToRelease
+ if (entry.Value.Prune())
+ { // may add entries to _poolsToRelease
PerformanceCounters.NumberOfActiveConnectionPoolGroups.Decrement();
QueuePoolGroupForRelease(entry.Value);
}
- else {
+ else
+ {
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
}
@@ -536,19 +634,22 @@ private void PruneConnectionPoolGroups(object state) {
}
}
- internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) {
+ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing)
+ {
// Queue the pool up for release -- we'll clear it out and dispose
// of it as the last part of the pruning timer callback so we don't
// do it with the pool entry or the pool collection locked.
- Debug.Assert (null != pool, "null pool?");
+ Debug.Assert(null != pool, "null pool?");
// set the pool to the shutdown state to force all active
// connections to be automatically disposed when they
// are returned to the pool
pool.Shutdown();
- lock (_poolsToRelease) {
- if (clearing) {
+ lock (_poolsToRelease)
+ {
+ if (clearing)
+ {
pool.Clear();
}
_poolsToRelease.Add(pool);
@@ -556,22 +657,25 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) {
PerformanceCounters.NumberOfInactiveConnectionPools.Increment();
}
- internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) {
- Debug.Assert (null != poolGroup, "null poolGroup?");
+ internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup)
+ {
+ Debug.Assert(null != poolGroup, "null poolGroup?");
Bid.Trace(" %d#, poolGroup=%d#\n", ObjectID, poolGroup.ObjectID);
- lock (_poolGroupsToRelease) {
+ lock (_poolGroupsToRelease)
+ {
_poolGroupsToRelease.Add(poolGroup);
}
PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Increment();
}
- virtual protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) {
+ virtual protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
+ {
return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection);
}
abstract protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection);
-
+
abstract protected DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous);
abstract protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options);
@@ -588,7 +692,7 @@ virtual protected DbConnectionInternal CreateConnection(DbConnectionOptions opti
abstract internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to);
- abstract internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) ;
+ abstract internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from);
abstract internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to);
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
index 55a48a905c..a346bedc76 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs
@@ -2,93 +2,100 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
- using System.ComponentModel;
using System.Data;
- using Microsoft.Data.Common;
+ using System.Data.Common;
using System.Diagnostics;
- using System.Globalization;
using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using System.Runtime.InteropServices.ComTypes;
- using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
+ using Microsoft.Data.Common;
using SysTx = System.Transactions;
- using System.Data.Common;
- internal abstract class DbConnectionInternal { // V1.1.3300
+ internal abstract class DbConnectionInternal
+ { // V1.1.3300
+
-
private static int _objectTypeCount;
internal readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed);
- internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open);
+ internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open);
- private readonly bool _allowSetConnectionString;
- private readonly bool _hidePassword;
+ private readonly bool _allowSetConnectionString;
+ private readonly bool _hidePassword;
private readonly ConnectionState _state;
- private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections)
+ private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections)
- private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only)
+ private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only)
private DbConnectionPoolCounters _performanceCounters; // the performance counters we're supposed to update
- private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated
- private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool)
+ private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated
+ private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool)
- private bool _connectionIsDoomed; // true when the connection should no longer be used.
- private bool _cannotBePooled; // true when the connection should no longer be pooled.
- private bool _isInStasis;
+ private bool _connectionIsDoomed; // true when the connection should no longer be used.
+ private bool _cannotBePooled; // true when the connection should no longer be pooled.
+ private bool _isInStasis;
- private DateTime _createTime; // when the connection was created.
+ private DateTime _createTime; // when the connection was created.
- private SysTx.Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
+ private SysTx.Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
// _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed.
// However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here.
// This field should only be assigned a value at the same time _enlistedTransaction is updated.
// Also, this reference should not be disposed, since we aren't taking ownership of it.
- private SysTx.Transaction _enlistedTransactionOriginal;
+ private SysTx.Transaction _enlistedTransactionOriginal;
#if DEBUG
private int _activateCount; // debug only counter to verify activate/deactivates are in sync.
#endif //DEBUG
- protected DbConnectionInternal() : this(ConnectionState.Open, true, false) { // V1.1.3300
+ protected DbConnectionInternal() : this(ConnectionState.Open, true, false)
+ { // V1.1.3300
}
// Constructor for internal connections
- internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString) {
+ internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString)
+ {
_allowSetConnectionString = allowSetConnectionString;
_hidePassword = hidePassword;
_state = state;
}
- internal bool AllowSetConnectionString {
- get {
+ internal bool AllowSetConnectionString
+ {
+ get
+ {
return _allowSetConnectionString;
}
}
- internal bool CanBePooled {
- get {
+ internal bool CanBePooled
+ {
+ get
+ {
bool flag = (!_connectionIsDoomed && !_cannotBePooled && !_owningObject.IsAlive);
return flag;
}
}
- protected internal SysTx.Transaction EnlistedTransaction {
- get {
+ protected internal SysTx.Transaction EnlistedTransaction
+ {
+ get
+ {
return _enlistedTransaction;
}
- set {
+ set
+ {
SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
if (((null == currentEnlistedTransaction) && (null != value))
- || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value))) { // WebData 20000024
+ || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value)))
+ { // WebData 20000024
// Pay attention to the order here:
// 1) defect from any notifications
@@ -100,8 +107,10 @@ protected internal SysTx.Transaction EnlistedTransaction {
// duration of the using block of the TransactionScope
SysTx.Transaction valueClone = null;
SysTx.Transaction previousTransactionClone = null;
- try {
- if (null != value) {
+ try
+ {
+ if (null != value)
+ {
valueClone = value.Clone();
}
@@ -111,7 +120,8 @@ protected internal SysTx.Transaction EnlistedTransaction {
// threads, and check once we get around to finalizing things
// inside a lock.
- lock(this) {
+ lock (this)
+ {
// NOTE: There is still a race condition here, when we are
// called from EnlistTransaction (which cannot re-enlist)
// instead of EnlistDistributedTransaction (which can),
@@ -129,15 +139,18 @@ protected internal SysTx.Transaction EnlistedTransaction {
valueClone = null; // we've stored it, don't dispose it.
}
}
- finally {
+ finally
+ {
// we really need to dispose our clones; they may have
// native resources and GC may not happen soon enough.
// VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction
- if (null != previousTransactionClone &&
- !Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction)) {
+ if (null != previousTransactionClone &&
+ !Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction))
+ {
previousTransactionClone.Dispose();
}
- if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction)) {
+ if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction))
+ {
valueClone.Dispose();
}
}
@@ -147,8 +160,10 @@ protected internal SysTx.Transaction EnlistedTransaction {
// against multiple concurrent calls to enlist, which really
// isn't supported anyway.
- if (null != value) {
- if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
+ if (null != value)
+ {
+ if (Bid.IsOn(DbConnectionPool.PoolerTracePoints))
+ {
int x = value.GetHashCode();
Bid.PoolerTrace(" %d#, Transaction %d#, Enlisting.\n", ObjectID, x);
}
@@ -201,8 +216,10 @@ protected bool EnlistedTransactionDisposed
}
// Is this connection in stasis, waiting for transaction to end before returning to pool?
- internal bool IsTxRootWaitingForTxEnd {
- get {
+ internal bool IsTxRootWaitingForTxEnd
+ {
+ get
+ {
return _isInStasis;
}
}
@@ -223,26 +240,34 @@ virtual protected bool UnbindOnTransactionCompletion
}
// Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction?
- virtual protected internal bool IsNonPoolableTransactionRoot {
- get {
+ virtual protected internal bool IsNonPoolableTransactionRoot
+ {
+ get
+ {
return false; // if you want to have delegated transactions that are non-poolable, you better override this...
}
}
- virtual internal bool IsTransactionRoot {
- get {
+ virtual internal bool IsTransactionRoot
+ {
+ get
+ {
return false; // if you want to have delegated transactions, you better override this...
}
}
- protected internal bool IsConnectionDoomed {
- get {
+ protected internal bool IsConnectionDoomed
+ {
+ get
+ {
return _connectionIsDoomed;
}
}
- internal bool IsEmancipated {
- get {
+ internal bool IsEmancipated
+ {
+ get
+ {
// NOTE: There are race conditions between PrePush, PostPop and this
// property getter -- only use this while this object is locked;
// (DbConnectionPool.Clear and ReclaimEmancipatedObjects
@@ -271,77 +296,99 @@ internal bool IsEmancipated {
}
}
- internal bool IsInPool {
- get {
+ internal bool IsInPool
+ {
+ get
+ {
Debug.Assert(_pooledCount <= 1 && _pooledCount >= -1, "Pooled count for object is invalid");
return (_pooledCount == 1);
}
}
- internal int ObjectID {
- get {
+ internal int ObjectID
+ {
+ get
+ {
return _objectID;
}
}
- protected internal object Owner {
+ protected internal object Owner
+ {
// We use a weak reference to the owning object so we can identify when
// it has been garbage collected without thowing exceptions.
- get {
+ get
+ {
return _owningObject.Target;
}
}
- internal DbConnectionPool Pool {
- get {
+ internal DbConnectionPool Pool
+ {
+ get
+ {
return _connectionPool;
}
}
- protected DbConnectionPoolCounters PerformanceCounters {
- get {
+ protected DbConnectionPoolCounters PerformanceCounters
+ {
+ get
+ {
return _performanceCounters;
}
}
- virtual protected bool ReadyToPrepareTransaction {
- get {
+ virtual protected bool ReadyToPrepareTransaction
+ {
+ get
+ {
return true;
}
}
- protected internal DbReferenceCollection ReferenceCollection {
- get {
+ protected internal DbReferenceCollection ReferenceCollection
+ {
+ get
+ {
return _referenceCollection;
}
}
- abstract public string ServerVersion {
+ abstract public string ServerVersion
+ {
get;
}
// this should be abstract but untill it is added to all the providers virtual will have to do RickFe
- virtual public string ServerVersionNormalized {
- get{
+ virtual public string ServerVersionNormalized
+ {
+ get
+ {
throw ADP.NotSupported();
}
}
- public bool ShouldHidePassword {
- get {
+ public bool ShouldHidePassword
+ {
+ get
+ {
return _hidePassword;
}
}
- public ConnectionState State {
- get {
+ public ConnectionState State
+ {
+ get
+ {
return _state;
}
}
abstract protected void Activate(SysTx.Transaction transaction);
- internal void ActivateConnection(SysTx.Transaction transaction) {
+ internal void ActivateConnection(SysTx.Transaction transaction)
+ {
// Internal method called from the connection pooler so we don't expose
// the Activate method publicly.
@@ -356,10 +403,13 @@ internal void ActivateConnection(SysTx.Transaction transaction) {
PerformanceCounters.NumberOfActiveConnections.Increment();
}
- internal void AddWeakReference(object value, int tag) {
- if (null == _referenceCollection) {
+ internal void AddWeakReference(object value, int tag)
+ {
+ if (null == _referenceCollection)
+ {
_referenceCollection = CreateReferenceCollection();
- if (null == _referenceCollection) {
+ if (null == _referenceCollection)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull);
}
}
@@ -368,11 +418,13 @@ internal void AddWeakReference(object value, int tag) {
abstract public DbTransaction BeginTransaction(IsolationLevel il);
- virtual public void ChangeDatabase(string value) {
+ virtual public void ChangeDatabase(string value)
+ {
throw ADP.MethodNotImplemented("ChangeDatabase");
}
- internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory) {
+ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
+ {
// The implementation here is the implementation required for the
// "open" internal connections, since our own private "closed"
// singleton internal connection objects override this method to
@@ -419,13 +471,16 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac
// block doesn't really help because a ThreadAbort during the finally block
// would just refert the connection to a bad state.
// Open->Closed: guarantee internal connection is returned to correct pool
- if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this)) {
-
+ if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this))
+ {
+
// Lock to prevent race condition with cancellation
- lock (this) {
+ lock (this)
+ {
object lockToken = ObtainAdditionalLocksForClose();
- try {
+ try
+ {
PrepareForCloseConnection();
DbConnectionPool connectionPool = Pool;
@@ -436,17 +491,19 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac
// The singleton closed classes won't have owners and
// connection pools, and we won't want to put them back
// into the pool.
- if (null != connectionPool) {
+ if (null != connectionPool)
+ {
connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us...
// NOTE: Before we leave the PutObject call, another
// thread may have already popped the connection from
// the pool, so don't expect to be able to verify it.
}
- else {
+ else
+ {
Deactivate(); // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up...
PerformanceCounters.HardDisconnectsPerSecond.Increment();
-
+
// To prevent an endless recursion, we need to clear
// the owning object before we call dispose so that
// we can't get here a second time... Ordinarily, I
@@ -456,10 +513,12 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac
// certain.
_owningObject.Target = null;
- if (IsTransactionRoot) {
- SetInStasis();
+ if (IsTransactionRoot)
+ {
+ SetInStasis();
}
- else {
+ else
+ {
PerformanceCounters.NumberOfNonPooledConnections.Decrement();
if (this.GetType() != typeof(Microsoft.Data.SqlClient.SqlInternalConnectionSmi))
{
@@ -468,7 +527,8 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac
}
}
}
- finally {
+ finally
+ {
ReleaseAdditionalLocksForClose(lockToken);
// if a ThreadAbort puts us here then its possible the outer connection will not reference
// this and this will be orphaned, not reclaimed by object pool until outer connection goes out of scope.
@@ -478,29 +538,35 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac
}
}
- virtual internal void PrepareForReplaceConnection() {
+ virtual internal void PrepareForReplaceConnection()
+ {
// By default, there is no preperation required
}
- virtual protected void PrepareForCloseConnection() {
+ virtual protected void PrepareForCloseConnection()
+ {
// By default, there is no preperation required
}
- virtual protected object ObtainAdditionalLocksForClose() {
+ virtual protected object ObtainAdditionalLocksForClose()
+ {
return null; // no additional locks in default implementation
}
- virtual protected void ReleaseAdditionalLocksForClose(object lockToken) {
+ virtual protected void ReleaseAdditionalLocksForClose(object lockToken)
+ {
// no additional locks in default implementation
}
- virtual protected DbReferenceCollection CreateReferenceCollection() {
+ virtual protected DbReferenceCollection CreateReferenceCollection()
+ {
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject);
}
abstract protected void Deactivate();
- internal void DeactivateConnection() {
+ internal void DeactivateConnection()
+ {
// Internal method called from the connection pooler so we don't expose
// the Deactivate method publicly.
@@ -510,23 +576,27 @@ internal void DeactivateConnection() {
Debug.Assert(0 == activateCount, "activated multiple times?");
#endif // DEBUG
- if (PerformanceCounters != null) { // Pool.Clear will DestroyObject that will clean performanceCounters before going here
+ if (PerformanceCounters != null)
+ { // Pool.Clear will DestroyObject that will clean performanceCounters before going here
PerformanceCounters.NumberOfActiveConnections.Decrement();
}
- if (!_connectionIsDoomed && Pool.UseLoadBalancing) {
+ if (!_connectionIsDoomed && Pool.UseLoadBalancing)
+ {
// If we're not already doomed, check the connection's lifetime and
// doom it if it's lifetime has elapsed.
DateTime now = DateTime.UtcNow; // WebData 111116
- if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks) {
+ if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks)
+ {
DoNotPoolThisConnection();
}
}
Deactivate();
}
- virtual internal void DelegatedTransactionEnded() {
+ virtual internal void DelegatedTransactionEnded()
+ {
// Called by System.Transactions when the delegated transaction has
// completed. We need to make closed connections that are in stasis
// available again, or disposed closed/leaked non-pooled connections.
@@ -537,7 +607,8 @@ virtual internal void DelegatedTransactionEnded() {
Bid.Trace(" %d#, Delegated Transaction Completed.\n", ObjectID);
- if (1 == _pooledCount) {
+ if (1 == _pooledCount)
+ {
// When _pooledCount is 1, it indicates a closed, pooled,
// connection so it is ready to put back into the pool for
// general use.
@@ -548,18 +619,20 @@ virtual internal void DelegatedTransactionEnded() {
DbConnectionPool pool = Pool;
- if (null == pool) {
+ if (null == pool)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool
}
pool.PutObjectFromTransactedPool(this);
}
- else if (-1 == _pooledCount && !_owningObject.IsAlive) {
+ else if (-1 == _pooledCount && !_owningObject.IsAlive)
+ {
// When _pooledCount is -1 and the owning object no longer exists,
// it indicates a closed (or leaked), non-pooled connection so
// it is safe to dispose.
TerminateStasis(false);
-
+
Deactivate(); // call it one more time just in case
// it's a non-pooled connection, we need to dispose of it
@@ -592,35 +665,40 @@ public virtual void Dispose()
}
}
- protected internal void DoNotPoolThisConnection() {
+ protected internal void DoNotPoolThisConnection()
+ {
_cannotBePooled = true;
Bid.PoolerTrace(" %d#, Marking pooled object as non-poolable so it will be disposed\n", ObjectID);
}
/// Ensure that this connection cannot be put back into the pool.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- protected internal void DoomThisConnection() {
+ protected internal void DoomThisConnection()
+ {
_connectionIsDoomed = true;
Bid.PoolerTrace(" %d#, Dooming\n", ObjectID);
}
// Reset connection doomed status so it can be re-connected and pooled.
- protected internal void UnDoomThisConnection() {
+ protected internal void UnDoomThisConnection()
+ {
_connectionIsDoomed = false;
}
abstract public void EnlistTransaction(SysTx.Transaction transaction);
- virtual protected internal DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions){
- Debug.Assert(outerConnection != null,"outerConnection may not be null.");
+ virtual protected internal DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions)
+ {
+ Debug.Assert(outerConnection != null, "outerConnection may not be null.");
DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this);
- Debug.Assert(metaDataFactory != null,"metaDataFactory may not be null.");
+ Debug.Assert(metaDataFactory != null, "metaDataFactory may not be null.");
- return metaDataFactory.GetSchema(outerConnection, collectionName,restrictions);
+ return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions);
}
- internal void MakeNonPooledObject(object owningObject, DbConnectionPoolCounters performanceCounters) {
+ internal void MakeNonPooledObject(object owningObject, DbConnectionPoolCounters performanceCounters)
+ {
// Used by DbConnectionFactory to indicate that this object IS NOT part of
// a connection pool.
@@ -630,7 +708,8 @@ internal void MakeNonPooledObject(object owningObject, DbConnectionPoolCounters
_pooledCount = -1;
}
- internal void MakePooledConnection(DbConnectionPool connectionPool) {
+ internal void MakePooledConnection(DbConnectionPool connectionPool)
+ {
// Used by DbConnectionFactory to indicate that this object IS part of
// a connection pool.
@@ -641,15 +720,19 @@ internal void MakePooledConnection(DbConnectionPool connectionPool) {
_performanceCounters = connectionPool.PerformanceCounters;
}
- internal void NotifyWeakReference(int message) {
+ internal void NotifyWeakReference(int message)
+ {
DbReferenceCollection referenceCollection = ReferenceCollection;
- if (null != referenceCollection) {
+ if (null != referenceCollection)
+ {
referenceCollection.Notify(message);
}
}
- internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) {
- if (!TryOpenConnection(outerConnection, connectionFactory, null, null)) {
+ internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
+ {
+ if (!TryOpenConnection(outerConnection, connectionFactory, null, null))
+ {
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
@@ -659,30 +742,38 @@ internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionF
/// override this and do the correct thing.
// User code should either override DbConnectionInternal.Activate when it comes out of the pool
// or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections
- internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) {
+ internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions)
+ {
throw ADP.ConnectionAlreadyOpen(State);
}
- internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) {
+ internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions)
+ {
throw ADP.MethodNotImplemented("TryReplaceConnection");
}
- protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions) {
+ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions)
+ {
// ?->Connecting: prevent set_ConnectionString during Open
- if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) {
+ if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this))
+ {
DbConnectionInternal openConnection = null;
- try {
+ try
+ {
connectionFactory.PermissionDemand(outerConnection);
- if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection)) {
+ if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection))
+ {
return false;
}
}
- catch {
+ catch
+ {
// This should occure for all exceptions, even ADP.UnCatchableExceptions.
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw;
}
- if (null == openConnection) {
+ if (null == openConnection)
+ {
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull);
}
@@ -692,7 +783,8 @@ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnect
return true;
}
- internal void PrePush(object expectedOwner) {
+ internal void PrePush(object expectedOwner)
+ {
// Called by DbConnectionPool when we're about to be put into it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
@@ -701,18 +793,23 @@ internal void PrePush(object expectedOwner) {
// ReclaimEmancipatedObjects.
//3 // The following tests are retail assertions of things we can't allow to happen.
- if (null == expectedOwner) {
- if (null != _owningObject.Target) {
+ if (null == expectedOwner)
+ {
+ if (null != _owningObject.Target)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner); // new unpooled object has an owner
}
}
- else if (_owningObject.Target != expectedOwner) {
+ else if (_owningObject.Target != expectedOwner)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); // unpooled object has incorrect owner
}
- if (0 != _pooledCount) {
+ if (0 != _pooledCount)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time
}
- if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
+ if (Bid.IsOn(DbConnectionPool.PoolerTracePoints))
+ {
//DbConnection x = (expectedOwner as DbConnection);
Bid.PoolerTrace(" %d#, Preparing to push into pool, owning connection %d#, pooledCount=%d\n", ObjectID, 0, _pooledCount);
}
@@ -720,12 +817,13 @@ internal void PrePush(object expectedOwner) {
_owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2%
}
- internal void PostPop(object newOwner) {
+ internal void PostPop(object newOwner)
+ {
// Called by DbConnectionPool right after it pulls this from it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
- Debug.Assert(!IsEmancipated,"pooled object not in pool");
-
+ Debug.Assert(!IsEmancipated, "pooled object not in pool");
+
// SQLBUDT #356871 -- When another thread is clearing this pool, it
// will doom all connections in this pool without prejudice which
// causes the following assert to fire, which really mucks up stress
@@ -737,29 +835,36 @@ internal void PostPop(object newOwner) {
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
- if (null != _owningObject.Target) {
+ if (null != _owningObject.Target)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner); // pooled connection already has an owner!
}
_owningObject.Target = newOwner;
_pooledCount--;
- if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
+ if (Bid.IsOn(DbConnectionPool.PoolerTracePoints))
+ {
//DbConnection x = (newOwner as DbConnection);
Bid.PoolerTrace(" %d#, Preparing to pop from pool, owning connection %d#, pooledCount=%d\n", ObjectID, 0, _pooledCount);
}
//3 // The following tests are retail assertions of things we can't allow to happen.
- if (null != Pool) {
- if (0 != _pooledCount) {
+ if (null != Pool)
+ {
+ if (0 != _pooledCount)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
- else if (-1 != _pooledCount) {
+ else if (-1 != _pooledCount)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
- internal void RemoveWeakReference(object value) {
+ internal void RemoveWeakReference(object value)
+ {
DbReferenceCollection referenceCollection = ReferenceCollection;
- if (null != referenceCollection) {
+ if (null != referenceCollection)
+ {
referenceCollection.Remove(value);
}
}
@@ -767,43 +872,54 @@ internal void RemoveWeakReference(object value) {
// Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
// This is a separate method because cleanup can be triggered in multiple ways for a delegated
// transaction.
- virtual protected void CleanupTransactionOnCompletion(SysTx.Transaction transaction) {
+ virtual protected void CleanupTransactionOnCompletion(SysTx.Transaction transaction)
+ {
}
- internal void DetachCurrentTransactionIfEnded() {
+ internal void DetachCurrentTransactionIfEnded()
+ {
SysTx.Transaction enlistedTransaction = EnlistedTransaction;
- if (enlistedTransaction != null) {
+ if (enlistedTransaction != null)
+ {
bool transactionIsDead;
- try {
+ try
+ {
transactionIsDead = (SysTx.TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status);
}
- catch (SysTx.TransactionException) {
+ catch (SysTx.TransactionException)
+ {
// If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception)
transactionIsDead = true;
}
- if (transactionIsDead) {
+ if (transactionIsDead)
+ {
DetachTransaction(enlistedTransaction, true);
}
}
}
// Detach transaction from connection.
- internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) {
+ internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing)
+ {
Bid.Trace(" %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount);
// potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new
// transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should
// be the exception, not the rule.
- lock (this) {
+ lock (this)
+ {
// Detach if detach-on-end behavior, or if outer connection was closed
DbConnection owner = (DbConnection)Owner;
- if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner) {
+ if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner)
+ {
SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
- if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction)) {
+ if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction))
+ {
EnlistedTransaction = null;
- if (IsTxRootWaitingForTxEnd) {
+ if (IsTxRootWaitingForTxEnd)
+ {
DelegatedTransactionEnded();
}
}
@@ -812,16 +928,19 @@ internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitly
}
// Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with
- internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transaction) {
+ internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transaction)
+ {
DetachTransaction(transaction, false);
DbConnectionPool pool = Pool;
- if (null != pool) {
+ if (null != pool)
+ {
pool.TransactionEnded(transaction, this);
}
}
- void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) {
+ void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e)
+ {
SysTx.Transaction transaction = e.Transaction;
Bid.Trace(" %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount);
@@ -833,22 +952,27 @@ void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) {
// TODO: Review whether we need the unmanaged code permission when we have the new object model available.
- [SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.UnmanagedCode)]
- private void TransactionOutcomeEnlist(SysTx.Transaction transaction) {
+ [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
+ private void TransactionOutcomeEnlist(SysTx.Transaction transaction)
+ {
transaction.TransactionCompleted += new SysTx.TransactionCompletedEventHandler(TransactionCompletedEvent);
}
- internal void SetInStasis() {
+ internal void SetInStasis()
+ {
_isInStasis = true;
Bid.PoolerTrace(" %d#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.\n", ObjectID);
PerformanceCounters.NumberOfStasisConnections.Increment();
}
- private void TerminateStasis(bool returningToPool) {
- if (returningToPool) {
+ private void TerminateStasis(bool returningToPool)
+ {
+ if (returningToPool)
+ {
Bid.PoolerTrace(" %d#, Delegated Transaction has ended, connection is closed. Returning to general pool.\n", ObjectID);
}
- else {
+ else
+ {
Bid.PoolerTrace(" %d#, Delegated Transaction has ended, connection is closed/leaked. Disposing.\n", ObjectID);
}
PerformanceCounters.NumberOfStasisConnections.Decrement();
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs
index 45c47e33a4..3d023597d3 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs
@@ -2,31 +2,29 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
- using System.Collections;
+ using System.Collections.Concurrent;
using System.Collections.Generic;
- using Microsoft.Data.Common;
- using Microsoft.Data.SqlClient;
+ using System.Data.Common;
using System.Diagnostics;
- using System.Globalization;
+ using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
- using System.Security;
- using System.Security.Permissions;
- using System.Security.Principal;
+ using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
+ using Microsoft.Data.Common;
+ using Microsoft.Data.SqlClient;
using SysTx = System.Transactions;
- using System.Runtime.Versioning;
- using System.Diagnostics.CodeAnalysis;
- using System.Collections.Concurrent;
- using System.Data.Common;
- sealed internal class DbConnectionPool {
- private enum State {
+ sealed internal class DbConnectionPool
+ {
+ private enum State
+ {
Initializing,
Running,
ShuttingDown,
@@ -37,21 +35,27 @@ private enum State {
// This class is a way to stash our cloned Tx key for later disposal when it's no longer needed.
// We can't get at the key in the dictionary without enumerating entries, so we stash an extra
// copy as part of the value.
- sealed private class TransactedConnectionList : List {
+ sealed private class TransactedConnectionList : List
+ {
private SysTx.Transaction _transaction;
- internal TransactedConnectionList(int initialAllocation, SysTx.Transaction tx) : base(initialAllocation) {
+ internal TransactedConnectionList(int initialAllocation, SysTx.Transaction tx) : base(initialAllocation)
+ {
_transaction = tx;
}
- internal void Dispose() {
- if (null != _transaction) {
+ internal void Dispose()
+ {
+ if (null != _transaction)
+ {
_transaction.Dispose();
}
}
}
- sealed class PendingGetConnection {
- public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion, DbConnectionOptions userOptions) {
+ sealed class PendingGetConnection
+ {
+ public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion, DbConnectionOptions userOptions)
+ {
DueTime = dueTime;
Owner = owner;
Completion = completion;
@@ -63,7 +67,7 @@ public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSour
public DbConnectionOptions UserOptions { get; private set; }
}
- sealed private class TransactedConnectionPool
+ sealed private class TransactedConnectionPool
{
Dictionary _transactedCxns;
@@ -78,24 +82,28 @@ internal TransactedConnectionPool(DbConnectionPool pool)
Debug.Assert(null != pool, "null pool?");
_pool = pool;
- _transactedCxns = new Dictionary ();
-
+ _transactedCxns = new Dictionary();
+
Bid.PoolerTrace(" %d#, Constructed for connection pool %d#\n", ObjectID, _pool.ObjectID);
}
- internal int ObjectID {
- get {
+ internal int ObjectID
+ {
+ get
+ {
return _objectID;
}
}
- internal DbConnectionPool Pool {
- get {
+ internal DbConnectionPool Pool
+ {
+ get
+ {
return _pool;
}
}
- internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction)
+ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction)
{
Debug.Assert(null != transaction, "null transaction?");
@@ -103,10 +111,10 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction)
TransactedConnectionList connections;
bool txnFound = false;
-
+
lock (_transactedCxns)
{
- txnFound = _transactedCxns.TryGetValue ( transaction, out connections );
+ txnFound = _transactedCxns.TryGetValue(transaction, out connections);
}
// NOTE: GetTransactedObject is only used when AutoEnlist = True and the ambient transaction
@@ -118,11 +126,11 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction)
// connection is probably better than unnecessarily locking
if (txnFound)
{
- Debug.Assert ( connections != null );
+ Debug.Assert(connections != null);
// synchronize multi-threaded access with PutTransactedObject (TransactionEnded should
// not be a concern, see comments above)
- lock ( connections )
+ lock (connections)
{
int i = connections.Count - 1;
if (0 <= i)
@@ -133,31 +141,33 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction)
}
}
- if (null != transactedObject) {
+ if (null != transactedObject)
+ {
Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Popped.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID);
}
return transactedObject;
}
- internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInternal transactedObject) {
+ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInternal transactedObject)
+ {
Debug.Assert(null != transaction, "null transaction?");
Debug.Assert(null != transactedObject, "null transactedObject?");
TransactedConnectionList connections;
bool txnFound = false;
-
+
// NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee
// around the order in which PutTransactionObject and TransactionEnded are called.
- lock ( _transactedCxns )
+ lock (_transactedCxns)
{
// Check if a transacted pool has been created for this transaction
- if ( txnFound = _transactedCxns.TryGetValue ( transaction, out connections ) )
+ if (txnFound = _transactedCxns.TryGetValue(transaction, out connections))
{
- Debug.Assert ( connections != null );
+ Debug.Assert(connections != null);
// synchronize multi-threaded access with GetTransactedObject
- lock ( connections )
+ lock (connections)
{
Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?");
Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Pushing.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID);
@@ -169,19 +179,19 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt
// CONSIDER: the following code is more complicated than it needs to be to avoid cloning the
// transaction and allocating memory within a lock. Is that complexity really necessary?
- if ( !txnFound )
+ if (!txnFound)
{
// create the transacted pool, making sure to clone the associated transaction
// for use as a key in our internal dictionary of transactions and connections
SysTx.Transaction transactionClone = null;
TransactedConnectionList newConnections = null;
-
- try
+
+ try
{
transactionClone = transaction.Clone();
newConnections = new TransactedConnectionList(2, transactionClone); // start with only two connections in the list; most times we won't need that many.
- lock ( _transactedCxns )
+ lock (_transactedCxns)
{
// NOTE: in the interim between the locks on the transacted pool (this) during
// execution of this method, another thread (threadB) may have attempted to
@@ -190,10 +200,10 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt
// transacted pool while threadA was processing the above instructions.
if (txnFound = _transactedCxns.TryGetValue(transaction, out connections))
{
- Debug.Assert ( connections != null );
-
+ Debug.Assert(connections != null);
+
// synchronize multi-threaded access with GetTransactedObject
- lock ( connections )
+ lock (connections)
{
Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?");
Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Pushing.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID);
@@ -206,18 +216,18 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt
Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Adding List to transacted pool.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID);
// add the connection/transacted object to the list
- newConnections.Add ( transactedObject );
-
+ newConnections.Add(transactedObject);
+
_transactedCxns.Add(transactionClone, newConnections);
transactionClone = null; // we've used it -- don't throw it or the TransactedConnectionList that references it away.
}
}
}
- finally
+ finally
{
if (null != transactionClone)
{
- if ( newConnections != null )
+ if (newConnections != null)
{
// another thread created the transaction pool and thus the new
// TransactedConnectionList was not used, so dispose of it and
@@ -231,20 +241,20 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt
}
}
}
- Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Added.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID );
+ Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Added.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID);
}
Pool.PerformanceCounters.NumberOfFreeConnections.Increment();
}
- internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject)
+ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject)
{
Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Transaction Completed\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID);
TransactedConnectionList connections;
int entry = -1;
-
+
// NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee
// around the order in which PutTransactionObject and TransactionEnded are called. As
// such, it is possible that the transaction does not yet have a pool created.
@@ -253,20 +263,20 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern
// TODO: that the pending creation of a transacted pool for this transaction is aborted when
// TODO: PutTransactedObject finally gets some CPU time?
- lock ( _transactedCxns )
+ lock (_transactedCxns)
{
- if (_transactedCxns.TryGetValue(transaction, out connections))
+ if (_transactedCxns.TryGetValue(transaction, out connections))
{
- Debug.Assert ( connections != null );
+ Debug.Assert(connections != null);
bool shouldDisposeConnections = false;
// Lock connections to avoid conflict with GetTransactionObject
- lock (connections)
+ lock (connections)
{
entry = connections.IndexOf(transactedObject);
- if ( entry >= 0 )
+ if (entry >= 0)
{
connections.RemoveAt(entry);
}
@@ -284,20 +294,21 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern
}
}
- if (shouldDisposeConnections) {
+ if (shouldDisposeConnections)
+ {
connections.Dispose();
}
}
else
{
//Debug.Assert ( false, "TransactionCompletedEvent fired before PutTransactedObject put the connection in the transacted pool." );
- Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID );
+ Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID);
}
}
-
+
// If (and only if) we found the connection in the list of
// connections, we'll put it back...
- if (0 <= entry)
+ if (0 <= entry)
{
Pool.PerformanceCounters.NumberOfFreeConnections.Decrement();
Pool.PutObjectFromTransactedPool(transactedObject);
@@ -305,8 +316,9 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern
}
}
-
- private sealed class PoolWaitHandles : DbBuffer {
+
+ private sealed class PoolWaitHandles : DbBuffer
+ {
private readonly Semaphore _poolSemaphore;
private readonly ManualResetEvent _errorEvent;
@@ -324,18 +336,20 @@ private sealed class PoolWaitHandles : DbBuffer {
[ResourceExposure(ResourceScope.None)] // SxS: this method does not create named objects
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
- internal PoolWaitHandles() : base(3*IntPtr.Size) {
+ internal PoolWaitHandles() : base(3 * IntPtr.Size)
+ {
bool mustRelease1 = false, mustRelease2 = false, mustRelease3 = false;
-
+
_poolSemaphore = new Semaphore(0, MAX_Q_SIZE);
_errorEvent = new ManualResetEvent(false);
_creationSemaphore = new Semaphore(1, 1);
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
// because SafeWaitHandle doesn't have reliability contract
- _poolHandle = _poolSemaphore.SafeWaitHandle;
- _errorHandle = _errorEvent.SafeWaitHandle;
+ _poolHandle = _poolSemaphore.SafeWaitHandle;
+ _errorHandle = _errorEvent.SafeWaitHandle;
_creationHandle = _creationSemaphore.SafeWaitHandle;
_poolHandle.DangerousAddRef(ref mustRelease1);
@@ -346,90 +360,102 @@ internal PoolWaitHandles() : base(3*IntPtr.Size) {
Debug.Assert(1 == ERROR_HANDLE, "ERROR_HANDLE");
Debug.Assert(2 == CREATION_HANDLE, "CREATION_HANDLE");
- WriteIntPtr(SEMAPHORE_HANDLE*IntPtr.Size, _poolHandle.DangerousGetHandle());
- WriteIntPtr(ERROR_HANDLE*IntPtr.Size, _errorHandle.DangerousGetHandle());
- WriteIntPtr(CREATION_HANDLE*IntPtr.Size, _creationHandle.DangerousGetHandle());
+ WriteIntPtr(SEMAPHORE_HANDLE * IntPtr.Size, _poolHandle.DangerousGetHandle());
+ WriteIntPtr(ERROR_HANDLE * IntPtr.Size, _errorHandle.DangerousGetHandle());
+ WriteIntPtr(CREATION_HANDLE * IntPtr.Size, _creationHandle.DangerousGetHandle());
}
- finally {
- if (mustRelease1) {
+ finally
+ {
+ if (mustRelease1)
+ {
_releaseFlags |= 1;
}
- if (mustRelease2) {
+ if (mustRelease2)
+ {
_releaseFlags |= 2;
}
- if (mustRelease3) {
+ if (mustRelease3)
+ {
_releaseFlags |= 4;
}
}
}
-
- internal SafeHandle CreationHandle {
+
+ internal SafeHandle CreationHandle
+ {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get { return _creationHandle; }
}
- internal Semaphore CreationSemaphore {
+ internal Semaphore CreationSemaphore
+ {
get { return _creationSemaphore; }
}
- internal ManualResetEvent ErrorEvent {
+ internal ManualResetEvent ErrorEvent
+ {
get { return _errorEvent; }
}
- internal Semaphore PoolSemaphore {
+ internal Semaphore PoolSemaphore
+ {
get { return _poolSemaphore; }
}
- protected override bool ReleaseHandle() {
+ protected override bool ReleaseHandle()
+ {
// NOTE: The SafeHandle class guarantees this will be called exactly once.
// we know we can touch these other managed objects because of our original DangerousAddRef
- if (0 != (1 & _releaseFlags)) {
+ if (0 != (1 & _releaseFlags))
+ {
_poolHandle.DangerousRelease();
}
- if (0 != (2 & _releaseFlags)) {
+ if (0 != (2 & _releaseFlags))
+ {
_errorHandle.DangerousRelease();
}
- if (0 != (4 & _releaseFlags)) {
+ if (0 != (4 & _releaseFlags))
+ {
_creationHandle.DangerousRelease();
}
return base.ReleaseHandle();
}
}
- private const int MAX_Q_SIZE = (int)0x00100000;
+ private const int MAX_Q_SIZE = (int)0x00100000;
// The order of these is important; we want the WaitAny call to be signaled
// for a free object before a creation signal. Only the index first signaled
// object is returned from the WaitAny call.
private const int SEMAPHORE_HANDLE = (int)0x0;
- private const int ERROR_HANDLE = (int)0x1;
- private const int CREATION_HANDLE = (int)0x2;
- private const int BOGUS_HANDLE = (int)0x3;
+ private const int ERROR_HANDLE = (int)0x1;
+ private const int CREATION_HANDLE = (int)0x2;
+ private const int BOGUS_HANDLE = (int)0x3;
private const int WAIT_OBJECT_0 = 0;
- private const int WAIT_TIMEOUT = (int)0x102;
+ private const int WAIT_TIMEOUT = (int)0x102;
private const int WAIT_ABANDONED = (int)0x80;
- private const int WAIT_FAILED = -1;
+ private const int WAIT_FAILED = -1;
private const int ERROR_WAIT_DEFAULT = 5 * 1000; // 5 seconds
// we do want a testable, repeatable set of generated random numbers
private static readonly Random _random = new Random(5101977); // Value obtained from Dave Driver
- private readonly int _cleanupWait;
+ private readonly int _cleanupWait;
private readonly DbConnectionPoolIdentity _identity;
- private readonly DbConnectionFactory _connectionFactory;
- private readonly DbConnectionPoolGroup _connectionPoolGroup;
+ private readonly DbConnectionFactory _connectionFactory;
+ private readonly DbConnectionPoolGroup _connectionPoolGroup;
private readonly DbConnectionPoolGroupOptions _connectionPoolGroupOptions;
- private DbConnectionPoolProviderInfo _connectionPoolProviderInfo;
+ private DbConnectionPoolProviderInfo _connectionPoolProviderInfo;
///
/// The private member which carries the set of authenticationcontexts for this pool (based on the user's identity).
///
private readonly ConcurrentDictionary _pooledDbAuthenticationContexts;
- private State _state;
+ private State _state;
private readonly ConcurrentStack _stackOld = new ConcurrentStack();
private readonly ConcurrentStack _stackNew = new ConcurrentStack();
@@ -437,23 +463,23 @@ protected override bool ReleaseHandle() {
private readonly ConcurrentQueue _pendingOpens = new ConcurrentQueue();
private int _pendingOpensWaiting = 0;
- private readonly WaitCallback _poolCreateRequest;
+ private readonly WaitCallback _poolCreateRequest;
- private int _waitCount;
- private readonly PoolWaitHandles _waitHandles;
+ private int _waitCount;
+ private readonly PoolWaitHandles _waitHandles;
- private Exception _resError;
- private volatile bool _errorOccurred;
+ private Exception _resError;
+ private volatile bool _errorOccurred;
- private int _errorWait;
- private Timer _errorTimer;
+ private int _errorWait;
+ private Timer _errorTimer;
- private Timer _cleanupTimer;
+ private Timer _cleanupTimer;
private readonly TransactedConnectionPool _transactedConnectionPool;
private readonly List _objectList;
- private int _totalObjects;
+ private int _totalObjects;
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
@@ -463,18 +489,21 @@ internal DbConnectionPool(
DbConnectionFactory connectionFactory,
DbConnectionPoolGroup connectionPoolGroup,
DbConnectionPoolIdentity identity,
- DbConnectionPoolProviderInfo connectionPoolProviderInfo ) {
+ DbConnectionPoolProviderInfo connectionPoolProviderInfo)
+ {
Debug.Assert(ADP.IsWindowsNT, "Attempting to construct a connection pool on Win9x?");
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup");
- if ((null != identity) && identity.IsRestricted) {
+ if ((null != identity) && identity.IsRestricted)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken);
}
- _state= State.Initializing;
+ _state = State.Initializing;
- lock(_random) { // Random.Next is not thread-safe
- _cleanupWait = _random.Next(12, 24)*10*1000; // 2-4 minutes in 10 sec intervals, WebData 103603
+ lock (_random)
+ { // Random.Next is not thread-safe
+ _cleanupWait = _random.Next(12, 24) * 10 * 1000; // 2-4 minutes in 10 sec intervals, WebData 103603
}
_connectionFactory = connectionFactory;
@@ -485,15 +514,16 @@ internal DbConnectionPool(
_waitHandles = new PoolWaitHandles();
- _errorWait = ERROR_WAIT_DEFAULT;
- _errorTimer = null; // No error yet.
+ _errorWait = ERROR_WAIT_DEFAULT;
+ _errorTimer = null; // No error yet.
- _objectList = new List(MaxPoolSize);
+ _objectList = new List(MaxPoolSize);
_pooledDbAuthenticationContexts = new ConcurrentDictionary(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/,
capacity: 2);
- if(ADP.IsPlatformNT5) {
+ if (ADP.IsPlatformNT5)
+ {
_transactedConnectionPool = new TransactedConnectionPool(this);
}
@@ -506,32 +536,40 @@ internal DbConnectionPool(
// StartBackgroundCallbacks after pool is actually in the collection
}
- private int CreationTimeout {
+ private int CreationTimeout
+ {
get { return PoolGroupOptions.CreationTimeout; }
}
- internal int Count {
+ internal int Count
+ {
get { return _totalObjects; }
}
- internal DbConnectionFactory ConnectionFactory {
+ internal DbConnectionFactory ConnectionFactory
+ {
get { return _connectionFactory; }
}
- internal bool ErrorOccurred {
+ internal bool ErrorOccurred
+ {
get { return _errorOccurred; }
}
- private bool HasTransactionAffinity {
+ private bool HasTransactionAffinity
+ {
get { return PoolGroupOptions.HasTransactionAffinity; }
}
- internal TimeSpan LoadBalanceTimeout {
+ internal TimeSpan LoadBalanceTimeout
+ {
get { return PoolGroupOptions.LoadBalanceTimeout; }
}
- private bool NeedToReplenish {
- get {
+ private bool NeedToReplenish
+ {
+ get
+ {
if (State.Running != _state) // SQL BU DT 364595 - don't allow connection create when not running.
return false;
@@ -543,49 +581,59 @@ private bool NeedToReplenish {
if (totalObjects < MinPoolSize)
return true;
- int freeObjects = (_stackNew.Count + _stackOld.Count);
- int waitingRequests = _waitCount;
+ int freeObjects = (_stackNew.Count + _stackOld.Count);
+ int waitingRequests = _waitCount;
bool needToReplenish = (freeObjects < waitingRequests) || ((freeObjects == waitingRequests) && (totalObjects > 1));
return needToReplenish;
}
}
- internal DbConnectionPoolIdentity Identity {
+ internal DbConnectionPoolIdentity Identity
+ {
get { return _identity; }
}
-
- internal bool IsRunning {
+
+ internal bool IsRunning
+ {
get { return State.Running == _state; }
}
- private int MaxPoolSize {
+ private int MaxPoolSize
+ {
get { return PoolGroupOptions.MaxPoolSize; }
}
- private int MinPoolSize {
+ private int MinPoolSize
+ {
get { return PoolGroupOptions.MinPoolSize; }
}
- internal int ObjectID {
- get {
+ internal int ObjectID
+ {
+ get
+ {
return _objectID;
}
}
- internal DbConnectionPoolCounters PerformanceCounters {
+ internal DbConnectionPoolCounters PerformanceCounters
+ {
get { return _connectionFactory.PerformanceCounters; }
}
- internal DbConnectionPoolGroup PoolGroup {
+ internal DbConnectionPoolGroup PoolGroup
+ {
get { return _connectionPoolGroup; }
}
- internal DbConnectionPoolGroupOptions PoolGroupOptions {
+ internal DbConnectionPoolGroupOptions PoolGroupOptions
+ {
get { return _connectionPoolGroupOptions; }
}
- internal DbConnectionPoolProviderInfo ProviderInfo {
+ internal DbConnectionPoolProviderInfo ProviderInfo
+ {
get { return _connectionPoolProviderInfo; }
}
@@ -600,15 +648,18 @@ internal ConcurrentDictionary %d#\n", ObjectID);
// Destroy free objects that put us above MinPoolSize from old stack.
- while(Count > MinPoolSize) { // While above MinPoolSize...
+ while (Count > MinPoolSize)
+ { // While above MinPoolSize...
- if (_waitHandles.PoolSemaphore.WaitOne(0, false) /* != WAIT_TIMEOUT */) {
+ if (_waitHandles.PoolSemaphore.WaitOne(0, false) /* != WAIT_TIMEOUT */)
+ {
// We obtained a objects from the semaphore.
DbConnectionInternal obj;
- if (_stackOld.TryPop(out obj)) {
+ if (_stackOld.TryPop(out obj))
+ {
Debug.Assert(obj != null, "null connection is not expected");
// If we obtained one from the old stack, destroy it.
PerformanceCounters.NumberOfFreeConnections.Decrement();
// Transaction roots must survive even aging out (TxEnd event will clean them up).
bool shouldDestroy = true;
- lock (obj) { // Lock to prevent race condition window between IsTransactionRoot and shouldDestroy assignment
- if (obj.IsTransactionRoot) {
+ lock (obj)
+ { // Lock to prevent race condition window between IsTransactionRoot and shouldDestroy assignment
+ if (obj.IsTransactionRoot)
+ {
shouldDestroy = false;
}
}
@@ -662,29 +718,35 @@ private void CleanupCallback(Object state) {
// we don't want to do under this lock, if possible. It should be possible to eliminate this race condition with
// more substantial re-architecture of the pool, but we don't have the time to do that work for the current release.
- if (shouldDestroy) {
+ if (shouldDestroy)
+ {
DestroyObject(obj);
}
- else {
+ else
+ {
obj.SetInStasis();
}
}
- else {
+ else
+ {
// Else we exhausted the old stack (the object the
// semaphore represents is on the new stack), so break.
_waitHandles.PoolSemaphore.Release(1);
break;
}
}
- else {
+ else
+ {
break;
}
}
// Push to the old-stack. For each free object, move object from
// new stack to old stack.
- if(_waitHandles.PoolSemaphore.WaitOne(0, false) /* != WAIT_TIMEOUT */) {
- for(;;) {
+ if (_waitHandles.PoolSemaphore.WaitOne(0, false) /* != WAIT_TIMEOUT */)
+ {
+ for (; ; )
+ {
DbConnectionInternal obj;
if (!_stackNew.TryPop(out obj))
@@ -695,7 +757,7 @@ private void CleanupCallback(Object state) {
Bid.PoolerTrace(" %d#, ChangeStacks=%d#\n", ObjectID, obj.ObjectID);
Debug.Assert(!obj.IsEmancipated, "pooled object not in pool");
- Debug.Assert(obj.CanBePooled, "pooled object is not poolable");
+ Debug.Assert(obj.CanBePooled, "pooled object is not poolable");
_stackOld.Push(obj);
}
@@ -706,31 +768,37 @@ private void CleanupCallback(Object state) {
QueuePoolCreateRequest();
}
- internal void Clear() {
+ internal void Clear()
+ {
Bid.PoolerTrace(" %d#, Clearing.\n", ObjectID);
DbConnectionInternal obj;
// First, quickly doom everything.
- lock(_objectList) {
+ lock (_objectList)
+ {
int count = _objectList.Count;
- for (int i = 0; i < count; ++i) {
+ for (int i = 0; i < count; ++i)
+ {
obj = _objectList[i];
- if (null != obj) {
+ if (null != obj)
+ {
obj.DoNotPoolThisConnection();
}
}
}
// Second, dispose of all the free connections.
- while (_stackNew.TryPop(out obj)) {
+ while (_stackNew.TryPop(out obj))
+ {
Debug.Assert(obj != null, "null connection is not expected");
PerformanceCounters.NumberOfFreeConnections.Decrement();
DestroyObject(obj);
}
- while (_stackOld.TryPop(out obj)) {
+ while (_stackOld.TryPop(out obj))
+ {
Debug.Assert(obj != null, "null connection is not expected");
PerformanceCounters.NumberOfFreeConnections.Decrement();
DestroyObject(obj);
@@ -743,7 +811,8 @@ internal void Clear() {
Bid.PoolerTrace(" %d#, Cleared.\n", ObjectID);
}
- private Timer CreateCleanupTimer() {
+ private Timer CreateCleanupTimer()
+ {
return (new Timer(new TimerCallback(this.CleanupCallback), null, _cleanupWait, _cleanupWait));
}
@@ -760,48 +829,54 @@ private bool IsBlockingPeriodEnabled()
switch (policy)
{
case PoolBlockingPeriod.Auto:
- {
- if (ADP.IsAzureSqlServerEndpoint(poolGroupConnectionOptions.DataSource))
{
- return false; // in Azure it will be Disabled
+ if (ADP.IsAzureSqlServerEndpoint(poolGroupConnectionOptions.DataSource))
+ {
+ return false; // in Azure it will be Disabled
+ }
+ else
+ {
+ return true; // in Non Azure, it will be Enabled
+ }
}
- else
+ case PoolBlockingPeriod.AlwaysBlock:
{
- return true; // in Non Azure, it will be Enabled
+ return true; //Enabled
}
- }
- case PoolBlockingPeriod.AlwaysBlock:
- {
- return true; //Enabled
- }
case PoolBlockingPeriod.NeverBlock:
- {
- return false; //Disabled
- }
+ {
+ return false; //Disabled
+ }
default:
- {
- //we should never get into this path.
- Debug.Fail("Unknown PoolBlockingPeriod. Please specify explicit results in above switch case statement.");
- return true;
- }
+ {
+ //we should never get into this path.
+ Debug.Fail("Unknown PoolBlockingPeriod. Please specify explicit results in above switch case statement.");
+ return true;
+ }
}
}
- private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) {
+ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
+ {
DbConnectionInternal newObj = null;
- try {
+ try
+ {
newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions);
- if (null == newObj) {
+ if (null == newObj)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object
}
- if (!newObj.CanBePooled) {
+ if (!newObj.CanBePooled)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.NewObjectCannotBePooled); // CreateObject succeeded, but non-poolable object
}
newObj.PrePush(null);
- lock (_objectList) {
- if ((oldConnection != null) && (oldConnection.Pool == this)) {
+ lock (_objectList)
+ {
+ if ((oldConnection != null) && (oldConnection.Pool == this))
+ {
_objectList.Remove(oldConnection);
}
_objectList.Add(newObj);
@@ -810,11 +885,14 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio
}
// If the old connection belonged to another pool, we need to remove it from that
- if (oldConnection != null) {
+ if (oldConnection != null)
+ {
var oldConnectionPool = oldConnection.Pool;
- if (oldConnectionPool != null && oldConnectionPool != this) {
+ if (oldConnectionPool != null && oldConnectionPool != this)
+ {
Debug.Assert(oldConnectionPool._state == State.ShuttingDown, "Old connections pool should be shutting down");
- lock (oldConnectionPool._objectList) {
+ lock (oldConnectionPool._objectList)
+ {
oldConnectionPool._objectList.Remove(oldConnection);
oldConnectionPool._totalObjects = oldConnectionPool._objectList.Count;
}
@@ -825,9 +903,11 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio
// Reset the error wait:
_errorWait = ERROR_WAIT_DEFAULT;
}
- catch(Exception e) {
+ catch (Exception e)
+ {
// UNDONE - should not be catching all exceptions!!!
- if (!ADP.IsCatchableExceptionType(e)) {
+ if (!ADP.IsCatchableExceptionType(e))
+ {
throw;
}
@@ -848,10 +928,13 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio
Timer t = new Timer(new TimerCallback(this.ErrorCallback), null, Timeout.Infinite, Timeout.Infinite);
bool timerIsNotDisposed;
RuntimeHelpers.PrepareConstrainedRegions();
- try{} finally {
- _waitHandles.ErrorEvent.Set();
+ try
+ { }
+ finally
+ {
+ _waitHandles.ErrorEvent.Set();
_errorOccurred = true;
-
+
// Enable the timer.
// Note that the timer is created to allow periodic invocation. If ThreadAbort occurs in the middle of ErrorCallback,
// the timer will restart. Otherwise, the timer callback (ErrorCallback) destroys the timer after resetting the error to avoid second callback.
@@ -861,10 +944,12 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio
Debug.Assert(timerIsNotDisposed, "ErrorCallback timer has been disposed");
- if (30000 < _errorWait) {
+ if (30000 < _errorWait)
+ {
_errorWait = 60000;
}
- else {
+ else
+ {
_errorWait *= 2;
}
throw;
@@ -872,17 +957,17 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio
return newObj;
}
- private void DeactivateObject(DbConnectionInternal obj)
+ private void DeactivateObject(DbConnectionInternal obj)
{
Bid.PoolerTrace(" %d#, Connection %d#, Deactivating.\n", ObjectID, obj.ObjectID);
obj.DeactivateConnection(); // we presume this operation is safe outside of a lock...
-
+
bool returnToGeneralPool = false;
bool destroyObject = false;
bool rootTxn = false;
-
- if ( obj.IsConnectionDoomed )
+
+ if (obj.IsConnectionDoomed)
{
// the object is not fit for reuse -- just dispose of it.
destroyObject = true;
@@ -891,9 +976,9 @@ private void DeactivateObject(DbConnectionInternal obj)
{
// NOTE: constructor should ensure that current state cannot be State.Initializing, so it can only
// be State.Running or State.ShuttingDown
- Debug.Assert ( _state == State.Running || _state == State.ShuttingDown );
-
- lock (obj)
+ Debug.Assert(_state == State.Running || _state == State.ShuttingDown);
+
+ lock (obj)
{
// A connection with a delegated transaction cannot currently
// be returned to a different customer until the transaction
@@ -901,9 +986,9 @@ private void DeactivateObject(DbConnectionInternal obj)
// transaction object will ensure that it is owned (not lost),
// and it will be certain to put it back into the pool.
- if ( _state == State.ShuttingDown )
+ if (_state == State.ShuttingDown)
{
- if ( obj.IsTransactionRoot )
+ if (obj.IsTransactionRoot)
{
// SQLHotfix# 50003503 - connections that are affiliated with a
// root transaction and that also happen to be in a connection
@@ -923,12 +1008,12 @@ private void DeactivateObject(DbConnectionInternal obj)
}
else
{
- if ( obj.IsNonPoolableTransactionRoot )
+ if (obj.IsNonPoolableTransactionRoot)
{
obj.SetInStasis();
rootTxn = true;
}
- else if ( obj.CanBePooled )
+ else if (obj.CanBePooled)
{
// We must put this connection into the transacted pool
// while inside a lock to prevent a race condition with
@@ -936,14 +1021,14 @@ private void DeactivateObject(DbConnectionInternal obj)
// thread.
SysTx.Transaction transaction = obj.EnlistedTransaction;
- if (null != transaction)
+ if (null != transaction)
{
// NOTE: we're not locking on _state, so it's possible that its
// value could change between the conditional check and here.
// Although perhaps not ideal, this is OK because the
// DelegatedTransactionEnded event will clean up the
// connection appropriately regardless of the pool state.
- Debug.Assert ( _transactedConnectionPool != null, "Transacted connection pool was not expected to be null.");
+ Debug.Assert(_transactedConnectionPool != null, "Transacted connection pool was not expected to be null.");
_transactedConnectionPool.PutTransactedObject(transaction, obj);
rootTxn = true;
}
@@ -955,7 +1040,7 @@ private void DeactivateObject(DbConnectionInternal obj)
}
else
{
- if ( obj.IsTransactionRoot && !obj.IsConnectionDoomed )
+ if (obj.IsTransactionRoot && !obj.IsConnectionDoomed)
{
// SQLHotfix# 50003503 - if the object cannot be pooled but is a transaction
// root, then we must have hit one of two race conditions:
@@ -979,16 +1064,16 @@ private void DeactivateObject(DbConnectionInternal obj)
}
}
}
-
- if (returnToGeneralPool)
+
+ if (returnToGeneralPool)
{
// Only push the connection into the general pool if we didn't
// already push it onto the transacted pool, put it into stasis,
// or want to destroy it.
- Debug.Assert ( destroyObject == false );
+ Debug.Assert(destroyObject == false);
PutNewObject(obj);
}
- else if ( destroyObject )
+ else if (destroyObject)
{
// VSTFDEVDIV# 479556 - connections that have been marked as no longer
// poolable (e.g. exceeded their connection lifetime) are not, in fact,
@@ -1001,31 +1086,36 @@ private void DeactivateObject(DbConnectionInternal obj)
// postcondition
// ensure that the connection was processed
- Debug.Assert ( rootTxn == true || returnToGeneralPool == true || destroyObject == true );
+ Debug.Assert(rootTxn == true || returnToGeneralPool == true || destroyObject == true);
// TODO: BID trace processing state?
}
- internal void DestroyObject(DbConnectionInternal obj) {
+ internal void DestroyObject(DbConnectionInternal obj)
+ {
// A connection with a delegated transaction cannot be disposed of
// until the delegated transaction has actually completed. Instead,
// we simply leave it alone; when the transaction completes, it will
// come back through PutObjectFromTransactedPool, which will call us
// again.
- if (obj.IsTxRootWaitingForTxEnd) {
+ if (obj.IsTxRootWaitingForTxEnd)
+ {
Bid.PoolerTrace(" %d#, Connection %d#, Has Delegated Transaction, waiting to Dispose.\n", ObjectID, obj.ObjectID);
}
- else {
+ else
+ {
Bid.PoolerTrace(" %d#, Connection %d#, Removing from pool.\n", ObjectID, obj.ObjectID);
bool removed = false;
- lock (_objectList) {
+ lock (_objectList)
+ {
removed = _objectList.Remove(obj);
Debug.Assert(removed, "attempt to DestroyObject not in list");
_totalObjects = _objectList.Count;
}
- if (removed) {
+ if (removed)
+ {
Bid.PoolerTrace(" %d#, Connection %d#, Removed from pool.\n", ObjectID, obj.ObjectID);
PerformanceCounters.NumberOfPooledConnections.Decrement();
}
@@ -1036,16 +1126,18 @@ internal void DestroyObject(DbConnectionInternal obj) {
}
}
- private void ErrorCallback(Object state) {
+ private void ErrorCallback(Object state)
+ {
Bid.PoolerTrace(" %d#, Resetting Error handling.\n", ObjectID);
_errorOccurred = false;
_waitHandles.ErrorEvent.Reset();
// the error state is cleaned, destroy the timer to avoid periodic invocation
- Timer t = _errorTimer;
+ Timer t = _errorTimer;
_errorTimer = null;
- if (t != null) {
+ if (t != null)
+ {
t.Dispose(); // Cancel timer request.
}
}
@@ -1055,47 +1147,57 @@ private Exception TryCloneCachedException()
// Cached exception can be of any type, so is not always cloneable.
// This functions clones SqlException
// OleDb and Odbc connections are not passing throw this code
- {
- if (_resError==null)
+ {
+ if (_resError == null)
return null;
- if (_resError.GetType()==typeof(SqlClient.SqlException))
+ if (_resError.GetType() == typeof(SqlClient.SqlException))
return ((SqlClient.SqlException)_resError).InternalClone();
return _resError;
}
- void WaitForPendingOpen() {
+ void WaitForPendingOpen()
+ {
Debug.Assert(!Thread.CurrentThread.IsThreadPoolThread, "This thread may block for a long time. Threadpool threads should not be used.");
PendingGetConnection next;
- do {
+ do
+ {
bool started = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
RuntimeHelpers.PrepareConstrainedRegions();
- try { }
- finally {
+ try
+ { }
+ finally
+ {
started = Interlocked.CompareExchange(ref _pendingOpensWaiting, 1, 0) == 0;
}
- if (!started) {
+ if (!started)
+ {
return;
}
- while (_pendingOpens.TryDequeue(out next)) {
+ while (_pendingOpens.TryDequeue(out next))
+ {
- if (next.Completion.Task.IsCompleted) {
+ if (next.Completion.Task.IsCompleted)
+ {
continue;
}
uint delay;
- if (next.DueTime == Timeout.Infinite) {
+ if (next.DueTime == Timeout.Infinite)
+ {
delay = unchecked((uint)Timeout.Infinite);
}
- else {
+ else
+ {
delay = (uint)Math.Max(ADP.TimerRemainingMilliseconds(next.DueTime), 0);
}
@@ -1104,7 +1206,8 @@ void WaitForPendingOpen() {
Exception caughtException = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
#if DEBUG
Microsoft.Data.SqlClient.TdsParser.ReliabilitySection tdsReliabilitySection = new Microsoft.Data.SqlClient.TdsParser.ReliabilitySection();
@@ -1126,39 +1229,52 @@ void WaitForPendingOpen() {
}
#endif //DEBUG
}
- catch (System.OutOfMemoryException) {
- if (connection != null) { connection.DoomThisConnection(); }
+ catch (System.OutOfMemoryException)
+ {
+ if (connection != null)
+ { connection.DoomThisConnection(); }
throw;
}
- catch (System.StackOverflowException) {
- if (connection != null) { connection.DoomThisConnection(); }
+ catch (System.StackOverflowException)
+ {
+ if (connection != null)
+ { connection.DoomThisConnection(); }
throw;
}
- catch (System.Threading.ThreadAbortException) {
- if (connection != null) { connection.DoomThisConnection(); }
+ catch (System.Threading.ThreadAbortException)
+ {
+ if (connection != null)
+ { connection.DoomThisConnection(); }
throw;
}
- catch (Exception e) {
+ catch (Exception e)
+ {
caughtException = e;
}
- if (caughtException != null) {
+ if (caughtException != null)
+ {
next.Completion.TrySetException(caughtException);
}
- else if (timeout) {
+ else if (timeout)
+ {
next.Completion.TrySetException(ADP.ExceptionWithStackTrace(ADP.PooledOpenTimeout()));
}
- else {
+ else
+ {
Debug.Assert(connection != null, "connection should never be null in success case");
- if (!next.Completion.TrySetResult(connection)) {
+ if (!next.Completion.TrySetResult(connection))
+ {
// if the completion was cancelled, lets try and get this connection back for the next try
PutObject(connection, next.Owner);
}
}
}
}
- finally {
- if (started) {
+ finally
+ {
+ if (started)
+ {
Interlocked.Exchange(ref _pendingOpensWaiting, 0);
}
}
@@ -1166,12 +1282,14 @@ void WaitForPendingOpen() {
} while (_pendingOpens.TryPeek(out next));
}
- internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource retry, DbConnectionOptions userOptions, out DbConnectionInternal connection) {
+ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource retry, DbConnectionOptions userOptions, out DbConnectionInternal connection)
+ {
uint waitForMultipleObjectsTimeout = 0;
bool allowCreate = false;
- if (retry == null) {
+ if (retry == null)
+ {
waitForMultipleObjectsTimeout = (uint)CreationTimeout;
// VSTFDEVDIV 445531: set the wait timeout to INFINITE (-1) if the SQL connection timeout is 0 (== infinite)
@@ -1181,31 +1299,35 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource %d#, DbConnectionInternal State != Running.\n", ObjectID);
connection = null;
return true;
}
bool onlyOneCheckConnection = true;
- if (TryGetConnection(owningObject, waitForMultipleObjectsTimeout, allowCreate, onlyOneCheckConnection, userOptions, out connection)) {
+ if (TryGetConnection(owningObject, waitForMultipleObjectsTimeout, allowCreate, onlyOneCheckConnection, userOptions, out connection))
+ {
return true;
}
- else if (retry == null) {
+ else if (retry == null)
+ {
// timed out on a sync call
return true;
}
- var pendingGetConnection =
+ var pendingGetConnection =
new PendingGetConnection(
- CreationTimeout == 0 ? Timeout.Infinite : ADP.TimerCurrent() + ADP.TimerFromSeconds(CreationTimeout/1000),
+ CreationTimeout == 0 ? Timeout.Infinite : ADP.TimerCurrent() + ADP.TimerFromSeconds(CreationTimeout / 1000),
owningObject,
retry,
userOptions);
_pendingOpens.Enqueue(pendingGetConnection);
// it is better to StartNew too many times than not enough
- if (_pendingOpensWaiting == 0) {
+ if (_pendingOpensWaiting == 0)
+ {
Thread waitOpenThread = new Thread(WaitForPendingOpen);
waitOpenThread.IsBackground = true;
waitOpenThread.Start();
@@ -1218,7 +1340,8 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource %d#, Wait timed out.\n", ObjectID);
- Interlocked.Decrement(ref _waitCount);
- connection = null;
- return false;
-
- case ERROR_HANDLE:
- // Throw the error that PoolCreateRequest stashed.
- Bid.PoolerTrace(" %d#, Errors are set.\n", ObjectID);
- Interlocked.Decrement(ref _waitCount);
- throw TryCloneCachedException();
-
- case CREATION_HANDLE:
- Bid.PoolerTrace(" %d#, Creating new connection.\n", ObjectID);
-
- try {
- obj = UserCreateRequest(owningObject, userOptions);
- }
- catch {
- if (null == obj) {
- Interlocked.Decrement(ref _waitCount);
+ switch (waitResult)
+ {
+ case WAIT_TIMEOUT:
+ Bid.PoolerTrace(" %d#, Wait timed out.\n", ObjectID);
+ Interlocked.Decrement(ref _waitCount);
+ connection = null;
+ return false;
+
+ case ERROR_HANDLE:
+ // Throw the error that PoolCreateRequest stashed.
+ Bid.PoolerTrace(" %d#, Errors are set.\n", ObjectID);
+ Interlocked.Decrement(ref _waitCount);
+ throw TryCloneCachedException();
+
+ case CREATION_HANDLE:
+ Bid.PoolerTrace(" %d#, Creating new connection.\n", ObjectID);
+
+ try
+ {
+ obj = UserCreateRequest(owningObject, userOptions);
}
- throw;
- }
- finally {
- // SQLBUDT #386664 - ensure that we release this waiter, regardless
- // of any exceptions that may be thrown.
- if (null != obj) {
- Interlocked.Decrement(ref _waitCount);
+ catch
+ {
+ if (null == obj)
+ {
+ Interlocked.Decrement(ref _waitCount);
+ }
+ throw;
+ }
+ finally
+ {
+ // SQLBUDT #386664 - ensure that we release this waiter, regardless
+ // of any exceptions that may be thrown.
+ if (null != obj)
+ {
+ Interlocked.Decrement(ref _waitCount);
+ }
}
- }
- if (null == obj) {
- // If we were not able to create an object, check to see if
- // we reached MaxPoolSize. If so, we will no longer wait on
- // the CreationHandle, but instead wait for a free object or
- // the timeout.
-
- // BUG - if we receive the CreationHandle midway into the wait
- // period and re-wait, we will be waiting on the full period
- if (Count >= MaxPoolSize && 0 != MaxPoolSize) {
- if (!ReclaimEmancipatedObjects()) {
- // modify handle array not to wait on creation mutex anymore
- Debug.Assert(2 == CREATION_HANDLE, "creation handle changed value");
- waitHandleCount = 2;
+ if (null == obj)
+ {
+ // If we were not able to create an object, check to see if
+ // we reached MaxPoolSize. If so, we will no longer wait on
+ // the CreationHandle, but instead wait for a free object or
+ // the timeout.
+
+ // BUG - if we receive the CreationHandle midway into the wait
+ // period and re-wait, we will be waiting on the full period
+ if (Count >= MaxPoolSize && 0 != MaxPoolSize)
+ {
+ if (!ReclaimEmancipatedObjects())
+ {
+ // modify handle array not to wait on creation mutex anymore
+ Debug.Assert(2 == CREATION_HANDLE, "creation handle changed value");
+ waitHandleCount = 2;
+ }
}
}
- }
- break;
-
- case SEMAPHORE_HANDLE:
- //
- // guaranteed available inventory
- //
- Interlocked.Decrement(ref _waitCount);
- obj = GetFromGeneralPool();
-
- if ((obj != null) && (!obj.IsConnectionAlive())) {
- Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID);
- DestroyObject(obj);
- obj = null; // Setting to null in case creating a new object fails
-
- if (onlyOneCheckConnection) {
- if (_waitHandles.CreationSemaphore.WaitOne(unchecked((int)waitForMultipleObjectsTimeout))) {
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- Bid.PoolerTrace(" %d#, Creating new connection.\n", ObjectID);
- obj = UserCreateRequest(owningObject, userOptions);
+ break;
+
+ case SEMAPHORE_HANDLE:
+ //
+ // guaranteed available inventory
+ //
+ Interlocked.Decrement(ref _waitCount);
+ obj = GetFromGeneralPool();
+
+ if ((obj != null) && (!obj.IsConnectionAlive()))
+ {
+ Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID);
+ DestroyObject(obj);
+ obj = null; // Setting to null in case creating a new object fails
+
+ if (onlyOneCheckConnection)
+ {
+ if (_waitHandles.CreationSemaphore.WaitOne(unchecked((int)waitForMultipleObjectsTimeout)))
+ {
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ Bid.PoolerTrace(" %d#, Creating new connection.\n", ObjectID);
+ obj = UserCreateRequest(owningObject, userOptions);
+ }
+ finally
+ {
+ _waitHandles.CreationSemaphore.Release(1);
+ }
}
- finally {
- _waitHandles.CreationSemaphore.Release(1);
+ else
+ {
+ // Timeout waiting for creation semaphore - return null
+ Bid.PoolerTrace(" %d#, Wait timed out.\n", ObjectID);
+ connection = null;
+ return false;
}
}
- else {
- // Timeout waiting for creation semaphore - return null
- Bid.PoolerTrace(" %d#, Wait timed out.\n", ObjectID);
- connection = null;
- return false;
- }
}
- }
- break;
-
- case WAIT_FAILED:
- Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0");
- Bid.PoolerTrace(" %d#, Wait failed.\n", ObjectID);
- Interlocked.Decrement(ref _waitCount);
- Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR);
- goto default; // if ThrowExceptionForHR didn't throw for some reason
- case (WAIT_ABANDONED+SEMAPHORE_HANDLE):
- Bid.PoolerTrace(" %d#, Semaphore handle abandonded.\n", ObjectID);
- Interlocked.Decrement(ref _waitCount);
- throw new AbandonedMutexException(SEMAPHORE_HANDLE,_waitHandles.PoolSemaphore);
- case (WAIT_ABANDONED+ERROR_HANDLE):
- Bid.PoolerTrace(" %d#, Error handle abandonded.\n", ObjectID);
- Interlocked.Decrement(ref _waitCount);
- throw new AbandonedMutexException(ERROR_HANDLE,_waitHandles.ErrorEvent);
- case (WAIT_ABANDONED+CREATION_HANDLE):
- Bid.PoolerTrace(" %d#, Creation handle abandoned.\n", ObjectID);
- Interlocked.Decrement(ref _waitCount);
- throw new AbandonedMutexException(CREATION_HANDLE,_waitHandles.CreationSemaphore);
- default:
- Bid.PoolerTrace(" %d#, WaitForMultipleObjects=%d\n", ObjectID, waitResult);
- Interlocked.Decrement(ref _waitCount);
- throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult);
+ break;
+
+ case WAIT_FAILED:
+ Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0");
+ Bid.PoolerTrace(" %d#, Wait failed.\n", ObjectID);
+ Interlocked.Decrement(ref _waitCount);
+ Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR);
+ goto default; // if ThrowExceptionForHR didn't throw for some reason
+ case (WAIT_ABANDONED + SEMAPHORE_HANDLE):
+ Bid.PoolerTrace(" %d#, Semaphore handle abandonded.\n", ObjectID);
+ Interlocked.Decrement(ref _waitCount);
+ throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore);
+ case (WAIT_ABANDONED + ERROR_HANDLE):
+ Bid.PoolerTrace(" %d#, Error handle abandonded.\n", ObjectID);
+ Interlocked.Decrement(ref _waitCount);
+ throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent);
+ case (WAIT_ABANDONED + CREATION_HANDLE):
+ Bid.PoolerTrace(" %d#, Creation handle abandoned.\n", ObjectID);
+ Interlocked.Decrement(ref _waitCount);
+ throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore);
+ default:
+ Bid.PoolerTrace(" %d#, WaitForMultipleObjects=%d\n", ObjectID, waitResult);
+ Interlocked.Decrement(ref _waitCount);
+ throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult);
}
}
- finally {
- if (CREATION_HANDLE == waitResult) {
+ finally
+ {
+ if (CREATION_HANDLE == waitResult)
+ {
int result = SafeNativeMethods.ReleaseSemaphore(_waitHandles.CreationHandle.DangerousGetHandle(), 1, IntPtr.Zero);
- if (0 == result) { // failure case
+ if (0 == result)
+ { // failure case
releaseSemaphoreResult = Marshal.GetHRForLastWin32Error();
}
}
- if (mustRelease) {
+ if (mustRelease)
+ {
_waitHandles.DangerousRelease();
}
}
- if (0 != releaseSemaphoreResult) {
+ if (0 != releaseSemaphoreResult)
+ {
Marshal.ThrowExceptionForHR(releaseSemaphoreResult); // will only throw if (hresult < 0)
}
} while (null == obj);
@@ -1401,7 +1551,8 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj
return true;
}
- private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, SysTx.Transaction transaction) {
+ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, SysTx.Transaction transaction)
+ {
lock (obj)
{ // Protect against Clear and ReclaimEmancipatedObjects, which call IsEmancipated, which is affected by PrePush and PostPop
obj.PostPop(owningObject);
@@ -1426,13 +1577,15 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o
/// Options used to create the new connection
/// Inner connection that will be replaced
/// A new inner connection that is attached to the
- internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) {
+ internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
+ {
PerformanceCounters.SoftConnectsPerSecond.Increment();
Bid.PoolerTrace(" %d#, replacing connection.\n", ObjectID);
DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection);
-
- if (newConnection != null) {
+
+ if (newConnection != null)
+ {
PrepareConnection(owningObject, newConnection, oldConnection.EnlistedTransaction);
oldConnection.PrepareForReplaceConnection();
oldConnection.DeactivateConnection();
@@ -1442,18 +1595,23 @@ internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbCon
return newConnection;
}
- private DbConnectionInternal GetFromGeneralPool() {
+ private DbConnectionInternal GetFromGeneralPool()
+ {
DbConnectionInternal obj = null;
- if (!_stackNew.TryPop(out obj)) {
- if (!_stackOld.TryPop(out obj)) {
+ if (!_stackNew.TryPop(out obj))
+ {
+ if (!_stackOld.TryPop(out obj))
+ {
obj = null;
}
- else {
+ else
+ {
Debug.Assert(obj != null, "null connection is not expected");
}
}
- else {
+ else
+ {
Debug.Assert(obj != null, "null connection is not expected");
}
@@ -1463,35 +1621,43 @@ private DbConnectionInternal GetFromGeneralPool() {
// checked bits. The assert is benign, so we're commenting it out.
//Debug.Assert(obj != null, "GetFromGeneralPool called with nothing in the pool!");
- if (null != obj) {
+ if (null != obj)
+ {
Bid.PoolerTrace(" %d#, Connection %d#, Popped from general pool.\n", ObjectID, obj.ObjectID);
PerformanceCounters.NumberOfFreeConnections.Decrement();
}
- return(obj);
+ return (obj);
}
- private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transaction) {
+ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transaction)
+ {
transaction = ADP.GetCurrentTransaction();
DbConnectionInternal obj = null;
- if (null != transaction && null != _transactedConnectionPool) {
+ if (null != transaction && null != _transactedConnectionPool)
+ {
obj = _transactedConnectionPool.GetTransactedObject(transaction);
- if (null != obj) {
+ if (null != obj)
+ {
Bid.PoolerTrace(" %d#, Connection %d#, Popped from transacted pool.\n", ObjectID, obj.ObjectID);
PerformanceCounters.NumberOfFreeConnections.Decrement();
- if (obj.IsTransactionRoot) {
- try {
+ if (obj.IsTransactionRoot)
+ {
+ try
+ {
obj.IsConnectionAlive(true);
}
- catch {
+ catch
+ {
Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID);
DestroyObject(obj);
throw;
}
}
- else if (!obj.IsConnectionAlive()) {
+ else if (!obj.IsConnectionAlive())
+ {
Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID);
DestroyObject(obj);
obj = null;
@@ -1503,7 +1669,8 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac
[ResourceExposure(ResourceScope.None)] // SxS: this method does not expose resources
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
- private void PoolCreateRequest(object state) {
+ private void PoolCreateRequest(object state)
+ {
// called by pooler to ensure pool requests are currently being satisfied -
// creation mutex has not been obtained
@@ -1511,12 +1678,15 @@ private void PoolCreateRequest(object state) {
Bid.PoolerScopeEnter(out hscp, " %d#\n", ObjectID);
- try {
- if (State.Running == _state) {
+ try
+ {
+ if (State.Running == _state)
+ {
// in case WaitForPendingOpen ever failed with no subsequent OpenAsync calls,
// start it back up again
- if (!_pendingOpens.IsEmpty && _pendingOpensWaiting == 0) {
+ if (!_pendingOpens.IsEmpty && _pendingOpensWaiting == 0)
+ {
Thread waitOpenThread = new Thread(WaitForPendingOpen);
waitOpenThread.IsBackground = true;
waitOpenThread.Start();
@@ -1526,15 +1696,18 @@ private void PoolCreateRequest(object state) {
// not closed.
ReclaimEmancipatedObjects();
- if (!ErrorOccurred) {
- if (NeedToReplenish) {
+ if (!ErrorOccurred)
+ {
+ if (NeedToReplenish)
+ {
// Check to see if pool was created using integrated security and if so, make
// sure the identity of current user matches that of user that created pool.
// If it doesn't match, do not create any objects on the ThreadPool thread,
// since either Open will fail or we will open a object for this pool that does
// not belong in this pool. The side effect of this is that if using integrated
// security min pool size cannot be guaranteed.
- if (UsingIntegrateSecurity && !_identity.Equals(DbConnectionPoolIdentity.GetCurrent())) {
+ if (UsingIntegrateSecurity && !_identity.Equals(DbConnectionPoolIdentity.GetCurrent()))
+ {
return;
}
bool mustRelease = false;
@@ -1542,48 +1715,61 @@ private void PoolCreateRequest(object state) {
uint timeout = (uint)CreationTimeout;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_waitHandles.DangerousAddRef(ref mustRelease);
-
+
// Obtain creation mutex so we're the only one creating objects
// and we must have the wait result
RuntimeHelpers.PrepareConstrainedRegions();
- try { } finally {
+ try
+ { }
+ finally
+ {
waitResult = SafeNativeMethods.WaitForSingleObjectEx(_waitHandles.CreationHandle.DangerousGetHandle(), timeout, false);
}
- if (WAIT_OBJECT_0 == waitResult) {
+ if (WAIT_OBJECT_0 == waitResult)
+ {
DbConnectionInternal newObj;
// Check ErrorOccurred again after obtaining mutex
- if (!ErrorOccurred) {
- while (NeedToReplenish) {
+ if (!ErrorOccurred)
+ {
+ while (NeedToReplenish)
+ {
// Don't specify any user options because there is no outer connection associated with the new connection
newObj = CreateObject(owningObject: null, userOptions: null, oldConnection: null);
// We do not need to check error flag here, since we know if
// CreateObject returned null, we are in error case.
- if (null != newObj) {
+ if (null != newObj)
+ {
PutNewObject(newObj);
}
- else {
+ else
+ {
break;
}
}
}
}
- else if (WAIT_TIMEOUT == waitResult) {
+ else if (WAIT_TIMEOUT == waitResult)
+ {
// do not wait forever and potential block this worker thread
// instead wait for a period of time and just requeue to try again
QueuePoolCreateRequest();
}
- else {
+ else
+ {
// trace waitResult and ignore the failure
Bid.PoolerTrace(" %d#, PoolCreateRequest called WaitForSingleObject failed %d", ObjectID, waitResult);
}
}
- catch (Exception e) {
+ catch (Exception e)
+ {
// UNDONE - should not be catching all exceptions!!!
- if (!ADP.IsCatchableExceptionType(e)) {
+ if (!ADP.IsCatchableExceptionType(e))
+ {
throw;
}
@@ -1592,12 +1778,15 @@ private void PoolCreateRequest(object state) {
// thrown to the user the next time they request a connection.
Bid.PoolerTrace(" %d#, PoolCreateRequest called CreateConnection which threw an exception: %ls", ObjectID, e);
}
- finally {
- if (WAIT_OBJECT_0 == waitResult) {
+ finally
+ {
+ if (WAIT_OBJECT_0 == waitResult)
+ {
// reuse waitResult and ignore its value
waitResult = SafeNativeMethods.ReleaseSemaphore(_waitHandles.CreationHandle.DangerousGetHandle(), 1, IntPtr.Zero);
}
- if (mustRelease) {
+ if (mustRelease)
+ {
_waitHandles.DangerousRelease();
}
}
@@ -1605,13 +1794,15 @@ private void PoolCreateRequest(object state) {
}
}
}
- finally {
+ finally
+ {
Bid.ScopeLeave(ref hscp);
}
}
- internal void PutNewObject(DbConnectionInternal obj) {
- Debug.Assert(null != obj, "why are we adding a null object to the pool?");
+ internal void PutNewObject(DbConnectionInternal obj)
+ {
+ Debug.Assert(null != obj, "why are we adding a null object to the pool?");
// VSTFDEVDIV 742887 - When another thread is clearing this pool, it
// will set _cannotBePooled for all connections in this pool without prejudice which
@@ -1627,7 +1818,8 @@ internal void PutNewObject(DbConnectionInternal obj) {
}
- internal void PutObject(DbConnectionInternal obj, object owningObject) {
+ internal void PutObject(DbConnectionInternal obj, object owningObject)
+ {
Debug.Assert(null != obj, "null obj?");
PerformanceCounters.SoftDisconnectsPerSecond.Increment();
@@ -1639,7 +1831,8 @@ internal void PutObject(DbConnectionInternal obj, object owningObject) {
// will not be a delegated or enlisted transaction once we leave the
// lock.
- lock (obj) {
+ lock (obj)
+ {
// Calling PrePush prevents the object from being reclaimed
// once we leave the lock, because it sets _pooledCount such
// that it won't appear to be out of the pool. What that
@@ -1653,7 +1846,8 @@ internal void PutObject(DbConnectionInternal obj, object owningObject) {
DeactivateObject(obj);
}
- internal void PutObjectFromTransactedPool(DbConnectionInternal obj) {
+ internal void PutObjectFromTransactedPool(DbConnectionInternal obj)
+ {
Debug.Assert(null != obj, "null pooledObject?");
Debug.Assert(obj.EnlistedTransaction == null, "pooledObject is still enlisted?");
@@ -1668,23 +1862,28 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) {
Bid.PoolerTrace(" %d#, Connection %d#, Transaction has ended.\n", ObjectID, obj.ObjectID);
- if (_state == State.Running && obj.CanBePooled) {
+ if (_state == State.Running && obj.CanBePooled)
+ {
PutNewObject(obj);
}
- else {
+ else
+ {
DestroyObject(obj);
QueuePoolCreateRequest();
}
}
- private void QueuePoolCreateRequest() {
- if (State.Running == _state) {
+ private void QueuePoolCreateRequest()
+ {
+ if (State.Running == _state)
+ {
// Make sure we're at quota by posting a callback to the threadpool.
ThreadPool.QueueUserWorkItem(_poolCreateRequest);
}
}
- private bool ReclaimEmancipatedObjects() {
+ private bool ReclaimEmancipatedObjects()
+ {
bool emancipatedObjectFound = false;
Bid.PoolerTrace(" %d#\n", ObjectID);
@@ -1692,20 +1891,26 @@ private bool ReclaimEmancipatedObjects() {
List reclaimedObjects = new List();
int count;
- lock(_objectList) {
+ lock (_objectList)
+ {
count = _objectList.Count;
- for (int i = 0; i < count; ++i) {
+ for (int i = 0; i < count; ++i)
+ {
DbConnectionInternal obj = _objectList[i];
- if (null != obj) {
+ if (null != obj)
+ {
bool locked = false;
- try {
+ try
+ {
Monitor.TryEnter(obj, ref locked);
- if (locked) { // avoid race condition with PrePush/PostPop and IsEmancipated
- if (obj.IsEmancipated) {
+ if (locked)
+ { // avoid race condition with PrePush/PostPop and IsEmancipated
+ if (obj.IsEmancipated)
+ {
// Inside the lock, we want to do as little
// as possible, so we simply mark the object
// as being in the pool, but hand it off to
@@ -1716,7 +1921,8 @@ private bool ReclaimEmancipatedObjects() {
}
}
}
- finally {
+ finally
+ {
if (locked)
Monitor.Exit(obj);
}
@@ -1730,7 +1936,8 @@ private bool ReclaimEmancipatedObjects() {
// to do up, and process them outside the lock.
count = reclaimedObjects.Count;
- for (int i = 0; i < count; ++i) {
+ for (int i = 0; i < count; ++i)
+ {
DbConnectionInternal obj = reclaimedObjects[i];
Bid.PoolerTrace(" %d#, Connection %d#, Reclaiming.\n", ObjectID, obj.ObjectID);
@@ -1744,16 +1951,19 @@ private bool ReclaimEmancipatedObjects() {
return emancipatedObjectFound;
}
- internal void Startup() {
+ internal void Startup()
+ {
Bid.PoolerTrace(" %d#, CleanupWait=%d\n", ObjectID, _cleanupWait);
_cleanupTimer = CreateCleanupTimer();
- if (NeedToReplenish) {
+ if (NeedToReplenish)
+ {
QueuePoolCreateRequest();
}
}
- internal void Shutdown() {
+ internal void Shutdown()
+ {
Bid.PoolerTrace(" %d#\n", ObjectID);
_state = State.ShuttingDown;
@@ -1761,7 +1971,8 @@ internal void Shutdown() {
// deactivate timer callbacks
Timer t = _cleanupTimer;
_cleanupTimer = null;
- if (null != t) {
+ if (null != t)
+ {
t.Dispose();
}
}
@@ -1770,7 +1981,8 @@ internal void Shutdown() {
// that is implemented inside DbConnectionPool. This method's counterpart (PutTransactedObject) should
// only be called from DbConnectionPool.DeactivateObject and thus the plumbing to provide access to
// other objects is unnecessary (hence the asymmetry of Ended but no Begin)
- internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) {
+ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject)
+ {
Debug.Assert(null != transaction, "null transaction?");
Debug.Assert(null != transactedObject, "null transactedObject?");
// Note: connection may still be associated with transaction due to Explicit Unbinding requirement.
@@ -1783,31 +1995,36 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern
// general circulation.
TransactedConnectionPool transactedConnectionPool = _transactedConnectionPool;
- if (null != transactedConnectionPool) {
+ if (null != transactedConnectionPool)
+ {
transactedConnectionPool.TransactionEnded(transaction, transactedObject);
}
}
-
- private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null) {
+
+ private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null)
+ {
// called by user when they were not able to obtain a free object but
// instead obtained creation mutex
DbConnectionInternal obj = null;
- if (ErrorOccurred) {
+ if (ErrorOccurred)
+ {
throw TryCloneCachedException();
}
- else {
- if ((oldConnection != null) || (Count < MaxPoolSize) || (0 == MaxPoolSize)) {
+ else
+ {
+ if ((oldConnection != null) || (Count < MaxPoolSize) || (0 == MaxPoolSize))
+ {
// If we have an odd number of total objects, reclaim any dead objects.
// If we did not find any objects to reclaim, create a new one.
// TODO: Consider implement a control knob here; why do we only check for dead objects ever other time? why not every 10th time or every time?
- if ((oldConnection != null) || (Count & 0x1) == 0x1 || !ReclaimEmancipatedObjects())
+ if ((oldConnection != null) || (Count & 0x1) == 0x1 || !ReclaimEmancipatedObjects())
obj = CreateObject(owningObject, userOptions, oldConnection);
}
return obj;
- }
+ }
}
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContext.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContext.cs
index 51946630cd..6fc660b8b1 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContext.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContext.cs
@@ -101,4 +101,4 @@ internal void ReleaseLockToUpdate() {
Debug.Assert(oldValue == STATUS_LOCKED);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContextKey.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContextKey.cs
index e6499a96bf..0f89649628 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContextKey.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolAuthenticationContextKey.cs
@@ -99,4 +99,4 @@ private int ComputeHashCode() {
return hashCode;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs
index 5f4a5133cb..9486ed376f 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs
@@ -2,22 +2,21 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
- using System.Collections;
- using Microsoft.Data.Common;
using System.Diagnostics;
- using System.Globalization;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
- using System.Security;
- using System.Security.Permissions;
- using System.Security.Principal;
using System.Runtime.Versioning;
+ using System.Security.Permissions;
+ using Microsoft.Data.Common;
- internal abstract class DbConnectionPoolCounters {
- private static class CreationData {
+ internal abstract class DbConnectionPoolCounters
+ {
+ private static class CreationData
+ {
static internal readonly CounterCreationData HardConnectsPerSecond = new CounterCreationData(
"HardConnectsPerSecond",
@@ -90,13 +89,18 @@ private static class CreationData {
PerformanceCounterType.NumberOfItems32);
};
- sealed internal class Counter {
+ sealed internal class Counter
+ {
private PerformanceCounter _instance;
-
- internal Counter (string categoryName, string instanceName, string counterName, PerformanceCounterType counterType) {
- if (ADP.IsPlatformNT5) {
- try {
- if (!ADP.IsEmpty(categoryName) && !ADP.IsEmpty(instanceName)) {
+
+ internal Counter(string categoryName, string instanceName, string counterName, PerformanceCounterType counterType)
+ {
+ if (ADP.IsPlatformNT5)
+ {
+ try
+ {
+ if (!ADP.IsEmpty(categoryName) && !ADP.IsEmpty(instanceName))
+ {
PerformanceCounter instance = new PerformanceCounter();
instance.CategoryName = categoryName;
instance.CounterName = counterName;
@@ -107,7 +111,8 @@ internal Counter (string categoryName, string instanceName, string counterName,
_instance = instance;
}
}
- catch (InvalidOperationException e) {
+ catch (InvalidOperationException e)
+ {
ADP.TraceExceptionWithoutRethrow(e);
// TODO: generate Application EventLog entry about inability to find perf counter
}
@@ -115,18 +120,22 @@ internal Counter (string categoryName, string instanceName, string counterName,
}
- internal void Decrement() {
+ internal void Decrement()
+ {
PerformanceCounter instance = _instance;
- if (null != instance) {
+ if (null != instance)
+ {
instance.Decrement();
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- internal void Dispose () { // TODO: race condition, Dispose at the same time as Increment/Decrement
+ internal void Dispose()
+ { // TODO: race condition, Dispose at the same time as Increment/Decrement
PerformanceCounter instance = _instance;
_instance = null;
- if (null != instance) {
+ if (null != instance)
+ {
instance.RemoveInstance();
// should we be calling instance.Close?
// if we do will it exacerbate the Dispose vs. Decrement race condition
@@ -134,9 +143,11 @@ internal void Dispose () { // TODO: race condition, Dispose at the same time as
}
}
- internal void Increment() {
+ internal void Increment()
+ {
PerformanceCounter instance = _instance;
- if (null != instance) {
+ if (null != instance)
+ {
instance.Increment();
}
}
@@ -158,25 +169,29 @@ internal void Increment() {
internal readonly Counter NumberOfFreeConnections;
internal readonly Counter NumberOfStasisConnections;
internal readonly Counter NumberOfReclaimedConnections;
-
- protected DbConnectionPoolCounters() : this(null, null) {
+
+ protected DbConnectionPoolCounters() : this(null, null)
+ {
}
- protected DbConnectionPoolCounters(string categoryName, string categoryHelp) {
+ protected DbConnectionPoolCounters(string categoryName, string categoryHelp)
+ {
AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadEventHandler);
AppDomain.CurrentDomain.ProcessExit += new EventHandler(this.ExitEventHandler);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.ExceptionEventHandler);
-
+
string instanceName = null;
- if (!ADP.IsEmpty(categoryName)) {
- if (ADP.IsPlatformNT5) {
+ if (!ADP.IsEmpty(categoryName))
+ {
+ if (ADP.IsPlatformNT5)
+ {
instanceName = GetInstanceName();
}
}
-
+
// level 0-3: hard connects/disconnects, plus basic pool/pool entry statistics
- string basicCategoryName = categoryName;
+ string basicCategoryName = categoryName;
HardConnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardConnectsPerSecond.CounterName, CreationData.HardConnectsPerSecond.CounterType);
HardDisconnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardDisconnectsPerSecond.CounterName, CreationData.HardDisconnectsPerSecond.CounterType);
NumberOfNonPooledConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfNonPooledConnections.CounterName, CreationData.NumberOfNonPooledConnections.CounterType);
@@ -187,14 +202,16 @@ protected DbConnectionPoolCounters(string categoryName, string categoryHelp) {
NumberOfInactiveConnectionPools = new Counter(basicCategoryName, instanceName, CreationData.NumberOfInactiveConnectionPools.CounterName, CreationData.NumberOfInactiveConnectionPools.CounterType);
NumberOfStasisConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfStasisConnections.CounterName, CreationData.NumberOfStasisConnections.CounterType);
NumberOfReclaimedConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfReclaimedConnections.CounterName, CreationData.NumberOfReclaimedConnections.CounterType);
-
+
// level 4: expensive stuff
string verboseCategoryName = null;
- if (!ADP.IsEmpty(categoryName)) {
+ if (!ADP.IsEmpty(categoryName))
+ {
// don't load TraceSwitch if no categoryName so that Odbc/OleDb have a chance of not loading TraceSwitch
// which are also used by System.Diagnostics.PerformanceCounter.ctor & System.Transactions.get_Current
TraceSwitch perfCtrSwitch = new TraceSwitch("ConnectionPoolPerformanceCounterDetail", "level of detail to track with connection pool performance counters");
- if (TraceLevel.Verbose == perfCtrSwitch.Level) {
+ if (TraceLevel.Verbose == perfCtrSwitch.Level)
+ {
verboseCategoryName = categoryName;
}
}
@@ -204,16 +221,19 @@ protected DbConnectionPoolCounters(string categoryName, string categoryHelp) {
NumberOfFreeConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfFreeConnections.CounterName, CreationData.NumberOfFreeConnections.CounterType);
}
- [FileIOPermission(SecurityAction.Assert, Unrestricted=true)]
- private string GetAssemblyName() {
+ [FileIOPermission(SecurityAction.Assert, Unrestricted = true)]
+ private string GetAssemblyName()
+ {
string result = null;
// First try GetEntryAssembly name, then AppDomain.FriendlyName.
Assembly assembly = Assembly.GetEntryAssembly();
- if (null != assembly) {
+ if (null != assembly)
+ {
AssemblyName name = assembly.GetName();
- if (name != null) {
+ if (name != null)
+ {
result = name.Name; // MDAC 73469
}
}
@@ -224,14 +244,17 @@ private string GetAssemblyName() {
// TODO: VSDD 534795 - remove the Resource* attributes if you do not use GetCurrentProcessId after the fix
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
- private string GetInstanceName() {
+ private string GetInstanceName()
+ {
string result = null;
string instanceName = GetAssemblyName(); // instance perfcounter name
- if (ADP.IsEmpty(instanceName)) {
+ if (ADP.IsEmpty(instanceName))
+ {
AppDomain appDomain = AppDomain.CurrentDomain;
- if (null != appDomain) {
+ if (null != appDomain)
+ {
instanceName = appDomain.FriendlyName;
}
}
@@ -245,10 +268,11 @@ private string GetInstanceName() {
// prevent problems.
result = String.Format((IFormatProvider)null, "{0}[{1}]", instanceName, pid);
- result = result.Replace('(','[').Replace(')',']').Replace('#','_').Replace('/','_').Replace('\\','_');
+ result = result.Replace('(', '[').Replace(')', ']').Replace('#', '_').Replace('/', '_').Replace('\\', '_');
// SQLBUVSTS #94625 - counter instance name cannot be greater than 127
- if (result.Length > CounterInstanceNameMaxLength) {
+ if (result.Length > CounterInstanceNameMaxLength)
+ {
// Replacing the middle part with "[...]"
// For example: if path is c:\long_path\very_(Ax200)_long__path\perftest.exe and process ID is 1234 than the resulted instance name will be:
// c:\long_path\very_(AxM)[...](AxN)_long__path\perftest.exe[1234]
@@ -261,7 +285,7 @@ private string GetInstanceName() {
insertString,
result.Substring(result.Length - lastPartLength, lastPartLength));
- Debug.Assert(result.Length == CounterInstanceNameMaxLength,
+ Debug.Assert(result.Length == CounterInstanceNameMaxLength,
string.Format((IFormatProvider)null, "wrong calculation of the instance name: expected {0}, actual: {1}", CounterInstanceNameMaxLength, result.Length));
}
@@ -269,7 +293,8 @@ private string GetInstanceName() {
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- public void Dispose() {
+ public void Dispose()
+ {
// ExceptionEventHandler with IsTerminiating may be called before
// the Connection Close is called or the variables are initialized
SafeDispose(HardConnectsPerSecond);
@@ -288,35 +313,43 @@ public void Dispose() {
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- private void SafeDispose(Counter counter) { // WebData 103603
- if (null != counter) {
+ private void SafeDispose(Counter counter)
+ { // WebData 103603
+ if (null != counter)
+ {
counter.Dispose();
}
}
[PrePrepareMethod]
- void ExceptionEventHandler (object sender, UnhandledExceptionEventArgs e) {
- if ((null != e) && e.IsTerminating) {
+ void ExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)
+ {
+ if ((null != e) && e.IsTerminating)
+ {
Dispose();
}
}
[PrePrepareMethod]
- void ExitEventHandler (object sender, EventArgs e) {
+ void ExitEventHandler(object sender, EventArgs e)
+ {
Dispose();
}
[PrePrepareMethod]
- void UnloadEventHandler (object sender, EventArgs e) {
+ void UnloadEventHandler(object sender, EventArgs e)
+ {
Dispose();
}
}
-
- sealed internal class DbConnectionPoolCountersNoCounters : DbConnectionPoolCounters {
+
+ sealed internal class DbConnectionPoolCountersNoCounters : DbConnectionPoolCounters
+ {
public static readonly DbConnectionPoolCountersNoCounters SingletonInstance = new DbConnectionPoolCountersNoCounters();
- private DbConnectionPoolCountersNoCounters() : base () {
+ private DbConnectionPoolCountersNoCounters() : base()
+ {
}
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs
index 64976e3c48..521b820d31 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs
@@ -2,13 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
-
- using System;
+namespace Microsoft.Data.ProviderBase
+{
using System.Collections.Concurrent;
- using Microsoft.Data.Common;
using System.Diagnostics;
- using System.Threading;
+ using Microsoft.Data.Common;
// set_ConnectionString calls DbConnectionFactory.GetConnectionPoolGroup
// when not found a new pool entry is created and potentially added
@@ -27,27 +25,29 @@ namespace Microsoft.Data.ProviderBase {
// and once no pools remain, change state from Active->Idle->Disabled
// Once Disabled, factory can remove its reference to the pool entry
- sealed internal class DbConnectionPoolGroup {
- private readonly DbConnectionOptions _connectionOptions;
- private readonly DbConnectionPoolKey _poolKey;
- private readonly DbConnectionPoolGroupOptions _poolGroupOptions;
+ sealed internal class DbConnectionPoolGroup
+ {
+ private readonly DbConnectionOptions _connectionOptions;
+ private readonly DbConnectionPoolKey _poolKey;
+ private readonly DbConnectionPoolGroupOptions _poolGroupOptions;
private ConcurrentDictionary _poolCollection;
- private int _state; // see PoolGroupState* below
+ private int _state; // see PoolGroupState* below
- private DbConnectionPoolGroupProviderInfo _providerInfo;
- private DbMetaDataFactory _metaDataFactory;
+ private DbConnectionPoolGroupProviderInfo _providerInfo;
+ private DbMetaDataFactory _metaDataFactory;
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
// always lock this before changing _state, we don't want to move out of the 'Disabled' state
// PoolGroupStateUninitialized = 0;
- private const int PoolGroupStateActive = 1; // initial state, GetPoolGroup from cache, connection Open
- private const int PoolGroupStateIdle = 2; // all pools are pruned via Clear
+ private const int PoolGroupStateActive = 1; // initial state, GetPoolGroup from cache, connection Open
+ private const int PoolGroupStateIdle = 2; // all pools are pruned via Clear
private const int PoolGroupStateDisabled = 4; // factory pool entry prunning method
- internal DbConnectionPoolGroup (DbConnectionOptions connectionOptions, DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolGroupOptions) {
+ internal DbConnectionPoolGroup(DbConnectionOptions connectionOptions, DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolGroupOptions)
+ {
Debug.Assert(null != connectionOptions, "null connection options");
Debug.Assert(null == poolGroupOptions || ADP.IsWindowsNT, "should not have pooling options on Win9x");
@@ -63,76 +63,99 @@ internal DbConnectionPoolGroup (DbConnectionOptions connectionOptions, DbConnect
_state = PoolGroupStateActive; // VSWhidbey 112102
}
- internal DbConnectionOptions ConnectionOptions {
- get {
+ internal DbConnectionOptions ConnectionOptions
+ {
+ get
+ {
return _connectionOptions;
}
}
- internal DbConnectionPoolKey PoolKey {
- get {
+ internal DbConnectionPoolKey PoolKey
+ {
+ get
+ {
return _poolKey;
}
}
- internal DbConnectionPoolGroupProviderInfo ProviderInfo {
- get {
+ internal DbConnectionPoolGroupProviderInfo ProviderInfo
+ {
+ get
+ {
return _providerInfo;
}
- set {
+ set
+ {
_providerInfo = value;
- if(null!=value) {
+ if (null != value)
+ {
_providerInfo.PoolGroup = this;
}
}
}
- internal bool IsDisabled {
- get {
+ internal bool IsDisabled
+ {
+ get
+ {
return (PoolGroupStateDisabled == _state);
}
}
- internal int ObjectID {
- get {
+ internal int ObjectID
+ {
+ get
+ {
return _objectID;
}
}
- internal DbConnectionPoolGroupOptions PoolGroupOptions {
- get {
+ internal DbConnectionPoolGroupOptions PoolGroupOptions
+ {
+ get
+ {
return _poolGroupOptions;
}
}
- internal DbMetaDataFactory MetaDataFactory{
- get {
- return _metaDataFactory;
- }
+ internal DbMetaDataFactory MetaDataFactory
+ {
+ get
+ {
+ return _metaDataFactory;
+ }
- set {
+ set
+ {
_metaDataFactory = value;
}
}
- internal int Clear() {
+ internal int Clear()
+ {
// must be multi-thread safe with competing calls by Clear and Prune via background thread
// will return the number of connections in the group after clearing has finished
// First, note the old collection and create a new collection to be used
ConcurrentDictionary oldPoolCollection = null;
- lock (this) {
- if (_poolCollection.Count > 0) {
+ lock (this)
+ {
+ if (_poolCollection.Count > 0)
+ {
oldPoolCollection = _poolCollection;
_poolCollection = new ConcurrentDictionary();
}
}
// Then, if a new collection was created, release the pools from the old collection
- if (oldPoolCollection != null) {
- foreach (var entry in oldPoolCollection) {
+ if (oldPoolCollection != null)
+ {
+ foreach (var entry in oldPoolCollection)
+ {
DbConnectionPool pool = entry.Value;
- if (pool != null) {
+ if (pool != null)
+ {
// TODO: SQLBU 422890
// Pruning a pool while a connection is currently attempting to connect
// will cause the pool to be prematurely abandoned. The only known effect so
@@ -152,7 +175,8 @@ internal int Clear() {
return _poolCollection.Count;
}
- internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory) {
+ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory)
+ {
// When this method returns null it indicates that the connection
// factory should not use pooling.
@@ -161,11 +185,13 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor
// PoolGroupOptions will only be null when we're not supposed to pool
// connections.
DbConnectionPool pool = null;
- if (null != _poolGroupOptions) {
+ if (null != _poolGroupOptions)
+ {
Debug.Assert(ADP.IsWindowsNT, "should not be pooling on Win9x");
DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity;
- if (_poolGroupOptions.PoolByIdentity) {
+ if (_poolGroupOptions.PoolByIdentity)
+ {
// if we're pooling by identity (because integrated security is
// being used for these connections) then we need to go out and
// search for the connectionPool that matches the current identity.
@@ -174,22 +200,28 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor
// If the current token is restricted in some way, then we must
// not attempt to pool these connections.
- if (currentIdentity.IsRestricted) {
+ if (currentIdentity.IsRestricted)
+ {
currentIdentity = null;
}
}
- if (null != currentIdentity) {
- if (!_poolCollection.TryGetValue(currentIdentity, out pool)) { // find the pool
-
+ if (null != currentIdentity)
+ {
+ if (!_poolCollection.TryGetValue(currentIdentity, out pool))
+ { // find the pool
+
- lock (this) {
+ lock (this)
+ {
// Did someone already add it to the list?
- if (!_poolCollection.TryGetValue(currentIdentity, out pool)) {
+ if (!_poolCollection.TryGetValue(currentIdentity, out pool))
+ {
DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions);
DbConnectionPool newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo);
- if (MarkPoolGroupAsActive()) {
+ if (MarkPoolGroupAsActive())
+ {
// If we get here, we know for certain that we there isn't
// a pool that matches the current identity, so we have to
// add the optimistically created one
@@ -199,7 +231,8 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor
connectionFactory.PerformanceCounters.NumberOfActiveConnectionPools.Increment();
pool = newPool;
}
- else {
+ else
+ {
// else pool entry has been disabled so don't create new pools
Debug.Assert(PoolGroupStateDisabled == _state, "state should be disabled");
@@ -208,7 +241,8 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor
newPool.Shutdown();
}
}
- else {
+ else
+ {
// else found an existing pool to use instead
Debug.Assert(PoolGroupStateActive == _state, "state should be active since a pool exists and lock holds");
}
@@ -218,8 +252,10 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor
}
}
- if (null == pool) {
- lock(this) {
+ if (null == pool)
+ {
+ lock (this)
+ {
// keep the pool entry state active when not pooling
MarkPoolGroupAsActive();
}
@@ -227,28 +263,35 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor
return pool;
}
- private bool MarkPoolGroupAsActive() {
+ private bool MarkPoolGroupAsActive()
+ {
// when getting a connection, make the entry active if it was idle (but not disabled)
// must always lock this before calling
- if (PoolGroupStateIdle == _state) {
+ if (PoolGroupStateIdle == _state)
+ {
_state = PoolGroupStateActive;
Bid.Trace(" %d#, Active\n", ObjectID);
}
return (PoolGroupStateActive == _state);
}
- internal bool Prune() {
+ internal bool Prune()
+ {
// must only call from DbConnectionFactory.PruneConnectionPoolGroups on background timer thread
// must lock(DbConnectionFactory._connectionPoolGroups.SyncRoot) before calling ReadyToRemove
// to avoid conflict with DbConnectionFactory.CreateConnectionPoolGroup replacing pool entry
- lock (this) {
- if (_poolCollection.Count > 0) {
+ lock (this)
+ {
+ if (_poolCollection.Count > 0)
+ {
var newPoolCollection = new ConcurrentDictionary();
- foreach (var entry in _poolCollection) {
+ foreach (var entry in _poolCollection)
+ {
DbConnectionPool pool = entry.Value;
- if (pool != null) {
+ if (pool != null)
+ {
// TODO: SQLBU 422890
// Pruning a pool while a connection is currently attempting to connect
// will cause the pool to be prematurely abandoned. The only known effect so
@@ -261,7 +304,8 @@ internal bool Prune() {
// Empty pool during pruning indicates zero or low activity, but
// an error state indicates the pool needs to stay around to
// throttle new connection attempts.
- if ((!pool.ErrorOccurred) && (0 == pool.Count)) {
+ if ((!pool.ErrorOccurred) && (0 == pool.Count))
+ {
// Order is important here. First we remove the pool
// from the collection of pools so no one will try
@@ -273,7 +317,8 @@ internal bool Prune() {
connectionFactory.PerformanceCounters.NumberOfActiveConnectionPools.Decrement();
connectionFactory.QueuePoolForRelease(pool, false);
}
- else {
+ else
+ {
newPoolCollection.TryAdd(entry.Key, entry.Value);
}
}
@@ -283,12 +328,15 @@ internal bool Prune() {
// must be pruning thread to change state and no connections
// otherwise pruning thread risks making entry disabled soon after user calls ClearPool
- if (0 == _poolCollection.Count) {
- if (PoolGroupStateActive == _state) {
+ if (0 == _poolCollection.Count)
+ {
+ if (PoolGroupStateActive == _state)
+ {
_state = PoolGroupStateIdle;
Bid.Trace(" %d#, Idle\n", ObjectID);
}
- else if (PoolGroupStateIdle == _state) {
+ else if (PoolGroupStateIdle == _state)
+ {
_state = PoolGroupStateDisabled;
Bid.Trace(" %d#, Disabled\n", ObjectID);
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs
index 9f9381b4d1..3eceb6d3e3 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroupProviderInfo.cs
@@ -2,17 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
-
- using System;
- internal class DbConnectionPoolGroupProviderInfo {
+namespace Microsoft.Data.ProviderBase
+{
+ internal class DbConnectionPoolGroupProviderInfo
+ {
private DbConnectionPoolGroup _poolGroup;
- internal DbConnectionPoolGroup PoolGroup {
- get {
+ internal DbConnectionPoolGroup PoolGroup
+ {
+ get
+ {
return _poolGroup;
}
- set {
+ set
+ {
_poolGroup = value;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs
index 72083297ca..341569145d 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs
@@ -2,152 +2,174 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
- using System.Collections;
- using Microsoft.Data.Common;
- using System.Diagnostics;
- using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
- using System.Security;
+ using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Security.Principal;
- using System.Threading;
- using System.Runtime.Versioning;
+ using Microsoft.Data.Common;
[Serializable] // Serializable so SqlDependencyProcessDispatcher can marshall cross domain to SqlDependency.
- sealed internal class DbConnectionPoolIdentity {
- private const int E_NotImpersonationToken = unchecked((int)0x8007051D);
- private const int Win32_CheckTokenMembership = 1;
- private const int Win32_GetTokenInformation_1 = 2;
- private const int Win32_GetTokenInformation_2 = 3;
+ sealed internal class DbConnectionPoolIdentity
+ {
+ private const int E_NotImpersonationToken = unchecked((int)0x8007051D);
+ private const int Win32_CheckTokenMembership = 1;
+ private const int Win32_GetTokenInformation_1 = 2;
+ private const int Win32_GetTokenInformation_2 = 3;
private const int Win32_ConvertSidToStringSidW = 4;
- private const int Win32_CreateWellKnownSid = 5;
+ private const int Win32_CreateWellKnownSid = 5;
- static public readonly DbConnectionPoolIdentity NoIdentity = new DbConnectionPoolIdentity(String.Empty, false, true);
- static private readonly byte[] NetworkSid = (ADP.IsWindowsNT ? CreateWellKnownSid(WellKnownSidType.NetworkSid) : null);
+ static public readonly DbConnectionPoolIdentity NoIdentity = new DbConnectionPoolIdentity(String.Empty, false, true);
+ static private readonly byte[] NetworkSid = (ADP.IsWindowsNT ? CreateWellKnownSid(WellKnownSidType.NetworkSid) : null);
static private DbConnectionPoolIdentity _lastIdentity = null;
private readonly string _sidString;
- private readonly bool _isRestricted;
- private readonly bool _isNetwork;
- private readonly int _hashCode;
+ private readonly bool _isRestricted;
+ private readonly bool _isNetwork;
+ private readonly int _hashCode;
- private DbConnectionPoolIdentity (string sidString, bool isRestricted, bool isNetwork) {
+ private DbConnectionPoolIdentity(string sidString, bool isRestricted, bool isNetwork)
+ {
_sidString = sidString;
_isRestricted = isRestricted;
_isNetwork = isNetwork;
_hashCode = sidString == null ? 0 : sidString.GetHashCode();
}
- internal bool IsRestricted {
+ internal bool IsRestricted
+ {
get { return _isRestricted; }
}
- internal bool IsNetwork {
+ internal bool IsNetwork
+ {
get { return _isNetwork; }
}
- static private byte[] CreateWellKnownSid(WellKnownSidType sidType) {
+ static private byte[] CreateWellKnownSid(WellKnownSidType sidType)
+ {
// Passing an array as big as it can ever be is a small price to pay for
// not having to P/Invoke twice (once to get the buffer, once to get the data)
- uint length = ( uint )SecurityIdentifier.MaxBinaryLength;
- byte[] resultSid = new byte[ length ];
+ uint length = (uint)SecurityIdentifier.MaxBinaryLength;
+ byte[] resultSid = new byte[length];
// NOTE - We copied this code from System.Security.Principal.Win32.CreateWellKnownSid...
- if ( 0 == UnsafeNativeMethods.CreateWellKnownSid(( int )sidType, null, resultSid, ref length )) {
+ if (0 == UnsafeNativeMethods.CreateWellKnownSid((int)sidType, null, resultSid, ref length))
+ {
IntegratedSecurityError(Win32_CreateWellKnownSid);
}
return resultSid;
}
- override public bool Equals(object value) {
+ override public bool Equals(object value)
+ {
bool result = ((this == NoIdentity) || (this == value));
- if (!result && (null != value)) {
- DbConnectionPoolIdentity that = ((DbConnectionPoolIdentity) value);
+ if (!result && (null != value))
+ {
+ DbConnectionPoolIdentity that = ((DbConnectionPoolIdentity)value);
result = ((this._sidString == that._sidString) && (this._isRestricted == that._isRestricted) && (this._isNetwork == that._isNetwork));
}
return result;
}
- [SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.ControlPrincipal)]
- static internal WindowsIdentity GetCurrentWindowsIdentity() {
+ [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlPrincipal)]
+ static internal WindowsIdentity GetCurrentWindowsIdentity()
+ {
return WindowsIdentity.GetCurrent();
}
- [SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.UnmanagedCode)]
- static private IntPtr GetWindowsIdentityToken(WindowsIdentity identity) {
+ [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
+ static private IntPtr GetWindowsIdentityToken(WindowsIdentity identity)
+ {
return identity.Token;
}
[ResourceExposure(ResourceScope.None)] // SxS: this method does not create named objects
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
- static internal DbConnectionPoolIdentity GetCurrent() {
+ static internal DbConnectionPoolIdentity GetCurrent()
+ {
// DEVNOTE: GetTokenInfo and EqualSID do not work on 9x. WindowsIdentity does not
// work either on 9x. In fact, after checking with native there is no way
// to validate the user on 9x, so simply don't. It is a known issue in
// native, and we will handle this the same way.
- if (!ADP.IsWindowsNT) {
+ if (!ADP.IsWindowsNT)
+ {
return NoIdentity;
}
- WindowsIdentity identity = GetCurrentWindowsIdentity();
- IntPtr token = GetWindowsIdentityToken(identity); // Free'd by WindowsIdentity.
- uint bufferLength = 2048; // Suggested default given by Greg Fee.
- uint lengthNeeded = 0;
+ WindowsIdentity identity = GetCurrentWindowsIdentity();
+ IntPtr token = GetWindowsIdentityToken(identity); // Free'd by WindowsIdentity.
+ uint bufferLength = 2048; // Suggested default given by Greg Fee.
+ uint lengthNeeded = 0;
- IntPtr tokenStruct = IntPtr.Zero;
- IntPtr SID;
- IntPtr sidStringBuffer = IntPtr.Zero;
- bool isNetwork;
+ IntPtr tokenStruct = IntPtr.Zero;
+ IntPtr SID;
+ IntPtr sidStringBuffer = IntPtr.Zero;
+ bool isNetwork;
// Win32NativeMethods.IsTokenRestricted will raise exception if the native call fails
- bool isRestricted = Win32NativeMethods.IsTokenRestrictedWrapper(token);
-
+ bool isRestricted = Win32NativeMethods.IsTokenRestrictedWrapper(token);
+
DbConnectionPoolIdentity current = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
- if (!UnsafeNativeMethods.CheckTokenMembership(token, NetworkSid, out isNetwork)) {
+ try
+ {
+ if (!UnsafeNativeMethods.CheckTokenMembership(token, NetworkSid, out isNetwork))
+ {
// will always fail with 0x8007051D if token is not an impersonation token
IntegratedSecurityError(Win32_CheckTokenMembership);
}
-
+
RuntimeHelpers.PrepareConstrainedRegions();
- try { } finally {
+ try
+ { }
+ finally
+ {
// allocating memory and assigning to tokenStruct must happen
tokenStruct = SafeNativeMethods.LocalAlloc(DbBuffer.LMEM_FIXED, (IntPtr)bufferLength);
}
- if (IntPtr.Zero == tokenStruct) {
+ if (IntPtr.Zero == tokenStruct)
+ {
throw new OutOfMemoryException();
}
- if (!UnsafeNativeMethods.GetTokenInformation(token, 1, tokenStruct, bufferLength, ref lengthNeeded)) {
- if (lengthNeeded > bufferLength) {
+ if (!UnsafeNativeMethods.GetTokenInformation(token, 1, tokenStruct, bufferLength, ref lengthNeeded))
+ {
+ if (lengthNeeded > bufferLength)
+ {
bufferLength = lengthNeeded;
RuntimeHelpers.PrepareConstrainedRegions();
- try { } finally {
+ try
+ { }
+ finally
+ {
// freeing token struct and setting tokenstruct to null must happen together
// allocating memory and assigning to tokenStruct must happen
SafeNativeMethods.LocalFree(tokenStruct);
tokenStruct = IntPtr.Zero; // protect against LocalAlloc throwing an exception
tokenStruct = SafeNativeMethods.LocalAlloc(DbBuffer.LMEM_FIXED, (IntPtr)bufferLength);
}
- if (IntPtr.Zero == tokenStruct) {
+ if (IntPtr.Zero == tokenStruct)
+ {
throw new OutOfMemoryException();
}
- if (!UnsafeNativeMethods.GetTokenInformation(token, 1, tokenStruct, bufferLength, ref lengthNeeded)) {
+ if (!UnsafeNativeMethods.GetTokenInformation(token, 1, tokenStruct, bufferLength, ref lengthNeeded))
+ {
IntegratedSecurityError(Win32_GetTokenInformation_1);
}
}
- else {
+ else
+ {
IntegratedSecurityError(Win32_GetTokenInformation_2);
}
}
@@ -157,31 +179,38 @@ static internal DbConnectionPoolIdentity GetCurrent() {
SID = Marshal.ReadIntPtr(tokenStruct, 0);
- if (!UnsafeNativeMethods.ConvertSidToStringSidW(SID, out sidStringBuffer)) {
+ if (!UnsafeNativeMethods.ConvertSidToStringSidW(SID, out sidStringBuffer))
+ {
IntegratedSecurityError(Win32_ConvertSidToStringSidW);
}
- if (IntPtr.Zero == sidStringBuffer) {
+ if (IntPtr.Zero == sidStringBuffer)
+ {
throw ADP.InternalError(ADP.InternalErrorCode.ConvertSidToStringSidWReturnedNull);
}
string sidString = Marshal.PtrToStringUni(sidStringBuffer);
var lastIdentity = _lastIdentity;
- if ((lastIdentity != null) && (lastIdentity._sidString == sidString) && (lastIdentity._isRestricted == isRestricted) && (lastIdentity._isNetwork == isNetwork)) {
+ if ((lastIdentity != null) && (lastIdentity._sidString == sidString) && (lastIdentity._isRestricted == isRestricted) && (lastIdentity._isNetwork == isNetwork))
+ {
current = lastIdentity;
}
- else {
+ else
+ {
current = new DbConnectionPoolIdentity(sidString, isRestricted, isNetwork);
}
}
- finally {
+ finally
+ {
// Marshal.FreeHGlobal does not have a ReliabilityContract
- if (IntPtr.Zero != tokenStruct) {
+ if (IntPtr.Zero != tokenStruct)
+ {
SafeNativeMethods.LocalFree(tokenStruct);
tokenStruct = IntPtr.Zero;
}
- if (IntPtr.Zero != sidStringBuffer) {
+ if (IntPtr.Zero != sidStringBuffer)
+ {
SafeNativeMethods.LocalFree(sidStringBuffer);
sidStringBuffer = IntPtr.Zero;
}
@@ -190,19 +219,22 @@ static internal DbConnectionPoolIdentity GetCurrent() {
return current;
}
- override public int GetHashCode() {
+ override public int GetHashCode()
+ {
return _hashCode;
}
- static private void IntegratedSecurityError(int caller) {
+ static private void IntegratedSecurityError(int caller)
+ {
// passing 1,2,3,4,5 instead of true/false so that with a debugger
// we could determine more easily which Win32 method call failed
int lastError = Marshal.GetHRForLastWin32Error();
- if ((Win32_CheckTokenMembership != caller) || (E_NotImpersonationToken != lastError)) {
+ if ((Win32_CheckTokenMembership != caller) || (E_NotImpersonationToken != lastError))
+ {
Marshal.ThrowExceptionForHR(lastError); // will only throw if (hresult < 0)
}
}
-
+
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolOptions.cs
index 81b5478a54..e7a03e5944 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolOptions.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolOptions.cs
@@ -2,20 +2,21 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
- using System.Diagnostics;
- internal sealed class DbConnectionPoolGroupOptions {
+ internal sealed class DbConnectionPoolGroupOptions
+ {
- private readonly bool _poolByIdentity;
- private readonly int _minPoolSize;
- private readonly int _maxPoolSize;
- private readonly int _creationTimeout;
- private readonly TimeSpan _loadBalanceTimeout;
- private readonly bool _hasTransactionAffinity;
- private readonly bool _useLoadBalancing;
+ private readonly bool _poolByIdentity;
+ private readonly int _minPoolSize;
+ private readonly int _maxPoolSize;
+ private readonly int _creationTimeout;
+ private readonly TimeSpan _loadBalanceTimeout;
+ private readonly bool _hasTransactionAffinity;
+ private readonly bool _useLoadBalancing;
public DbConnectionPoolGroupOptions(
bool poolByIdentity,
@@ -23,13 +24,15 @@ public DbConnectionPoolGroupOptions(
int maxPoolSize,
int creationTimeout,
int loadBalanceTimeout,
- bool hasTransactionAffinity) {
+ bool hasTransactionAffinity)
+ {
_poolByIdentity = poolByIdentity;
_minPoolSize = minPoolSize;
_maxPoolSize = maxPoolSize;
_creationTimeout = creationTimeout;
- if (0 != loadBalanceTimeout) {
+ if (0 != loadBalanceTimeout)
+ {
_loadBalanceTimeout = new TimeSpan(0, 0, loadBalanceTimeout);
_useLoadBalancing = true;
}
@@ -37,28 +40,35 @@ public DbConnectionPoolGroupOptions(
_hasTransactionAffinity = hasTransactionAffinity;
}
- public int CreationTimeout {
+ public int CreationTimeout
+ {
get { return _creationTimeout; }
}
- public bool HasTransactionAffinity {
- get { return _hasTransactionAffinity; }
+ public bool HasTransactionAffinity
+ {
+ get { return _hasTransactionAffinity; }
}
- public TimeSpan LoadBalanceTimeout {
- get { return _loadBalanceTimeout; }
+ public TimeSpan LoadBalanceTimeout
+ {
+ get { return _loadBalanceTimeout; }
}
- public int MaxPoolSize {
- get { return _maxPoolSize; }
+ public int MaxPoolSize
+ {
+ get { return _maxPoolSize; }
}
- public int MinPoolSize {
- get { return _minPoolSize; }
+ public int MinPoolSize
+ {
+ get { return _minPoolSize; }
}
- public bool PoolByIdentity {
- get { return _poolByIdentity; }
+ public bool PoolByIdentity
+ {
+ get { return _poolByIdentity; }
}
- public bool UseLoadBalancing {
- get { return _useLoadBalancing; }
+ public bool UseLoadBalancing
+ {
+ get { return _useLoadBalancing; }
}
}
}
-
+
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolProviderInfo.cs
index 4208db8bc0..5392795dff 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolProviderInfo.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolProviderInfo.cs
@@ -2,11 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
-
- using System;
- using System.Diagnostics;
-
- internal class DbConnectionPoolProviderInfo {
+namespace Microsoft.Data.ProviderBase
+{
+ internal class DbConnectionPoolProviderInfo
+ {
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs
index 6cce48857d..2b4d4f966b 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs
@@ -2,77 +2,83 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
- using System.Collections;
- using Microsoft.Data;
- using Microsoft.Data.Common;
+ using System.Data;
+ using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.IO;
- using System.Xml;
- using System.Xml.Schema;
- using System.Data;
- using System.Data.Common;
+ using Microsoft.Data.Common;
- internal class DbMetaDataFactory{ // V1.2.3300
-
- private DataSet _metaDataCollectionsDataSet;
- private string _normalizedServerVersion;
- private string _serverVersionString;
- // well known column names
- private const string _collectionName = "CollectionName";
- private const string _populationMechanism = "PopulationMechanism";
- private const string _populationString = "PopulationString";
- private const string _maximumVersion = "MaximumVersion";
- private const string _minimumVersion = "MinimumVersion";
- private const string _dataSourceProductVersionNormalized = "DataSourceProductVersionNormalized";
- private const string _dataSourceProductVersion = "DataSourceProductVersion";
- private const string _restrictionDefault = "RestrictionDefault";
- private const string _restrictionNumber = "RestrictionNumber";
- private const string _numberOfRestrictions = "NumberOfRestrictions";
- private const string _restrictionName = "RestrictionName";
- private const string _parameterName = "ParameterName";
+ internal class DbMetaDataFactory
+ { // V1.2.3300
+
+ private DataSet _metaDataCollectionsDataSet;
+ private string _normalizedServerVersion;
+ private string _serverVersionString;
+ // well known column names
+ private const string _collectionName = "CollectionName";
+ private const string _populationMechanism = "PopulationMechanism";
+ private const string _populationString = "PopulationString";
+ private const string _maximumVersion = "MaximumVersion";
+ private const string _minimumVersion = "MinimumVersion";
+ private const string _dataSourceProductVersionNormalized = "DataSourceProductVersionNormalized";
+ private const string _dataSourceProductVersion = "DataSourceProductVersion";
+ private const string _restrictionDefault = "RestrictionDefault";
+ private const string _restrictionNumber = "RestrictionNumber";
+ private const string _numberOfRestrictions = "NumberOfRestrictions";
+ private const string _restrictionName = "RestrictionName";
+ private const string _parameterName = "ParameterName";
// population mechanisms
- private const string _dataTable = "DataTable";
- private const string _sqlCommand = "SQLCommand";
- private const string _prepareCollection = "PrepareCollection";
+ private const string _dataTable = "DataTable";
+ private const string _sqlCommand = "SQLCommand";
+ private const string _prepareCollection = "PrepareCollection";
-
- public DbMetaDataFactory(Stream xmlStream, string serverVersion, string normalizedServerVersion) {
+
+ public DbMetaDataFactory(Stream xmlStream, string serverVersion, string normalizedServerVersion)
+ {
ADP.CheckArgumentNull(xmlStream, "xmlStream");
ADP.CheckArgumentNull(serverVersion, "serverVersion");
ADP.CheckArgumentNull(normalizedServerVersion, "normalizedServerVersion");
-
+
LoadDataSetFromXml(xmlStream);
_serverVersionString = serverVersion;
_normalizedServerVersion = normalizedServerVersion;
}
- protected DataSet CollectionDataSet {
- get {
+ protected DataSet CollectionDataSet
+ {
+ get
+ {
return _metaDataCollectionsDataSet;
}
}
- protected string ServerVersion {
- get {
+ protected string ServerVersion
+ {
+ get
+ {
return _serverVersionString;
}
}
- protected string ServerVersionNormalized {
- get {
+ protected string ServerVersionNormalized
+ {
+ get
+ {
return _normalizedServerVersion;
}
}
- protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames) {
+ protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames)
+ {
DataTable sourceTable;
DataTable destinationTable;
@@ -80,23 +86,27 @@ protected DataTable CloneAndFilterCollection(string collectionName, string[] hid
DataColumnCollection destinationColumns;
DataRow newRow;
- sourceTable = _metaDataCollectionsDataSet.Tables[collectionName];
+ sourceTable = _metaDataCollectionsDataSet.Tables[collectionName];
- if ((sourceTable == null) || (collectionName != sourceTable.TableName)) {
+ if ((sourceTable == null) || (collectionName != sourceTable.TableName))
+ {
throw ADP.DataTableDoesNotExist(collectionName);
}
-
+
destinationTable = new DataTable(collectionName);
destinationTable.Locale = CultureInfo.InvariantCulture;
destinationColumns = destinationTable.Columns;
- filteredSourceColumns = FilterColumns(sourceTable,hiddenColumnNames,destinationColumns);
+ filteredSourceColumns = FilterColumns(sourceTable, hiddenColumnNames, destinationColumns);
- foreach (DataRow row in sourceTable.Rows) {
- if (SupportedByCurrentVersion(row) == true) {
+ foreach (DataRow row in sourceTable.Rows)
+ {
+ if (SupportedByCurrentVersion(row) == true)
+ {
newRow = destinationTable.NewRow();
- for(int i = 0; i < destinationColumns.Count; i++) {
- newRow[destinationColumns[i]] = row[filteredSourceColumns[i],DataRowVersion.Current];
+ for (int i = 0; i < destinationColumns.Count; i++)
+ {
+ newRow[destinationColumns[i]] = row[filteredSourceColumns[i], DataRowVersion.Current];
}
destinationTable.Rows.Add(newRow);
newRow.AcceptChanges();
@@ -106,95 +116,111 @@ protected DataTable CloneAndFilterCollection(string collectionName, string[] hid
return destinationTable;
}
- public void Dispose() {
+ public void Dispose()
+ {
Dispose(true);
}
- virtual protected void Dispose(bool disposing) {
- if (disposing) {
+ virtual protected void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
_normalizedServerVersion = null;
_serverVersionString = null;
_metaDataCollectionsDataSet.Dispose();
}
}
- private DataTable ExecuteCommand(DataRow requestedCollectionRow, String[] restrictions, DbConnection connection){
+ private DataTable ExecuteCommand(DataRow requestedCollectionRow, String[] restrictions, DbConnection connection)
+ {
- DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
- DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString];
- DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions];
- DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName];
+ DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
+ DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString];
+ DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions];
+ DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName];
//DataColumn restrictionNameColumn = metaDataCollectionsTable.Columns[_restrictionName];
-
- DataTable resultTable = null;
- DbCommand command = null;
- DataTable schemaTable = null;
+
+ DataTable resultTable = null;
+ DbCommand command = null;
+ DataTable schemaTable = null;
Debug.Assert(requestedCollectionRow != null);
- String sqlCommand = requestedCollectionRow[populationStringColumn,DataRowVersion.Current] as string;
- int numberOfRestrictions = (int)requestedCollectionRow[numberOfRestrictionsColumn,DataRowVersion.Current] ;
- String collectionName = requestedCollectionRow[collectionNameColumn,DataRowVersion.Current] as string;
+ String sqlCommand = requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string;
+ int numberOfRestrictions = (int)requestedCollectionRow[numberOfRestrictionsColumn, DataRowVersion.Current];
+ String collectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string;
- if ((restrictions != null) && (restrictions.Length > numberOfRestrictions)) {
+ if ((restrictions != null) && (restrictions.Length > numberOfRestrictions))
+ {
throw ADP.TooManyRestrictions(collectionName);
}
command = connection.CreateCommand();
command.CommandText = sqlCommand;
- command.CommandTimeout = System.Math.Max(command.CommandTimeout,180);
+ command.CommandTimeout = System.Math.Max(command.CommandTimeout, 180);
+
+ for (int i = 0; i < numberOfRestrictions; i++)
+ {
- for (int i = 0; i < numberOfRestrictions; i++) {
-
DbParameter restrictionParameter = command.CreateParameter();
-
-
- if ((restrictions != null) && (restrictions.Length > i ) && (restrictions[i] != null)) {
-
+
+
+ if ((restrictions != null) && (restrictions.Length > i) && (restrictions[i] != null))
+ {
+
restrictionParameter.Value = restrictions[i];
}
- else {
+ else
+ {
// This is where we have to assign null to the value of the parameter.
restrictionParameter.Value = DBNull.Value;
}
- restrictionParameter.ParameterName = GetParameterName(collectionName, i+1);
+ restrictionParameter.ParameterName = GetParameterName(collectionName, i + 1);
restrictionParameter.Direction = ParameterDirection.Input;
command.Parameters.Add(restrictionParameter);
}
-
+
DbDataReader reader = null;
- try {
-
- try {
- reader = command.ExecuteReader();
+ try
+ {
+
+ try
+ {
+ reader = command.ExecuteReader();
}
- catch (Exception e) {
- if (!ADP.IsCatchableExceptionType(e)) {
+ catch (Exception e)
+ {
+ if (!ADP.IsCatchableExceptionType(e))
+ {
throw;
- }
- throw ADP.QueryFailed(collectionName,e);
+ }
+ throw ADP.QueryFailed(collectionName, e);
}
-
+
// TODO: Consider using the DataAdapter.Fill
// Build a DataTable from the reader
resultTable = new DataTable(collectionName);
resultTable.Locale = CultureInfo.InvariantCulture;
-
+
schemaTable = reader.GetSchemaTable();
- foreach (DataRow row in schemaTable.Rows){
+ foreach (DataRow row in schemaTable.Rows)
+ {
resultTable.Columns.Add(row["ColumnName"] as string, (Type)row["DataType"] as Type);
}
object[] values = new object[resultTable.Columns.Count];
- while (reader.Read()) {
+ while (reader.Read())
+ {
reader.GetValues(values);
resultTable.Rows.Add(values);
}
}
- finally {
- if (reader != null) {
+ finally
+ {
+ if (reader != null)
+ {
reader.Dispose();
reader = null;
}
@@ -202,29 +228,35 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, String[] restri
return resultTable;
}
- private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColumnNames, DataColumnCollection destinationColumns) {
+ private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColumnNames, DataColumnCollection destinationColumns)
+ {
DataColumn newDestinationColumn;
int currentColumn;
DataColumn[] filteredSourceColumns = null;
int columnCount = 0;
- foreach (DataColumn sourceColumn in sourceTable.Columns){
- if (IncludeThisColumn(sourceColumn,hiddenColumnNames) == true) {
+ foreach (DataColumn sourceColumn in sourceTable.Columns)
+ {
+ if (IncludeThisColumn(sourceColumn, hiddenColumnNames) == true)
+ {
columnCount++;
}
}
- if (columnCount == 0) {
+ if (columnCount == 0)
+ {
throw ADP.NoColumns();
}
- currentColumn= 0;
+ currentColumn = 0;
filteredSourceColumns = new DataColumn[columnCount];
- foreach(DataColumn sourceColumn in sourceTable.Columns){
- if (IncludeThisColumn(sourceColumn,hiddenColumnNames) == true) {
- newDestinationColumn = new DataColumn(sourceColumn.ColumnName,sourceColumn.DataType);
+ foreach (DataColumn sourceColumn in sourceTable.Columns)
+ {
+ if (IncludeThisColumn(sourceColumn, hiddenColumnNames) == true)
+ {
+ newDestinationColumn = new DataColumn(sourceColumn.ColumnName, sourceColumn.DataType);
destinationColumns.Add(newDestinationColumn);
filteredSourceColumns[currentColumn] = sourceColumn;
currentColumn++;
@@ -233,55 +265,67 @@ private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColu
return filteredSourceColumns;
}
- internal DataRow FindMetaDataCollectionRow(string collectionName) {
+ internal DataRow FindMetaDataCollectionRow(string collectionName)
+ {
- bool versionFailure;
- bool haveExactMatch;
- bool haveMultipleInexactMatches;
- string candidateCollectionName;
+ bool versionFailure;
+ bool haveExactMatch;
+ bool haveMultipleInexactMatches;
+ string candidateCollectionName;
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
- if (metaDataCollectionsTable == null) {
+ if (metaDataCollectionsTable == null)
+ {
throw ADP.InvalidXml();
}
-
- DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
- if ((null == collectionNameColumn) || (typeof(System.String) != collectionNameColumn.DataType)) {
+ DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
+
+ if ((null == collectionNameColumn) || (typeof(System.String) != collectionNameColumn.DataType))
+ {
throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName);
}
DataRow requestedCollectionRow = null;
String exactCollectionName = null;
-
+
// find the requested collection
versionFailure = false;
haveExactMatch = false;
haveMultipleInexactMatches = false;
-
- foreach (DataRow row in metaDataCollectionsTable.Rows){
- candidateCollectionName = row[collectionNameColumn,DataRowVersion.Current] as string;
- if (ADP.IsEmpty(candidateCollectionName)) {
- throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections,DbMetaDataColumnNames.CollectionName);
+ foreach (DataRow row in metaDataCollectionsTable.Rows)
+ {
+
+ candidateCollectionName = row[collectionNameColumn, DataRowVersion.Current] as string;
+ if (ADP.IsEmpty(candidateCollectionName))
+ {
+ throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName);
}
- if (ADP.CompareInsensitiveInvariant(candidateCollectionName, collectionName)){
- if (SupportedByCurrentVersion(row) == false) {
+ if (ADP.CompareInsensitiveInvariant(candidateCollectionName, collectionName))
+ {
+ if (SupportedByCurrentVersion(row) == false)
+ {
versionFailure = true;
}
- else{
- if (collectionName == candidateCollectionName) {
- if (haveExactMatch == true) {
+ else
+ {
+ if (collectionName == candidateCollectionName)
+ {
+ if (haveExactMatch == true)
+ {
throw ADP.CollectionNameIsNotUnique(collectionName);
}
requestedCollectionRow = row;
exactCollectionName = candidateCollectionName;
haveExactMatch = true;
}
- else {
+ else
+ {
// have an inexact match - ok only if it is the only one
- if (exactCollectionName != null) {
+ if (exactCollectionName != null)
+ {
// can't fail here becasue we may still find an exact match
haveMultipleInexactMatches = true;
}
@@ -292,37 +336,44 @@ internal DataRow FindMetaDataCollectionRow(string collectionName) {
}
}
- if (requestedCollectionRow == null){
- if (versionFailure == false) {
+ if (requestedCollectionRow == null)
+ {
+ if (versionFailure == false)
+ {
throw ADP.UndefinedCollection(collectionName);
}
- else {
+ else
+ {
throw ADP.UnsupportedVersion(collectionName);
}
}
-
- if ((haveExactMatch == false) && (haveMultipleInexactMatches == true)) {
+
+ if ((haveExactMatch == false) && (haveMultipleInexactMatches == true))
+ {
throw ADP.AmbigousCollectionName(collectionName);
- }
+ }
return requestedCollectionRow;
-
+
}
- private void FixUpVersion(DataTable dataSourceInfoTable){
+ private void FixUpVersion(DataTable dataSourceInfoTable)
+ {
Debug.Assert(dataSourceInfoTable.TableName == DbMetaDataCollectionNames.DataSourceInformation);
- DataColumn versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion];
+ DataColumn versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion];
DataColumn normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized];
- if ((versionColumn == null) || (normalizedVersionColumn == null)) {
+ if ((versionColumn == null) || (normalizedVersionColumn == null))
+ {
throw ADP.MissingDataSourceInformationColumn();
}
- if (dataSourceInfoTable.Rows.Count != 1) {
+ if (dataSourceInfoTable.Rows.Count != 1)
+ {
throw ADP.IncorrectNumberOfDataSourceInformationRows();
}
- DataRow dataSourceInfoRow = dataSourceInfoTable.Rows[0];
+ DataRow dataSourceInfoRow = dataSourceInfoTable.Rows[0];
dataSourceInfoRow[versionColumn] = _serverVersionString;
dataSourceInfoRow[normalizedVersionColumn] = _normalizedServerVersion;
@@ -330,20 +381,24 @@ private void FixUpVersion(DataTable dataSourceInfoTable){
}
- private string GetParameterName(string neededCollectionName, int neededRestrictionNumber) {
+ private string GetParameterName(string neededCollectionName, int neededRestrictionNumber)
+ {
DataTable restrictionsTable = null;
DataColumnCollection restrictionColumns = null;
DataColumn collectionName = null;
- DataColumn parameterName = null;
+ DataColumn parameterName = null;
DataColumn restrictionName = null;
- DataColumn restrictionNumber = null;;
- string result = null;
+ DataColumn restrictionNumber = null;
+ ;
+ string result = null;
restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions];
- if (restrictionsTable != null) {
+ if (restrictionsTable != null)
+ {
restrictionColumns = restrictionsTable.Columns;
- if (restrictionColumns != null) {
+ if (restrictionColumns != null)
+ {
collectionName = restrictionColumns[_collectionName];
parameterName = restrictionColumns[_parameterName];
restrictionName = restrictionColumns[_restrictionName];
@@ -351,22 +406,26 @@ private string GetParameterName(string neededCollectionName, int neededRestricti
}
}
- if ((parameterName == null) ||(collectionName == null) || (restrictionName == null) || (restrictionNumber == null)) {
+ if ((parameterName == null) || (collectionName == null) || (restrictionName == null) || (restrictionNumber == null))
+ {
throw ADP.MissingRestrictionColumn();
}
- foreach (DataRow restriction in restrictionsTable.Rows) {
+ foreach (DataRow restriction in restrictionsTable.Rows)
+ {
if (((string)restriction[collectionName] == neededCollectionName) &&
((int)restriction[restrictionNumber] == neededRestrictionNumber) &&
- (SupportedByCurrentVersion(restriction))) {
+ (SupportedByCurrentVersion(restriction)))
+ {
result = (string)restriction[parameterName];
break;
}
}
- if (result == null) {
+ if (result == null)
+ {
throw ADP.MissingRestrictionRow();
}
@@ -374,25 +433,29 @@ private string GetParameterName(string neededCollectionName, int neededRestricti
}
- virtual public DataTable GetSchema(DbConnection connection, string collectionName, string[] restrictions) {
- Debug.Assert (_metaDataCollectionsDataSet != null);
+ virtual public DataTable GetSchema(DbConnection connection, string collectionName, string[] restrictions)
+ {
+ Debug.Assert(_metaDataCollectionsDataSet != null);
//TODO: MarkAsh or EnzoL should review this code for efficency.
- DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
- DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism];
- DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
- DataRow requestedCollectionRow = null;
- DataTable requestedSchema = null;
- string[] hiddenColumns;
- string exactCollectionName = null;
+ DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
+ DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism];
+ DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
+ DataRow requestedCollectionRow = null;
+ DataTable requestedSchema = null;
+ string[] hiddenColumns;
+ string exactCollectionName = null;
requestedCollectionRow = FindMetaDataCollectionRow(collectionName);
- exactCollectionName = requestedCollectionRow[collectionNameColumn,DataRowVersion.Current] as string;
+ exactCollectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string;
+
+ if (ADP.IsEmptyArray(restrictions) == false)
+ {
- if (ADP.IsEmptyArray(restrictions) == false){
-
- for (int i = 0; i < restrictions.Length; i++) {
- if ((restrictions[i] != null) && (restrictions[i].Length > 4096)) {
+ for (int i = 0; i < restrictions.Length; i++)
+ {
+ if ((restrictions[i] != null) && (restrictions[i].Length > 4096))
+ {
// use a non-specific error because no new beta 2 error messages are allowed
// TODO: will add a more descriptive error in RTM
throw ADP.NotSupported();
@@ -400,41 +463,46 @@ virtual public DataTable GetSchema(DbConnection connection, string collectionNam
}
}
- string populationMechanism = requestedCollectionRow[populationMechanismColumn,DataRowVersion.Current] as string;
- switch (populationMechanism) {
+ string populationMechanism = requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string;
+ switch (populationMechanism)
+ {
case _dataTable:
- if (exactCollectionName == DbMetaDataCollectionNames.MetaDataCollections) {
+ if (exactCollectionName == DbMetaDataCollectionNames.MetaDataCollections)
+ {
hiddenColumns = new string[2];
hiddenColumns[0] = _populationMechanism;
hiddenColumns[1] = _populationString;
}
- else {
+ else
+ {
hiddenColumns = null;
}
// none of the datatable collections support restrictions
- if (ADP.IsEmptyArray(restrictions) == false){
+ if (ADP.IsEmptyArray(restrictions) == false)
+ {
throw ADP.TooManyRestrictions(exactCollectionName);
}
- requestedSchema = CloneAndFilterCollection(exactCollectionName,hiddenColumns);
+ requestedSchema = CloneAndFilterCollection(exactCollectionName, hiddenColumns);
// TODO: Consider an alternate method that doesn't involve special casing -- perhaps _prepareCollection
// for the data source infomation table we need to fix up the version columns at run time
// since the version is determined at run time
- if (exactCollectionName == DbMetaDataCollectionNames.DataSourceInformation) {
+ if (exactCollectionName == DbMetaDataCollectionNames.DataSourceInformation)
+ {
FixUpVersion(requestedSchema);
}
break;
case _sqlCommand:
- requestedSchema = ExecuteCommand(requestedCollectionRow,restrictions,connection);
+ requestedSchema = ExecuteCommand(requestedCollectionRow, restrictions, connection);
break;
case _prepareCollection:
- requestedSchema = PrepareCollection(exactCollectionName,restrictions, connection);
+ requestedSchema = PrepareCollection(exactCollectionName, restrictions, connection);
break;
default:
@@ -444,12 +512,14 @@ virtual public DataTable GetSchema(DbConnection connection, string collectionNam
return requestedSchema;
}
- private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames) {
+ private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames)
+ {
bool result = true;
string sourceColumnName = sourceColumn.ColumnName;
- switch (sourceColumnName) {
+ switch (sourceColumnName)
+ {
case _minimumVersion:
case _maximumVersion:
@@ -457,11 +527,14 @@ private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNam
break;
default:
- if (hiddenColumnNames == null) {
+ if (hiddenColumnNames == null)
+ {
break;
}
- for (int i = 0 ; i < hiddenColumnNames.Length; i++) {
- if (hiddenColumnNames[i] == sourceColumnName){
+ for (int i = 0; i < hiddenColumnNames.Length; i++)
+ {
+ if (hiddenColumnNames[i] == sourceColumnName)
+ {
result = false;
break;
}
@@ -472,17 +545,20 @@ private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNam
return result;
}
- private void LoadDataSetFromXml(Stream XmlStream){
+ private void LoadDataSetFromXml(Stream XmlStream)
+ {
_metaDataCollectionsDataSet = new DataSet();
- _metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
+ _metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
_metaDataCollectionsDataSet.ReadXml(XmlStream);
}
- virtual protected DataTable PrepareCollection(String collectionName, String[] restrictions,DbConnection connection){
+ virtual protected DataTable PrepareCollection(String collectionName, String[] restrictions, DbConnection connection)
+ {
throw ADP.NotSupported();
}
- private bool SupportedByCurrentVersion(DataRow requestedCollectionRow){
+ private bool SupportedByCurrentVersion(DataRow requestedCollectionRow)
+ {
bool result = true;
DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns;
@@ -491,11 +567,15 @@ private bool SupportedByCurrentVersion(DataRow requestedCollectionRow){
// check the minimum version first
versionColumn = tableColumns[_minimumVersion];
- if (versionColumn != null) {
+ if (versionColumn != null)
+ {
version = requestedCollectionRow[versionColumn];
- if (version != null) {
- if (version != DBNull.Value) {
- if (0 > string.Compare( _normalizedServerVersion,(string)version, StringComparison.OrdinalIgnoreCase)){
+ if (version != null)
+ {
+ if (version != DBNull.Value)
+ {
+ if (0 > string.Compare(_normalizedServerVersion, (string)version, StringComparison.OrdinalIgnoreCase))
+ {
result = false;
}
}
@@ -503,13 +583,18 @@ private bool SupportedByCurrentVersion(DataRow requestedCollectionRow){
}
// if the minmum version was ok what about the maximum version
- if (result == true) {
+ if (result == true)
+ {
versionColumn = tableColumns[_maximumVersion];
- if (versionColumn != null) {
+ if (versionColumn != null)
+ {
version = requestedCollectionRow[versionColumn];
- if (version != null) {
- if (version != DBNull.Value) {
- if (0 < string.Compare( _normalizedServerVersion,(string)version, StringComparison.OrdinalIgnoreCase)){
+ if (version != null)
+ {
+ if (version != DBNull.Value)
+ {
+ if (0 < string.Compare(_normalizedServerVersion, (string)version, StringComparison.OrdinalIgnoreCase))
+ {
result = false;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbReferenceCollection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbReferenceCollection.cs
index bc373d066a..b4efafe2cb 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbReferenceCollection.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbReferenceCollection.cs
@@ -2,52 +2,63 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
- using System.Collections;
- using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
- internal abstract class DbReferenceCollection {
+ internal abstract class DbReferenceCollection
+ {
- private struct CollectionEntry {
+ private struct CollectionEntry
+ {
private int _tag; // information about the reference
private WeakReference _weak; // the reference itself.
- public void NewTarget(int tag, object target) {
+ public void NewTarget(int tag, object target)
+ {
Debug.Assert(!HasTarget, "Entry already has a valid target");
Debug.Assert(tag != 0, "Bad tag");
Debug.Assert(target != null, "Invalid target");
- if (_weak == null) {
+ if (_weak == null)
+ {
_weak = new WeakReference(target, false);
}
- else {
+ else
+ {
_weak.Target = target;
}
_tag = tag;
}
- public void RemoveTarget() {
+ public void RemoveTarget()
+ {
_tag = 0;
}
- public bool HasTarget {
- get {
+ public bool HasTarget
+ {
+ get
+ {
return ((_tag != 0) && (_weak.IsAlive));
}
}
-
- public int Tag {
- get {
- return _tag;
+
+ public int Tag
+ {
+ get
+ {
+ return _tag;
}
}
- public object Target {
- get {
+ public object Target
+ {
+ get
+ {
return (_tag == 0 ? null : _weak.Target);
}
}
@@ -61,7 +72,8 @@ public object Target {
private int _lastItemIndex; // Location of the last item in _items
private volatile bool _isNotifying; // Indicates that the collection is currently being notified (and, therefore, about to be cleared)
- protected DbReferenceCollection() {
+ protected DbReferenceCollection()
+ {
_items = new CollectionEntry[DefaultCollectionSize];
_itemLock = new object();
_optimisticCount = 0;
@@ -70,14 +82,18 @@ protected DbReferenceCollection() {
abstract public void Add(object value, int tag);
- protected void AddItem(object value, int tag) {
+ protected void AddItem(object value, int tag)
+ {
Debug.Assert(null != value && 0 != tag, "AddItem with null value or 0 tag");
bool itemAdded = false;
- lock (_itemLock) {
+ lock (_itemLock)
+ {
// Try to find a free spot
- for (int i = 0; i <= _lastItemIndex; ++i) {
- if (_items[i].Tag == 0) {
+ for (int i = 0; i <= _lastItemIndex; ++i)
+ {
+ if (_items[i].Tag == 0)
+ {
_items[i].NewTarget(tag, value);
Debug.Assert(_items[i].HasTarget, "missing expected target");
itemAdded = true;
@@ -86,16 +102,20 @@ protected void AddItem(object value, int tag) {
}
// No free spots, can we just add on to the end?
- if ((!itemAdded) && (_lastItemIndex + 1 < _items.Length)) {
+ if ((!itemAdded) && (_lastItemIndex + 1 < _items.Length))
+ {
_lastItemIndex++;
_items[_lastItemIndex].NewTarget(tag, value);
itemAdded = true;
}
// If no free spots and no space at the end, try to find a dead item
- if (!itemAdded) {
- for (int i = 0; i <= _lastItemIndex; ++i) {
- if (!_items[i].HasTarget) {
+ if (!itemAdded)
+ {
+ for (int i = 0; i <= _lastItemIndex; ++i)
+ {
+ if (!_items[i].HasTarget)
+ {
_items[i].NewTarget(tag, value);
Debug.Assert(_items[i].HasTarget, "missing expected target");
itemAdded = true;
@@ -105,7 +125,8 @@ protected void AddItem(object value, int tag) {
}
// If nothing was free, then resize and add to the end
- if (!itemAdded) {
+ if (!itemAdded)
+ {
Array.Resize(ref _items, _items.Length * 2);
_lastItemIndex++;
_items[_lastItemIndex].NewTarget(tag, value);
@@ -115,23 +136,31 @@ protected void AddItem(object value, int tag) {
}
}
- internal T FindItem(int tag, Func filterMethod) where T : class {
+ internal T FindItem(int tag, Func filterMethod) where T : class
+ {
bool lockObtained = false;
- try {
+ try
+ {
TryEnterItemLock(ref lockObtained);
- if (lockObtained) {
- if (_optimisticCount > 0) {
+ if (lockObtained)
+ {
+ if (_optimisticCount > 0)
+ {
// Loop through the items
- for (int counter = 0; counter <= _lastItemIndex; counter++) {
+ for (int counter = 0; counter <= _lastItemIndex; counter++)
+ {
// Check tag (should be easiest and quickest)
- if (_items[counter].Tag == tag) {
+ if (_items[counter].Tag == tag)
+ {
// NOTE: Check if the returned value is null twice may seem wasteful, but this if for performance
// Since checking for null twice is cheaper than calling both HasTarget and Target OR always attempting to typecast
object value = _items[counter].Target;
- if (value != null) {
+ if (value != null)
+ {
// Make sure the item has the correct type and passes the filtering
T tempItem = value as T;
- if ((tempItem != null) && (filterMethod(tempItem))) {
+ if ((tempItem != null) && (filterMethod(tempItem)))
+ {
return tempItem;
}
}
@@ -140,7 +169,8 @@ internal T FindItem(int tag, Func filterMethod) where T : class {
}
}
}
- finally {
+ finally
+ {
ExitItemLockIfNeeded(lockObtained);
}
@@ -148,19 +178,26 @@ internal T FindItem(int tag, Func filterMethod) where T : class {
return null;
}
- public void Notify(int message) {
+ public void Notify(int message)
+ {
bool lockObtained = false;
- try {
+ try
+ {
TryEnterItemLock(ref lockObtained);
- if (lockObtained) {
- try {
+ if (lockObtained)
+ {
+ try
+ {
_isNotifying = true;
// Loop through each live item and notify it
- if (_optimisticCount > 0) {
- for (int index = 0; index <= _lastItemIndex; ++index) {
+ if (_optimisticCount > 0)
+ {
+ for (int index = 0; index <= _lastItemIndex; ++index)
+ {
object value = _items[index].Target; // checks tag & gets target
- if (null != value) {
+ if (null != value)
+ {
NotifyItem(message, _items[index].Tag, value);
_items[index].RemoveTarget();
}
@@ -168,19 +205,22 @@ public void Notify(int message) {
}
_optimisticCount = 0;
}
-
+
// Shrink collection (if needed)
- if (_items.Length > 100) {
+ if (_items.Length > 100)
+ {
_lastItemIndex = 0;
_items = new CollectionEntry[DefaultCollectionSize];
}
}
- finally {
+ finally
+ {
_isNotifying = false;
}
}
}
- finally {
+ finally
+ {
ExitItemLockIfNeeded(lockObtained);
}
}
@@ -189,18 +229,24 @@ public void Notify(int message) {
abstract public void Remove(object value);
- protected void RemoveItem(object value) {
+ protected void RemoveItem(object value)
+ {
Debug.Assert(null != value, "RemoveItem with null");
bool lockObtained = false;
- try {
+ try
+ {
TryEnterItemLock(ref lockObtained);
- if (lockObtained) {
+ if (lockObtained)
+ {
// Find the value, and then remove the target from our collection
- if (_optimisticCount > 0) {
- for (int index = 0; index <= _lastItemIndex; ++index) {
- if (value == _items[index].Target) { // checks tag & gets target
+ if (_optimisticCount > 0)
+ {
+ for (int index = 0; index <= _lastItemIndex; ++index)
+ {
+ if (value == _items[index].Target)
+ { // checks tag & gets target
_items[index].RemoveTarget();
_optimisticCount--;
break;
@@ -209,23 +255,28 @@ protected void RemoveItem(object value) {
}
}
}
- finally {
+ finally
+ {
ExitItemLockIfNeeded(lockObtained);
}
}
// This is polling lock that will abandon getting the lock if _isNotifying is set to true
- private void TryEnterItemLock(ref bool lockObtained) {
+ private void TryEnterItemLock(ref bool lockObtained)
+ {
// Assume that we couldn't take the lock
lockObtained = false;
// Keep trying to take the lock until either we've taken it, or the collection is being notified
- while ((!_isNotifying) && (!lockObtained)) {
+ while ((!_isNotifying) && (!lockObtained))
+ {
Monitor.TryEnter(_itemLock, LockPollTime, ref lockObtained);
}
}
- private void ExitItemLockIfNeeded(bool lockObtained) {
- if (lockObtained) {
+ private void ExitItemLockIfNeeded(bool lockObtained)
+ {
+ if (lockObtained)
+ {
Monitor.Exit(_itemLock);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/FieldNameLookup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/FieldNameLookup.cs
index c6e5e0a0da..48ad75a507 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/FieldNameLookup.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/FieldNameLookup.cs
@@ -2,18 +2,16 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
-
- using System;
+namespace Microsoft.Data.ProviderBase
+{
using System.Collections;
- using System.ComponentModel;
using System.Data;
- using Microsoft.Data.Common;
using System.Diagnostics;
using System.Globalization;
- using System.Text;
-
- internal sealed class FieldNameLookup { // V1.2.3300, MDAC 69015, 71470
+ using Microsoft.Data.Common;
+
+ internal sealed class FieldNameLookup
+ { // V1.2.3300, MDAC 69015, 71470
// hashtable stores the index into the _fieldNames, match via case-sensitive
private Hashtable _fieldNameLookup;
@@ -26,19 +24,23 @@ internal sealed class FieldNameLookup { // V1.2.3300, MDAC 69015, 71470
private CompareInfo _compareInfo;
private int _defaultLocaleID;
- public FieldNameLookup(string[] fieldNames, int defaultLocaleID) { // V1.2.3300
- if (null == fieldNames) {
+ public FieldNameLookup(string[] fieldNames, int defaultLocaleID)
+ { // V1.2.3300
+ if (null == fieldNames)
+ {
throw ADP.ArgumentNull("fieldNames");
}
_fieldNames = fieldNames;
_defaultLocaleID = defaultLocaleID;
}
- public FieldNameLookup(System.Collections.ObjectModel.ReadOnlyCollection columnNames, int defaultLocaleID) {
+ public FieldNameLookup(System.Collections.ObjectModel.ReadOnlyCollection columnNames, int defaultLocaleID)
+ {
int length = columnNames.Count;
string[] fieldNames = new string[length];
- for (int i = 0; i < length; ++i) {
+ for (int i = 0; i < length; ++i)
+ {
fieldNames[i] = columnNames[i];
Debug.Assert(null != fieldNames[i], "MDAC 66681");
}
@@ -47,11 +49,13 @@ public FieldNameLookup(System.Collections.ObjectModel.ReadOnlyCollection
GenerateLookup();
}
- public FieldNameLookup(IDataRecord reader, int defaultLocaleID) { // V1.2.3300
+ public FieldNameLookup(IDataRecord reader, int defaultLocaleID)
+ { // V1.2.3300
int length = reader.FieldCount;
string[] fieldNames = new string[length];
- for (int i = 0; i < length; ++i) {
+ for (int i = 0; i < length; ++i)
+ {
fieldNames[i] = reader.GetName(i);
Debug.Assert(null != fieldNames[i], "MDAC 66681");
}
@@ -59,40 +63,50 @@ public FieldNameLookup(IDataRecord reader, int defaultLocaleID) { // V1.2.3300
_defaultLocaleID = defaultLocaleID;
}
- public int GetOrdinal(string fieldName) { // V1.2.3300
- if (null == fieldName) {
+ public int GetOrdinal(string fieldName)
+ { // V1.2.3300
+ if (null == fieldName)
+ {
throw ADP.ArgumentNull("fieldName");
}
int index = IndexOf(fieldName);
- if (-1 == index) {
+ if (-1 == index)
+ {
throw ADP.IndexOutOfRange(fieldName);
}
return index;
}
- public int IndexOfName(string fieldName) { // V1.2.3300
- if (null == _fieldNameLookup) {
+ public int IndexOfName(string fieldName)
+ { // V1.2.3300
+ if (null == _fieldNameLookup)
+ {
GenerateLookup();
}
// via case sensitive search, first match with lowest ordinal matches
object value = _fieldNameLookup[fieldName];
- return ((null != value) ? (int) value : -1);
+ return ((null != value) ? (int)value : -1);
}
- public int IndexOf(string fieldName) { // V1.2.3300
- if (null == _fieldNameLookup) {
+ public int IndexOf(string fieldName)
+ { // V1.2.3300
+ if (null == _fieldNameLookup)
+ {
GenerateLookup();
}
int index;
object value = _fieldNameLookup[fieldName];
- if (null != value) {
+ if (null != value)
+ {
// via case sensitive search, first match with lowest ordinal matches
- index = (int) value;
+ index = (int)value;
}
- else {
+ else
+ {
// via case insensitive search, first match with lowest ordinal matches
index = LinearIndexOf(fieldName, CompareOptions.IgnoreCase);
- if (-1 == index) {
+ if (-1 == index)
+ {
// do the slow search now (kana, width insensitive comparison)
index = LinearIndexOf(fieldName, ADP.compareOptions);
}
@@ -100,20 +114,26 @@ public int IndexOf(string fieldName) { // V1.2.3300
return index;
}
- private int LinearIndexOf(string fieldName, CompareOptions compareOptions) {
+ private int LinearIndexOf(string fieldName, CompareOptions compareOptions)
+ {
CompareInfo compareInfo = _compareInfo;
- if (null == compareInfo) {
- if (-1 != _defaultLocaleID) {
+ if (null == compareInfo)
+ {
+ if (-1 != _defaultLocaleID)
+ {
compareInfo = CompareInfo.GetCompareInfo(_defaultLocaleID);
}
- if (null == compareInfo) {
+ if (null == compareInfo)
+ {
compareInfo = CultureInfo.InvariantCulture.CompareInfo;
}
_compareInfo = compareInfo;
}
int length = _fieldNames.Length;
- for (int i = 0; i < length; ++i) {
- if (0 == compareInfo.Compare(fieldName, _fieldNames[i], compareOptions)) {
+ for (int i = 0; i < length; ++i)
+ {
+ if (0 == compareInfo.Compare(fieldName, _fieldNames[i], compareOptions))
+ {
_fieldNameLookup[fieldName] = i; // add an exact match for the future
return i;
}
@@ -122,12 +142,14 @@ private int LinearIndexOf(string fieldName, CompareOptions compareOptions) {
}
// RTM common code for generating Hashtable from array of column names
- private void GenerateLookup() {
+ private void GenerateLookup()
+ {
int length = _fieldNames.Length;
Hashtable hash = new Hashtable(length);
// via case sensitive search, first match with lowest ordinal matches
- for (int i = length-1; 0 <= i; --i) {
+ for (int i = length - 1; 0 <= i; --i)
+ {
string fieldName = _fieldNames[i];
hash[fieldName] = i;
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs
index 5656eda529..1e64061282 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs
@@ -5,38 +5,41 @@
namespace Microsoft.Data.SqlClient
{
using System;
- using Microsoft.Data.Common;
- using Microsoft.Data.ProviderBase;
+ using System.Data;
+ using System.Data.Common;
using System.Diagnostics;
using System.Runtime.ConstrainedExecution;
using System.Threading;
+ using Microsoft.Data.Common;
+ using Microsoft.Data.ProviderBase;
using SysTx = System.Transactions;
- using System.Data;
- using System.Data.Common;
- public sealed partial class SqlConnection : DbConnection {
- private static readonly DbConnectionFactory _connectionFactory = SqlConnectionFactory.SingletonInstance;
+ public sealed partial class SqlConnection : DbConnection
+ {
+ private static readonly DbConnectionFactory _connectionFactory = SqlConnectionFactory.SingletonInstance;
internal static readonly System.Security.CodeAccessPermission ExecutePermission = SqlConnection.CreateExecutePermission();
- private DbConnectionOptions _userConnectionOptions;
- private DbConnectionPoolGroup _poolGroup;
- private DbConnectionInternal _innerConnection;
- private int _closeCount; // used to distinguish between different uses of this object, so we don't have to maintain a list of it's children
+ private DbConnectionOptions _userConnectionOptions;
+ private DbConnectionPoolGroup _poolGroup;
+ private DbConnectionInternal _innerConnection;
+ private int _closeCount; // used to distinguish between different uses of this object, so we don't have to maintain a list of it's children
private static int _objectTypeCount; // Bid counter
internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
- public SqlConnection() : base() {
+ public SqlConnection() : base()
+ {
GC.SuppressFinalize(this);
_innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
// Copy Constructor
- private void CopyFrom(SqlConnection connection) { // V1.2.3300
+ private void CopyFrom(SqlConnection connection)
+ { // V1.2.3300
ADP.CheckArgumentNull(connection, "connection");
_userConnectionOptions = connection.UserConnectionOptions;
_poolGroup = connection.PoolGroup;
-
+
// SQLBU 432115
// Match the original connection's behavior for whether the connection was never opened,
// but ensure Clone is in the closed state.
@@ -55,54 +58,65 @@ private void CopyFrom(SqlConnection connection) { // V1.2.3300
/// would be affected by a close, we simply increment the _closeCount
/// and have each of our children check to see if they're "orphaned"
///
- internal int CloseCount {
- get {
+ internal int CloseCount
+ {
+ get
+ {
return _closeCount;
}
}
- internal DbConnectionFactory ConnectionFactory {
- get {
+ internal DbConnectionFactory ConnectionFactory
+ {
+ get
+ {
return _connectionFactory;
}
}
- internal DbConnectionOptions ConnectionOptions {
- get {
+ internal DbConnectionOptions ConnectionOptions
+ {
+ get
+ {
Microsoft.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup;
return ((null != poolGroup) ? poolGroup.ConnectionOptions : null);
}
}
- private string ConnectionString_Get() {
- Bid.Trace( " %d#\n", ObjectID);
+ private string ConnectionString_Get()
+ {
+ Bid.Trace(" %d#\n", ObjectID);
bool hidePassword = InnerConnection.ShouldHidePassword;
DbConnectionOptions connectionOptions = UserConnectionOptions;
return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : "");
}
- private void ConnectionString_Set(string value) {
+ private void ConnectionString_Set(string value)
+ {
DbConnectionPoolKey key = new DbConnectionPoolKey(value);
ConnectionString_Set(key);
}
- private void ConnectionString_Set(DbConnectionPoolKey key) {
+ private void ConnectionString_Set(DbConnectionPoolKey key)
+ {
DbConnectionOptions connectionOptions = null;
Microsoft.Data.ProviderBase.DbConnectionPoolGroup poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions);
DbConnectionInternal connectionInternal = InnerConnection;
bool flag = connectionInternal.AllowSetConnectionString;
- if (flag) {
+ if (flag)
+ {
//try {
- // NOTE: There's a race condition with multiple threads changing
- // ConnectionString and any thread throws an exception
- // Closed->Busy: prevent Open during set_ConnectionString
- flag = SetInnerConnectionFrom(DbConnectionClosedBusy.SingletonInstance, connectionInternal);
- if (flag) {
- _userConnectionOptions = connectionOptions;
- _poolGroup = poolGroup;
- _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
- }
+ // NOTE: There's a race condition with multiple threads changing
+ // ConnectionString and any thread throws an exception
+ // Closed->Busy: prevent Open during set_ConnectionString
+ flag = SetInnerConnectionFrom(DbConnectionClosedBusy.SingletonInstance, connectionInternal);
+ if (flag)
+ {
+ _userConnectionOptions = connectionOptions;
+ _poolGroup = poolGroup;
+ _innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
+ }
//}
//catch {
// // recover from exceptions to avoid sticking in busy state
@@ -110,44 +124,55 @@ private void ConnectionString_Set(DbConnectionPoolKey key) {
// throw;
//}
}
- if (!flag) {
+ if (!flag)
+ {
throw ADP.OpenConnectionPropertySet(ADP.ConnectionString, connectionInternal.State);
}
- if (Bid.TraceOn) {
+ if (Bid.TraceOn)
+ {
string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : "");
Bid.Trace(" %d#, '%ls'\n", ObjectID, cstr);
}
}
- internal DbConnectionInternal InnerConnection {
- get {
+ internal DbConnectionInternal InnerConnection
+ {
+ get
+ {
return _innerConnection;
}
}
- internal Microsoft.Data.ProviderBase.DbConnectionPoolGroup PoolGroup {
- get {
+ internal Microsoft.Data.ProviderBase.DbConnectionPoolGroup PoolGroup
+ {
+ get
+ {
return _poolGroup;
}
- set {
+ set
+ {
// when a poolgroup expires and the connection eventually activates, the pool entry will be replaced
Debug.Assert(null != value, "null poolGroup");
_poolGroup = value;
}
}
-
- internal DbConnectionOptions UserConnectionOptions {
- get {
+
+ internal DbConnectionOptions UserConnectionOptions
+ {
+ get
+ {
return _userConnectionOptions;
}
}
// Open->ClosedPreviouslyOpened, and doom the internal connection too...
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal void Abort(Exception e) {
+ internal void Abort(Exception e)
+ {
DbConnectionInternal innerConnection = _innerConnection; // Should not cause memory allocation...
- if (ConnectionState.Open == innerConnection.State) {
+ if (ConnectionState.Open == innerConnection.State)
+ {
Interlocked.CompareExchange(ref _innerConnection, DbConnectionClosedPreviouslyOpened.SingletonInstance, innerConnection);
innerConnection.DoomThisConnection();
}
@@ -155,44 +180,53 @@ internal void Abort(Exception e) {
// NOTE: we put the tracing last, because the ToString() calls (and
// the Bid.Trace, for that matter) have no reliability contract and
// will end the reliable try...
- if (e is OutOfMemoryException) {
+ if (e is OutOfMemoryException)
+ {
Bid.Trace(" %d#, Aborting operation due to asynchronous exception: %ls\n", ObjectID, "OutOfMemory");
}
- else {
+ else
+ {
Bid.Trace(" %d#, Aborting operation due to asynchronous exception: %ls\n", ObjectID, e.ToString());
}
}
- internal void AddWeakReference(object value, int tag) {
+ internal void AddWeakReference(object value, int tag)
+ {
InnerConnection.AddWeakReference(value, tag);
}
- override protected DbCommand CreateDbCommand() {
+ override protected DbCommand CreateDbCommand()
+ {
DbCommand command = null;
IntPtr hscp;
Bid.ScopeEnter(out hscp, " %d#\n", ObjectID);
- try {
+ try
+ {
DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory;
command = providerFactory.CreateCommand();
command.Connection = this;
}
- finally {
+ finally
+ {
Bid.ScopeLeave(ref hscp);
}
return command;
}
- private static System.Security.CodeAccessPermission CreateExecutePermission() {
+ private static System.Security.CodeAccessPermission CreateExecutePermission()
+ {
DBDataPermission p = (DBDataPermission)SqlConnectionFactory.SingletonInstance.ProviderFactory.CreatePermission(System.Security.Permissions.PermissionState.None);
p.Add(String.Empty, String.Empty, KeyRestrictionBehavior.AllowOnly);
return p;
}
- override protected void Dispose(bool disposing) {
- if (disposing) {
+ override protected void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
_userConnectionOptions = null;
- _poolGroup= null;
+ _poolGroup = null;
Close();
}
DisposeMe(disposing);
@@ -204,16 +238,18 @@ override protected void Dispose(bool disposing) {
// NOTE: This is just a private helper because OracleClient V1.1 shipped
// with a different argument name and it's a breaking change to not use
// the same argument names in V2.0 (VB Named Parameter Binding--Ick)
- private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITransaction transaction) {
+ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITransaction transaction)
+ {
System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);
permissionSet.AddPermission(SqlConnection.ExecutePermission); // MDAC 81476
permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode));
permissionSet.Demand();
- Bid.Trace( " %d#, Connection enlisting in a transaction.\n", ObjectID);
+ Bid.Trace(" %d#, Connection enlisting in a transaction.\n", ObjectID);
SysTx.Transaction indigoTransaction = null;
- if (null != transaction) {
+ if (null != transaction)
+ {
indigoTransaction = SysTx.TransactionInterop.GetTransactionFromDtcTransaction((SysTx.IDtcTransaction)transaction);
}
@@ -230,10 +266,11 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans
GC.KeepAlive(this);
}
- override public void EnlistTransaction(SysTx.Transaction transaction) {
+ override public void EnlistTransaction(SysTx.Transaction transaction)
+ {
SqlConnection.ExecutePermission.Demand();
- Bid.Trace( " %d#, Connection enlisting in a transaction.\n", ObjectID);
+ Bid.Trace(" %d#, Connection enlisting in a transaction.\n", ObjectID);
// If we're currently enlisted in a transaction and we were called
// on the EnlistTransaction method (Whidbey) we're not allowed to
@@ -245,9 +282,11 @@ override public void EnlistTransaction(SysTx.Transaction transaction) {
// server, we don't want to lock here, we'll handle the race conditions
// elsewhere.
SysTx.Transaction enlistedTransaction = innerConnection.EnlistedTransaction;
- if (enlistedTransaction != null) {
+ if (enlistedTransaction != null)
+ {
// Allow calling enlist if already enlisted (no-op)
- if (enlistedTransaction.Equals(transaction)) {
+ if (enlistedTransaction.Equals(transaction))
+ {
return;
}
@@ -267,39 +306,47 @@ override public void EnlistTransaction(SysTx.Transaction transaction) {
GC.KeepAlive(this);
}
- private DbMetaDataFactory GetMetaDataFactory(DbConnectionInternal internalConnection) {
+ private DbMetaDataFactory GetMetaDataFactory(DbConnectionInternal internalConnection)
+ {
return ConnectionFactory.GetMetaDataFactory(_poolGroup, internalConnection);
}
- internal DbMetaDataFactory GetMetaDataFactoryInternal(DbConnectionInternal internalConnection) {
+ internal DbMetaDataFactory GetMetaDataFactoryInternal(DbConnectionInternal internalConnection)
+ {
return GetMetaDataFactory(internalConnection);
}
- override public DataTable GetSchema() {
+ override public DataTable GetSchema()
+ {
return this.GetSchema(DbMetaDataCollectionNames.MetaDataCollections, null);
}
- override public DataTable GetSchema(string collectionName) {
+ override public DataTable GetSchema(string collectionName)
+ {
return this.GetSchema(collectionName, null);
}
- override public DataTable GetSchema(string collectionName, string[] restrictionValues) {
+ override public DataTable GetSchema(string collectionName, string[] restrictionValues)
+ {
// NOTE: This is virtual because not all providers may choose to support
// returning schema data
SqlConnection.ExecutePermission.Demand();
return InnerConnection.GetSchema(ConnectionFactory, PoolGroup, this, collectionName, restrictionValues);
}
- internal void NotifyWeakReference(int message) {
+ internal void NotifyWeakReference(int message)
+ {
InnerConnection.NotifyWeakReference(message);
}
- internal void PermissionDemand() {
+ internal void PermissionDemand()
+ {
Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting");
Microsoft.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup;
DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null);
- if ((null == connectionOptions) || connectionOptions.IsEmpty) {
+ if ((null == connectionOptions) || connectionOptions.IsEmpty)
+ {
throw ADP.NoConnectionString();
}
@@ -309,13 +356,15 @@ internal void PermissionDemand() {
userConnectionOptions.DemandPermission();
}
- internal void RemoveWeakReference(object value) {
+ internal void RemoveWeakReference(object value)
+ {
InnerConnection.RemoveWeakReference(value);
}
// OpenBusy->Closed (previously opened)
// Connecting->Open
- internal void SetInnerConnectionEvent(DbConnectionInternal to) {
+ internal void SetInnerConnectionEvent(DbConnectionInternal to)
+ {
// Set's the internal connection without verifying that it's a specific value
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != to, "to null InnerConnection");
@@ -323,22 +372,28 @@ internal void SetInnerConnectionEvent(DbConnectionInternal to) {
ConnectionState originalState = _innerConnection.State & ConnectionState.Open;
ConnectionState currentState = to.State & ConnectionState.Open;
- if ((originalState != currentState) && (ConnectionState.Closed == currentState)) {
+ if ((originalState != currentState) && (ConnectionState.Closed == currentState))
+ {
// Increment the close count whenever we switch to Closed
- unchecked { _closeCount++; }
+ unchecked
+ { _closeCount++; }
}
_innerConnection = to;
- if (ConnectionState.Closed == originalState && ConnectionState.Open == currentState) {
+ if (ConnectionState.Closed == originalState && ConnectionState.Open == currentState)
+ {
OnStateChange(DbConnectionInternal.StateChangeOpen);
}
- else if (ConnectionState.Open == originalState && ConnectionState.Closed == currentState) {
+ else if (ConnectionState.Open == originalState && ConnectionState.Closed == currentState)
+ {
OnStateChange(DbConnectionInternal.StateChangeClosed);
}
- else {
+ else
+ {
Debug.Fail("unexpected state switch");
- if (originalState != currentState) {
+ if (originalState != currentState)
+ {
OnStateChange(new StateChangeEventArgs(originalState, currentState));
}
}
@@ -350,7 +405,8 @@ internal void SetInnerConnectionEvent(DbConnectionInternal to) {
// Closed->Connecting: prevent set_ConnectionString during Open
// Open->OpenBusy: guarantee internal connection is returned to correct pool
// Closed->ClosedBusy: prevent Open during set_ConnectionString
- internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from) {
+ internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from)
+ {
// Set's the internal connection, verifying that it's a specific value before doing so.
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != from, "from null InnerConnection");
@@ -362,7 +418,8 @@ internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionIntern
// ClosedBusy->Closed (never opened)
// Connecting->Closed (exception during open, return to previous closed state)
- internal void SetInnerConnectionTo(DbConnectionInternal to) {
+ internal void SetInnerConnectionTo(DbConnectionInternal to)
+ {
// Set's the internal connection without verifying that it's a specific value
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != to, "to null InnerConnection");
@@ -370,12 +427,15 @@ internal void SetInnerConnectionTo(DbConnectionInternal to) {
}
[ConditionalAttribute("DEBUG")]
- internal static void VerifyExecutePermission() {
- try {
+ internal static void VerifyExecutePermission()
+ {
+ try
+ {
// use this to help validate this code path is only used after the following permission has been previously demanded in the current codepath
SqlConnection.ExecutePermission.Demand();
}
- catch(System.Security.SecurityException) {
+ catch (System.Security.SecurityException)
+ {
System.Diagnostics.Debug.Assert(false, "unexpected SecurityException for current codepath");
throw;
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlParameterCollectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlParameterCollectionHelper.cs
index e080153979..aab8236839 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlParameterCollectionHelper.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlParameterCollectionHelper.cs
@@ -7,29 +7,32 @@ namespace Microsoft.Data.SqlClient
using System;
using System.Collections.Generic;
using System.ComponentModel;
- using Microsoft.Data;
- using Microsoft.Data.Common;
- using Microsoft.Data.ProviderBase;
+ using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Data.Common;
+ using Microsoft.Data.Common;
- public sealed partial class SqlParameterCollection : DbParameterCollection {
+ public sealed partial class SqlParameterCollection : DbParameterCollection
+ {
private List _items; // the collection of parameters
- override public int Count {
- get {
+ override public int Count
+ {
+ get
+ {
// NOTE: we don't construct the list just to get the count.
return ((null != _items) ? _items.Count : 0);
}
}
- private List InnerList {
- get {
+ private List InnerList
+ {
+ get
+ {
List items = _items;
- if (null == items) {
+ if (null == items)
+ {
items = new List();
_items = items;
}
@@ -37,26 +40,34 @@ private List InnerList {
}
}
- override public bool IsFixedSize {
- get {
+ override public bool IsFixedSize
+ {
+ get
+ {
return ((System.Collections.IList)InnerList).IsFixedSize;
}
}
- override public bool IsReadOnly {
- get {
+ override public bool IsReadOnly
+ {
+ get
+ {
return ((System.Collections.IList)InnerList).IsReadOnly;
}
}
- override public bool IsSynchronized {
- get {
+ override public bool IsSynchronized
+ {
+ get
+ {
return ((System.Collections.ICollection)InnerList).IsSynchronized;
}
}
- override public object SyncRoot {
- get {
+ override public object SyncRoot
+ {
+ get
+ {
return ((System.Collections.ICollection)InnerList).SyncRoot;
}
}
@@ -64,87 +75,109 @@ override public object SyncRoot {
[
EditorBrowsableAttribute(EditorBrowsableState.Never)
]
- override public int Add(object value) {
+ override public int Add(object value)
+ {
OnChange(); // fire event before value is validated
ValidateType(value);
Validate(-1, value);
InnerList.Add((SqlParameter)value);
- return Count-1;
+ return Count - 1;
}
- override public void AddRange(System.Array values) {
+ override public void AddRange(System.Array values)
+ {
OnChange(); // fire event before value is validated
- if (null == values) {
+ if (null == values)
+ {
throw ADP.ArgumentNull("values");
}
- foreach(object value in values) {
+ foreach (object value in values)
+ {
ValidateType(value);
}
- foreach(SqlParameter value in values) {
+ foreach (SqlParameter value in values)
+ {
Validate(-1, value);
InnerList.Add((SqlParameter)value);
}
}
- private int CheckName(string parameterName) {
+ private int CheckName(string parameterName)
+ {
int index = IndexOf(parameterName);
- if (index < 0) {
+ if (index < 0)
+ {
throw ADP.ParametersSourceIndex(parameterName, this, ItemType);
}
return index;
}
- override public void Clear() {
+ override public void Clear()
+ {
OnChange(); // fire event before value is validated
List items = InnerList;
- if (null != items) {
- foreach(SqlParameter item in items) {
+ if (null != items)
+ {
+ foreach (SqlParameter item in items)
+ {
item.ResetParent();
}
items.Clear();
}
}
- override public bool Contains(object value) {
+ override public bool Contains(object value)
+ {
return (-1 != IndexOf(value));
}
- override public void CopyTo(Array array, int index) {
+ override public void CopyTo(Array array, int index)
+ {
((System.Collections.ICollection)InnerList).CopyTo(array, index);
}
- override public System.Collections.IEnumerator GetEnumerator() {
+ override public System.Collections.IEnumerator GetEnumerator()
+ {
return ((System.Collections.ICollection)InnerList).GetEnumerator();
}
- override protected DbParameter GetParameter(int index) {
+ override protected DbParameter GetParameter(int index)
+ {
RangeCheck(index);
return InnerList[index];
}
- override protected DbParameter GetParameter(string parameterName) {
+ override protected DbParameter GetParameter(string parameterName)
+ {
int index = IndexOf(parameterName);
- if (index < 0) {
+ if (index < 0)
+ {
throw ADP.ParametersSourceIndex(parameterName, this, ItemType);
}
return InnerList[index];
}
- private static int IndexOf(System.Collections.IEnumerable items, string parameterName) {
- if (null != items) {
+ private static int IndexOf(System.Collections.IEnumerable items, string parameterName)
+ {
+ if (null != items)
+ {
int i = 0;
// first case, kana, width sensitive search
- foreach(SqlParameter parameter in items) {
- if (0 == ADP.SrcCompare(parameterName, parameter.ParameterName)) {
+ foreach (SqlParameter parameter in items)
+ {
+ if (0 == ADP.SrcCompare(parameterName, parameter.ParameterName))
+ {
return i;
}
++i;
}
i = 0;
// then insensitive search
- foreach(SqlParameter parameter in items) {
- if (0 == ADP.DstCompare(parameterName, parameter.ParameterName)) {
+ foreach (SqlParameter parameter in items)
+ {
+ if (0 == ADP.DstCompare(parameterName, parameter.ParameterName))
+ {
return i;
}
++i;
@@ -153,21 +186,27 @@ private static int IndexOf(System.Collections.IEnumerable items, string paramete
return -1;
}
- override public int IndexOf(string parameterName) {
+ override public int IndexOf(string parameterName)
+ {
return IndexOf(InnerList, parameterName);
}
- override public int IndexOf(object value) {
- if (null != value) {
+ override public int IndexOf(object value)
+ {
+ if (null != value)
+ {
ValidateType(value);
List items = InnerList;
- if (null != items) {
+ if (null != items)
+ {
int count = items.Count;
- for (int i = 0; i < count; i++) {
- if (value == items[i]) {
+ for (int i = 0; i < count; i++)
+ {
+ if (value == items[i])
+ {
return i;
}
}
@@ -176,44 +215,53 @@ override public int IndexOf(object value) {
return -1;
}
- override public void Insert(int index, object value) {
+ override public void Insert(int index, object value)
+ {
OnChange(); // fire event before value is validated
ValidateType(value);
Validate(-1, (SqlParameterCollection)value);
InnerList.Insert(index, (SqlParameter)value);
}
- private void RangeCheck(int index) {
- if ((index < 0) || (Count <= index)) {
+ private void RangeCheck(int index)
+ {
+ if ((index < 0) || (Count <= index))
+ {
throw ADP.ParametersMappingIndex(index, this);
}
}
- override public void Remove(object value) {
+ override public void Remove(object value)
+ {
OnChange(); // fire event before value is validated
ValidateType(value);
int index = IndexOf(value);
- if (-1 != index) {
+ if (-1 != index)
+ {
RemoveIndex(index);
}
- else if (this != ((SqlParameter)value).CompareExchangeParent(null, this)) {
+ else if (this != ((SqlParameter)value).CompareExchangeParent(null, this))
+ {
throw ADP.CollectionRemoveInvalidObject(ItemType, this);
}
}
- override public void RemoveAt(int index) {
+ override public void RemoveAt(int index)
+ {
OnChange(); // fire event before value is validated
RangeCheck(index);
RemoveIndex(index);
}
- override public void RemoveAt(string parameterName) {
+ override public void RemoveAt(string parameterName)
+ {
OnChange(); // fire event before value is validated
int index = CheckName(parameterName);
RemoveIndex(index);
}
- private void RemoveIndex(int index) {
+ private void RemoveIndex(int index)
+ {
List items = InnerList;
Debug.Assert((null != items) && (0 <= index) && (index < Count), "RemoveIndex, invalid");
SqlParameter item = items[index];
@@ -221,7 +269,8 @@ private void RemoveIndex(int index) {
item.ResetParent();
}
- private void Replace(int index, object newValue) {
+ private void Replace(int index, object newValue)
+ {
List items = InnerList;
Debug.Assert((null != items) && (0 <= index) && (index < Count), "Replace Index invalid");
ValidateType(newValue);
@@ -231,40 +280,50 @@ private void Replace(int index, object newValue) {
item.ResetParent();
}
- override protected void SetParameter(int index, DbParameter value) {
+ override protected void SetParameter(int index, DbParameter value)
+ {
OnChange(); // fire event before value is validated
RangeCheck(index);
Replace(index, value);
}
- override protected void SetParameter(string parameterName, DbParameter value) {
+ override protected void SetParameter(string parameterName, DbParameter value)
+ {
OnChange(); // fire event before value is validated
int index = IndexOf(parameterName);
- if (index < 0) {
+ if (index < 0)
+ {
throw ADP.ParametersSourceIndex(parameterName, this, ItemType);
}
Replace(index, value);
}
- private void Validate(int index, object value) {
- if (null == value) {
+ private void Validate(int index, object value)
+ {
+ if (null == value)
+ {
throw ADP.ParameterNull("value", this, ItemType);
}
// Validate assigns the parent - remove clears the parent
object parent = ((SqlParameter)value).CompareExchangeParent(this, null);
- if (null != parent) {
- if (this != parent) {
+ if (null != parent)
+ {
+ if (this != parent)
+ {
throw ADP.ParametersIsNotParent(ItemType, this);
}
- if (index != IndexOf(value)) {
+ if (index != IndexOf(value))
+ {
throw ADP.ParametersIsParent(ItemType, this);
}
}
// generate a ParameterName
String name = ((SqlParameter)value).ParameterName;
- if (0 == name.Length) {
+ if (0 == name.Length)
+ {
index = 1;
- do {
+ do
+ {
name = ADP.Parameter + index.ToString(CultureInfo.CurrentCulture);
index++;
} while (-1 != IndexOf(name));
@@ -272,11 +331,14 @@ private void Validate(int index, object value) {
}
}
- private void ValidateType(object value) {
- if (null == value) {
+ private void ValidateType(object value)
+ {
+ if (null == value)
+ {
throw ADP.ParameterNull("value", this, ItemType);
}
- else if (!ItemType.IsInstanceOfType(value)) {
+ else if (!ItemType.IsInstanceOfType(value))
+ {
throw ADP.InvalidParameterType(this, ItemType, value);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlParameterHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlParameterHelper.cs
index 87d0089171..dba3fd0926 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlParameterHelper.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlParameterHelper.cs
@@ -4,15 +4,14 @@
using System;
using System.ComponentModel;
-using Microsoft.Data;
-using Microsoft.Data.Common;
-using System.Globalization;
-using System.Data.Common;
using System.Data;
+using System.Data.Common;
+using Microsoft.Data.Common;
namespace Microsoft.Data.SqlClient
-{
- public sealed partial class SqlParameter : DbParameter { // V1.2.3300
+{
+ public sealed partial class SqlParameter : DbParameter
+ { // V1.2.3300
private object _value;
private object _parent;
@@ -30,22 +29,27 @@ public sealed partial class SqlParameter : DbParameter { // V1.2.3300
private object _coercedValue;
- private SqlParameter(SqlParameter source) : this() { // V1.2.3300, Clone
+ private SqlParameter(SqlParameter source) : this()
+ { // V1.2.3300, Clone
ADP.CheckArgumentNull(source, "source");
source.CloneHelper(this);
ICloneable cloneable = (_value as ICloneable);
- if (null != cloneable) { // MDAC 49322
+ if (null != cloneable)
+ { // MDAC 49322
_value = cloneable.Clone();
}
}
- private object CoercedValue { // V1.2.3300
- get {
+ private object CoercedValue
+ { // V1.2.3300
+ get
+ {
return _coercedValue;
}
- set {
+ set
+ {
_coercedValue = value;
}
}
@@ -55,33 +59,41 @@ private object CoercedValue { // V1.2.3300
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.DbParameter_Direction),
]
- override public ParameterDirection Direction { // V1.2.3300, XXXParameter V1.0.3300
- get {
+ override public ParameterDirection Direction
+ { // V1.2.3300, XXXParameter V1.0.3300
+ get
+ {
ParameterDirection direction = _direction;
return ((0 != direction) ? direction : ParameterDirection.Input);
}
- set {
- if (_direction != value) {
- switch (value) { // @perfnote: Enum.IsDefined
- case ParameterDirection.Input:
- case ParameterDirection.Output:
- case ParameterDirection.InputOutput:
- case ParameterDirection.ReturnValue:
- PropertyChanging();
- _direction = value;
- break;
- default:
- throw ADP.InvalidParameterDirection(value);
+ set
+ {
+ if (_direction != value)
+ {
+ switch (value)
+ { // @perfnote: Enum.IsDefined
+ case ParameterDirection.Input:
+ case ParameterDirection.Output:
+ case ParameterDirection.InputOutput:
+ case ParameterDirection.ReturnValue:
+ PropertyChanging();
+ _direction = value;
+ break;
+ default:
+ throw ADP.InvalidParameterDirection(value);
}
}
}
}
- override public bool IsNullable { // V1.2.3300, XXXParameter V1.0.3300
- get {
+ override public bool IsNullable
+ { // V1.2.3300, XXXParameter V1.0.3300
+ get
+ {
return _isNullable;
}
- set {
+ set
+ {
_isNullable = value;
}
}
@@ -93,12 +105,16 @@ private object CoercedValue { // V1.2.3300
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.DbParameter_Offset),
]
- public int Offset {
- get {
+ public int Offset
+ {
+ get
+ {
return _offset;
}
- set {
- if (value < 0) {
+ set
+ {
+ if (value < 0)
+ {
throw ADP.InvalidOffsetValue(value);
}
_offset = value;
@@ -116,17 +132,23 @@ internal int Offset {
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.DbParameter_Size),
]
- override public int Size { // V1.2.3300, XXXParameter V1.0.3300
- get {
+ override public int Size
+ { // V1.2.3300, XXXParameter V1.0.3300
+ get
+ {
int size = _size;
- if (0 == size) {
+ if (0 == size)
+ {
size = ValueSize(Value);
}
return size;
}
- set {
- if (_size != value) {
- if (value < -1) {
+ set
+ {
+ if (_size != value)
+ {
+ if (value < -1)
+ {
throw ADP.InvalidSizeValue(value);
}
PropertyChanging();
@@ -135,14 +157,17 @@ internal int Offset {
}
}
- private void ResetSize() {
- if (0 != _size) {
+ private void ResetSize()
+ {
+ if (0 != _size)
+ {
PropertyChanging();
_size = 0;
}
}
- private bool ShouldSerializeSize() { // V1.2.3300
+ private bool ShouldSerializeSize()
+ { // V1.2.3300
return (0 != _size);
}
@@ -150,21 +175,27 @@ private bool ShouldSerializeSize() { // V1.2.3300
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Update),
ResDescriptionAttribute(StringsHelper.ResourceNames.DbParameter_SourceColumn),
]
- override public string SourceColumn { // V1.2.3300, XXXParameter V1.0.3300
- get {
+ override public string SourceColumn
+ { // V1.2.3300, XXXParameter V1.0.3300
+ get
+ {
string sourceColumn = _sourceColumn;
return ((null != sourceColumn) ? sourceColumn : ADP.StrEmpty);
}
- set {
+ set
+ {
_sourceColumn = value;
}
}
- public override bool SourceColumnNullMapping {
- get {
+ public override bool SourceColumnNullMapping
+ {
+ get
+ {
return _sourceColumnNullMapping;
}
- set {
+ set
+ {
_sourceColumnNullMapping = value;
}
}
@@ -173,93 +204,113 @@ public override bool SourceColumnNullMapping {
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Update),
ResDescriptionAttribute(StringsHelper.ResourceNames.DbParameter_SourceVersion),
]
- override public DataRowVersion SourceVersion { // V1.2.3300, XXXParameter V1.0.3300
- get {
+ override public DataRowVersion SourceVersion
+ { // V1.2.3300, XXXParameter V1.0.3300
+ get
+ {
DataRowVersion sourceVersion = _sourceVersion;
return ((0 != sourceVersion) ? sourceVersion : DataRowVersion.Current);
}
- set {
- switch(value) { // @perfnote: Enum.IsDefined
- case DataRowVersion.Original:
- case DataRowVersion.Current:
- case DataRowVersion.Proposed:
- case DataRowVersion.Default:
- _sourceVersion = value;
- break;
- default:
- throw ADP.InvalidDataRowVersion(value);
+ set
+ {
+ switch (value)
+ { // @perfnote: Enum.IsDefined
+ case DataRowVersion.Original:
+ case DataRowVersion.Current:
+ case DataRowVersion.Proposed:
+ case DataRowVersion.Default:
+ _sourceVersion = value;
+ break;
+ default:
+ throw ADP.InvalidDataRowVersion(value);
}
}
}
- private void CloneHelperCore(SqlParameter destination) {
- destination._value = _value;
+ private void CloneHelperCore(SqlParameter destination)
+ {
+ destination._value = _value;
// NOTE: _parent is not cloned
- destination._direction = _direction;
- destination._size = _size;
+ destination._direction = _direction;
+ destination._size = _size;
#if USEOFFSET
- destination._offset = _offset;
+ destination._offset = _offset;
#endif
- destination._sourceColumn = _sourceColumn;
- destination._sourceVersion = _sourceVersion;
- destination._sourceColumnNullMapping = _sourceColumnNullMapping;
- destination._isNullable = _isNullable;
+ destination._sourceColumn = _sourceColumn;
+ destination._sourceVersion = _sourceVersion;
+ destination._sourceColumnNullMapping = _sourceColumnNullMapping;
+ destination._isNullable = _isNullable;
}
-
- internal void CopyTo(DbParameter destination) {
+
+ internal void CopyTo(DbParameter destination)
+ {
ADP.CheckArgumentNull(destination, "destination");
CloneHelper((SqlParameter)destination);
}
- internal object CompareExchangeParent(object value, object comparand) {
+ internal object CompareExchangeParent(object value, object comparand)
+ {
// the interlock guarantees same parameter won't belong to multiple collections
// at the same time, but to actually occur the user must really try
// since we never declared thread safety, we don't care at this time
//return System.Threading.Interlocked.CompareExchange(ref _parent, value, comparand);
object parent = _parent;
- if (comparand == parent) {
+ if (comparand == parent)
+ {
_parent = value;
}
return parent;
}
- internal void ResetParent() {
+ internal void ResetParent()
+ {
_parent = null;
}
- override public string ToString() { // V1.2.3300, XXXParameter V1.0.3300
+ override public string ToString()
+ { // V1.2.3300, XXXParameter V1.0.3300
return ParameterName;
}
- private byte ValuePrecisionCore(object value) { // V1.2.3300
- if (value is Decimal) {
- return ((System.Data.SqlTypes.SqlDecimal)(Decimal) value).Precision; // WebData 102913
+ private byte ValuePrecisionCore(object value)
+ { // V1.2.3300
+ if (value is Decimal)
+ {
+ return ((System.Data.SqlTypes.SqlDecimal)(Decimal)value).Precision; // WebData 102913
}
return 0;
}
- private byte ValueScaleCore(object value) { // V1.2.3300
- if (value is Decimal) {
+ private byte ValueScaleCore(object value)
+ { // V1.2.3300
+ if (value is Decimal)
+ {
return (byte)((Decimal.GetBits((Decimal)value)[3] & 0x00ff0000) >> 0x10);
}
return 0;
}
- private int ValueSizeCore(object value) { // V1.2.3300
- if (!ADP.IsNull(value)) {
+ private int ValueSizeCore(object value)
+ { // V1.2.3300
+ if (!ADP.IsNull(value))
+ {
string svalue = (value as string);
- if (null != svalue) {
+ if (null != svalue)
+ {
return svalue.Length;
}
byte[] bvalue = (value as byte[]);
- if (null != bvalue) {
+ if (null != bvalue)
+ {
return bvalue.Length;
}
char[] cvalue = (value as char[]);
- if (null != cvalue) {
+ if (null != cvalue)
+ {
return cvalue.Length;
}
- if ((value is byte) || (value is char)) {
+ if ((value is byte) || (value is char))
+ {
return 1;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/TimeoutTimer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/TimeoutTimer.cs
index 42c13753be..73b6656dd5 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/TimeoutTimer.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/TimeoutTimer.cs
@@ -5,179 +5,183 @@
namespace Microsoft.Data.ProviderBase
{
using System;
- using Microsoft.Data.Common;
using System.Diagnostics;
+ using Microsoft.Data.Common;
-// Purpose:
-// Manages determining and tracking timeouts
-//
-// Intended use:
-// Call StartXXXXTimeout() to get a timer with the given expiration point
-// Get remaining time in appropriate format to pass to subsystem timeouts
-// Check for timeout via IsExpired for checks in managed code.
-// Simply abandon to GC when done.
-internal class TimeoutTimer
-{
- //-------------------
- // Fields
- //-------------------
- private long _timerExpire;
- private bool _isInfiniteTimeout;
- private long _originalTimerTicks;
-
- //-------------------
- // Timeout-setting methods
- //-------------------
-
- // Get a new timer that will expire in the given number of seconds
- // For input, a value of zero seconds indicates infinite timeout
- internal static TimeoutTimer StartSecondsTimeout(int seconds)
+ // Purpose:
+ // Manages determining and tracking timeouts
+ //
+ // Intended use:
+ // Call StartXXXXTimeout() to get a timer with the given expiration point
+ // Get remaining time in appropriate format to pass to subsystem timeouts
+ // Check for timeout via IsExpired for checks in managed code.
+ // Simply abandon to GC when done.
+ internal class TimeoutTimer
{
- //--------------------
- // Preconditions: None (seconds must conform to SetTimeoutSeconds requirements)
+ //-------------------
+ // Fields
+ //-------------------
+ private long _timerExpire;
+ private bool _isInfiniteTimeout;
+ private long _originalTimerTicks;
+
+ //-------------------
+ // Timeout-setting methods
+ //-------------------
+
+ // Get a new timer that will expire in the given number of seconds
+ // For input, a value of zero seconds indicates infinite timeout
+ internal static TimeoutTimer StartSecondsTimeout(int seconds)
+ {
+ //--------------------
+ // Preconditions: None (seconds must conform to SetTimeoutSeconds requirements)
- //--------------------
- // Method body
- var timeout = new TimeoutTimer();
- timeout.SetTimeoutSeconds(seconds);
+ //--------------------
+ // Method body
+ var timeout = new TimeoutTimer();
+ timeout.SetTimeoutSeconds(seconds);
- //---------------------
- // Postconditions
- Debug.Assert(timeout != null); // Need a valid timeouttimer if no error
+ //---------------------
+ // Postconditions
+ Debug.Assert(timeout != null); // Need a valid timeouttimer if no error
- return timeout;
- }
+ return timeout;
+ }
- // Get a new timer that will expire in the given number of milliseconds
- // No current need to support infinite milliseconds timeout
- internal static TimeoutTimer StartMillisecondsTimeout(long milliseconds)
- {
- //--------------------
- // Preconditions
- Debug.Assert(0 <= milliseconds);
-
- //--------------------
- // Method body
- var timeout = new TimeoutTimer();
- timeout._originalTimerTicks = milliseconds * TimeSpan.TicksPerMillisecond;
- timeout._timerExpire = checked(ADP.TimerCurrent() + timeout._originalTimerTicks);
- timeout._isInfiniteTimeout = false;
-
- //---------------------
- // Postconditions
- Debug.Assert(timeout != null); // Need a valid timeouttimer if no error
-
- return timeout;
- }
+ // Get a new timer that will expire in the given number of milliseconds
+ // No current need to support infinite milliseconds timeout
+ internal static TimeoutTimer StartMillisecondsTimeout(long milliseconds)
+ {
+ //--------------------
+ // Preconditions
+ Debug.Assert(0 <= milliseconds);
- //-------------------
- // Methods for changing timeout
- //-------------------
+ //--------------------
+ // Method body
+ var timeout = new TimeoutTimer();
+ timeout._originalTimerTicks = milliseconds * TimeSpan.TicksPerMillisecond;
+ timeout._timerExpire = checked(ADP.TimerCurrent() + timeout._originalTimerTicks);
+ timeout._isInfiniteTimeout = false;
- internal void SetTimeoutSeconds(int seconds)
- {
- //--------------------
- // Preconditions
- Debug.Assert(0 <= seconds || InfiniteTimeout == seconds); // no need to support negative seconds at present
+ //---------------------
+ // Postconditions
+ Debug.Assert(timeout != null); // Need a valid timeouttimer if no error
- //--------------------
- // Method body
- if (InfiniteTimeout == seconds)
- {
- _isInfiniteTimeout = true;
- }
- else
- {
- // Stash current time + timeout
- _originalTimerTicks = ADP.TimerFromSeconds(seconds);
- _timerExpire = checked(ADP.TimerCurrent() + _originalTimerTicks);
- _isInfiniteTimeout = false;
+ return timeout;
}
- //---------------------
- // Postconditions:None
- }
+ //-------------------
+ // Methods for changing timeout
+ //-------------------
- // Reset timer to original duration.
- internal void Reset() {
- if (InfiniteTimeout == _originalTimerTicks) {
- _isInfiniteTimeout = true;
- } else {
- _timerExpire = checked(ADP.TimerCurrent() + _originalTimerTicks);
- _isInfiniteTimeout = false;
- }
- }
+ internal void SetTimeoutSeconds(int seconds)
+ {
+ //--------------------
+ // Preconditions
+ Debug.Assert(0 <= seconds || InfiniteTimeout == seconds); // no need to support negative seconds at present
- //-------------------
- // Timeout info properties
- //-------------------
+ //--------------------
+ // Method body
+ if (InfiniteTimeout == seconds)
+ {
+ _isInfiniteTimeout = true;
+ }
+ else
+ {
+ // Stash current time + timeout
+ _originalTimerTicks = ADP.TimerFromSeconds(seconds);
+ _timerExpire = checked(ADP.TimerCurrent() + _originalTimerTicks);
+ _isInfiniteTimeout = false;
+ }
- // Indicator for infinite timeout when starting a timer
- internal static readonly long InfiniteTimeout = 0;
+ //---------------------
+ // Postconditions:None
+ }
- // Is this timer in an expired state?
- internal bool IsExpired
- {
- get
+ // Reset timer to original duration.
+ internal void Reset()
{
- return !IsInfinite && ADP.TimerHasExpired(_timerExpire);
+ if (InfiniteTimeout == _originalTimerTicks)
+ {
+ _isInfiniteTimeout = true;
+ }
+ else
+ {
+ _timerExpire = checked(ADP.TimerCurrent() + _originalTimerTicks);
+ _isInfiniteTimeout = false;
+ }
}
- }
- // is this an infinite-timeout timer?
- internal bool IsInfinite
- {
- get
+ //-------------------
+ // Timeout info properties
+ //-------------------
+
+ // Indicator for infinite timeout when starting a timer
+ internal static readonly long InfiniteTimeout = 0;
+
+ // Is this timer in an expired state?
+ internal bool IsExpired
{
- return _isInfiniteTimeout;
+ get
+ {
+ return !IsInfinite && ADP.TimerHasExpired(_timerExpire);
+ }
}
- }
- // Special accessor for TimerExpire for use when thunking to legacy timeout methods.
- internal long LegacyTimerExpire
- {
- get
+ // is this an infinite-timeout timer?
+ internal bool IsInfinite
{
- return (_isInfiniteTimeout) ? Int64.MaxValue : _timerExpire;
+ get
+ {
+ return _isInfiniteTimeout;
+ }
}
- }
- // Returns milliseconds remaining trimmed to zero for none remaining
- // and long.MaxValue for infinite
- // This method should be prefered for internal calculations that are not
- // yet common enough to code into the TimeoutTimer class itself.
- internal long MillisecondsRemaining
- {
- get
+ // Special accessor for TimerExpire for use when thunking to legacy timeout methods.
+ internal long LegacyTimerExpire
{
- //-------------------
- // Preconditions: None
-
- //-------------------
- // Method Body
- long milliseconds;
- if (_isInfiniteTimeout)
+ get
{
- milliseconds = long.MaxValue;
+ return (_isInfiniteTimeout) ? Int64.MaxValue : _timerExpire;
}
- else
+ }
+
+ // Returns milliseconds remaining trimmed to zero for none remaining
+ // and long.MaxValue for infinite
+ // This method should be prefered for internal calculations that are not
+ // yet common enough to code into the TimeoutTimer class itself.
+ internal long MillisecondsRemaining
+ {
+ get
{
- milliseconds = ADP.TimerRemainingMilliseconds(_timerExpire);
- if (0 > milliseconds)
+ //-------------------
+ // Preconditions: None
+
+ //-------------------
+ // Method Body
+ long milliseconds;
+ if (_isInfiniteTimeout)
{
- milliseconds = 0;
+ milliseconds = long.MaxValue;
+ }
+ else
+ {
+ milliseconds = ADP.TimerRemainingMilliseconds(_timerExpire);
+ if (0 > milliseconds)
+ {
+ milliseconds = 0;
+ }
}
- }
- //--------------------
- // Postconditions
- Debug.Assert(0<=milliseconds); // This property guarantees no negative return values
+ //--------------------
+ // Postconditions
+ Debug.Assert(0 <= milliseconds); // This property guarantees no negative return values
- return milliseconds;
+ return milliseconds;
+ }
}
- }
-}
+ }
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/WrappedIUnknown.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/WrappedIUnknown.cs
index 32b19c2135..f66b813bc2 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/WrappedIUnknown.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/WrappedIUnknown.cs
@@ -2,16 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.ProviderBase {
+namespace Microsoft.Data.ProviderBase
+{
using System;
- using Microsoft.Data.Common;
using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
- using System.Security;
- using System.Security.Permissions;
- using System.Threading;
// We wrap the interface as a native IUnknown IntPtr so that every
// thread that creates a connection will fake the correct context when
@@ -19,51 +15,66 @@ namespace Microsoft.Data.ProviderBase {
// for two reasons: first for the connection pooler, this is a significant
// performance gain, second for the OLE DB provider, it doesn't marshal.
- internal class WrappedIUnknown : SafeHandle {
+ internal class WrappedIUnknown : SafeHandle
+ {
- internal WrappedIUnknown() : base(IntPtr.Zero, true) {
+ internal WrappedIUnknown() : base(IntPtr.Zero, true)
+ {
}
- internal WrappedIUnknown(object unknown) : this() {
- if (null != unknown) {
+ internal WrappedIUnknown(object unknown) : this()
+ {
+ if (null != unknown)
+ {
RuntimeHelpers.PrepareConstrainedRegions();
- try {} finally {
+ try
+ { }
+ finally
+ {
base.handle = Marshal.GetIUnknownForObject(unknown); // TODO: this method should be marked with a reliability contract.
}
}
}
- public override bool IsInvalid {
- get {
+ public override bool IsInvalid
+ {
+ get
+ {
return (IntPtr.Zero == base.handle);
}
}
- internal object ComWrapper() {
+ internal object ComWrapper()
+ {
// NOTE: Method, instead of property, to avoid being evaluated at
// runtime in the debugger.
object value = null;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
DangerousAddRef(ref mustRelease);
-
+
IntPtr handle = DangerousGetHandle();
value = System.Runtime.Remoting.Services.EnterpriseServicesHelper.WrapIUnknownWithComObject(handle);
}
- finally {
- if (mustRelease) {
+ finally
+ {
+ if (mustRelease)
+ {
DangerousRelease();
}
}
return value;
}
- override protected bool ReleaseHandle() {
+ override protected bool ReleaseHandle()
+ {
// NOTE: The SafeHandle class guarantees this will be called exactly once.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
- if (IntPtr.Zero != ptr) {
+ if (IntPtr.Zero != ptr)
+ {
Marshal.Release(ptr);
}
return true;
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/RelationshipConverter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/RelationshipConverter.cs
index cb391c74f4..895649fc72 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/RelationshipConverter.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/RelationshipConverter.cs
@@ -2,15 +2,18 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data {
+namespace Microsoft.Data
+{
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
- sealed internal class RelationshipConverter : ExpandableObjectConverter {
+ sealed internal class RelationshipConverter : ExpandableObjectConverter
+ {
// converter classes should have public ctor
- public RelationshipConverter() {
+ public RelationshipConverter()
+ {
}
@@ -18,8 +21,10 @@ public RelationshipConverter() {
/// Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.
///
- public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
- if (destinationType == typeof(InstanceDescriptor)) {
+ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
+ {
+ if (destinationType == typeof(InstanceDescriptor))
+ {
return true;
}
return base.CanConvertTo(context, destinationType);
@@ -48,7 +53,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati
// if (Microsoft.Data.Common.ADP.IsEmpty(parentTable.Namespace) && Microsoft.Data.Common.ADP.IsEmpty(childTable.Namespace)) {
// ctor = typeof(DataRelation).GetConstructor(new Type[] { typeof(string) /*relationName*/, typeof(string) /*parentTableName*/, typeof(string) /*childTableName */,
// typeof(string[]) /*parentColumnNames */, typeof(string[]) /*childColumnNames*/, typeof(bool) /*nested*/ } );
-
+
// values = new object[] { rel.RelationName, rel.ParentKey.Table.TableName, rel.ChildKey.Table.TableName,rel.ParentColumnNames, rel.ChildColumnNames, rel.Nested };
// }
// else {
@@ -59,10 +64,10 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati
// values = new object[] { rel.RelationName, rel.ParentKey.Table.TableName, rel.ParentKey.Table.Namespace, rel.ChildKey.Table.TableName,
// rel.ChildKey.Table.Namespace, rel.ParentColumnNames, rel.ChildColumnNames, rel.Nested };
// }
-
+
// return new InstanceDescriptor(ctor, values);
// }
-
+
// return base.ConvertTo(context, culture, value, destinationType);
//}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Sql/SqlGenericUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Sql/SqlGenericUtil.cs
index 49645cf8f5..271f27c6f5 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Sql/SqlGenericUtil.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Sql/SqlGenericUtil.cs
@@ -2,13 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.Sql {
+namespace Microsoft.Data.Sql
+{
using System;
using Microsoft.Data;
using Microsoft.Data.Common;
- using System.Diagnostics;
- sealed internal class SqlGenericUtil {
+ sealed internal class SqlGenericUtil
+ {
private SqlGenericUtil() { /* prevent utility class from being insantiated*/ }
@@ -20,13 +21,15 @@ private SqlGenericUtil() { /* prevent utility class from being insantiated*/ }
// Sql.Definition
//
- static internal Exception NullCommandText() {
+ static internal Exception NullCommandText()
+ {
return ADP.Argument(StringsHelper.GetString(Strings.Sql_NullCommandText));
}
- static internal Exception MismatchedMetaDataDirectionArrayLengths() {
+ static internal Exception MismatchedMetaDataDirectionArrayLengths()
+ {
return ADP.Argument(StringsHelper.GetString(Strings.Sql_MismatchedMetaDataDirectionArrayLengths));
}
}
- }//namespace
+}//namespace
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Sql/SqlNotificationRequest.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Sql/SqlNotificationRequest.cs
index dcdedeb75c..0a6a62d246 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Sql/SqlNotificationRequest.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Sql/SqlNotificationRequest.cs
@@ -2,62 +2,76 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.Sql {
+namespace Microsoft.Data.Sql
+{
using System;
using Microsoft.Data.Common;
- using Microsoft.Data.SqlClient;
-
-// [System.ComponentModel.TypeConverterAttribute(typeof(Microsoft.Data.Sql.SqlNotificationRequest.SqlNotificationRequestConverter))]
- public sealed class SqlNotificationRequest {
+
+ //[System.ComponentModel.TypeConverterAttribute(typeof(Microsoft.Data.Sql.SqlNotificationRequest.SqlNotificationRequestConverter))]
+ public sealed class SqlNotificationRequest
+ {
private string _userData;
private string _options;
- private int _timeout;
+ private int _timeout;
- public SqlNotificationRequest()
- : this(null, null, SqlClient.SQL.SqlDependencyTimeoutDefault) {}
+ public SqlNotificationRequest()
+ : this(null, null, SqlClient.SQL.SqlDependencyTimeoutDefault) { }
- public SqlNotificationRequest(string userData, string options, int timeout) {
+ public SqlNotificationRequest(string userData, string options, int timeout)
+ {
UserData = userData;
- Timeout = timeout;
- Options = options;
+ Timeout = timeout;
+ Options = options;
}
- public string Options {
- get {
+ public string Options
+ {
+ get
+ {
return _options;
}
- set {
- if ((null != value) && (UInt16.MaxValue < value.Length)) {
+ set
+ {
+ if ((null != value) && (UInt16.MaxValue < value.Length))
+ {
throw ADP.ArgumentOutOfRange(String.Empty, ADP.ParameterService);
}
_options = value;
}
}
- public int Timeout {
- get {
+ public int Timeout
+ {
+ get
+ {
return _timeout;
}
- set {
- if (0 > value) {
+ set
+ {
+ if (0 > value)
+ {
throw ADP.ArgumentOutOfRange(String.Empty, ADP.ParameterTimeout);
}
_timeout = value;
}
}
- public string UserData {
- get {
+ public string UserData
+ {
+ get
+ {
return _userData;
}
- set {
- if ((null != value) && (UInt16.MaxValue < value.Length)) {
+ set
+ {
+ if ((null != value) && (UInt16.MaxValue < value.Length))
+ {
throw ADP.ArgumentOutOfRange(String.Empty, ADP.ParameterUserData);
}
_userData = value;
}
- }
+ }
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs
index 7afa684fec..04ea9417d7 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs
@@ -2,18 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Security.Cryptography;
+using System;
using System.ComponentModel;
+using System.Security.Cryptography;
using System.Text;
-using System;
-namespace Microsoft.Data.SqlClient {
+namespace Microsoft.Data.SqlClient
+{
///
/// AD auth retry states.
///
- internal enum ActiveDirectoryAuthenticationTimeoutRetryState {
+ internal enum ActiveDirectoryAuthenticationTimeoutRetryState
+ {
NotStarted = 0,
Retrying,
HasLoggedIn,
@@ -22,7 +24,8 @@ internal enum ActiveDirectoryAuthenticationTimeoutRetryState {
///
/// AD auth retry helper.
///
- internal class ActiveDirectoryAuthenticationTimeoutRetryHelper {
+ internal class ActiveDirectoryAuthenticationTimeoutRetryHelper
+ {
private ActiveDirectoryAuthenticationTimeoutRetryState _state = ActiveDirectoryAuthenticationTimeoutRetryState.NotStarted;
private SqlFedAuthToken _token;
private readonly string _typeName;
@@ -31,25 +34,31 @@ internal class ActiveDirectoryAuthenticationTimeoutRetryHelper {
///
/// Constructor.
///
- public ActiveDirectoryAuthenticationTimeoutRetryHelper() {
+ public ActiveDirectoryAuthenticationTimeoutRetryHelper()
+ {
_typeName = GetType().Name;
}
///
/// Retry state.
///
- public ActiveDirectoryAuthenticationTimeoutRetryState State {
+ public ActiveDirectoryAuthenticationTimeoutRetryState State
+ {
get { return _state; }
- set {
- switch (_state) {
+ set
+ {
+ switch (_state)
+ {
case ActiveDirectoryAuthenticationTimeoutRetryState.NotStarted:
if (value != ActiveDirectoryAuthenticationTimeoutRetryState.Retrying
- && value != ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn) {
+ && value != ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn)
+ {
throw new InvalidOperationException($"Cannot transit from {_state} to {value}.");
}
break;
case ActiveDirectoryAuthenticationTimeoutRetryState.Retrying:
- if (value != ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn) {
+ if (value != ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn)
+ {
throw new InvalidOperationException($"Cannot transit from {_state} to {value}.");
}
break;
@@ -66,15 +75,20 @@ public ActiveDirectoryAuthenticationTimeoutRetryState State {
///
/// Cached token.
///
- public SqlFedAuthToken CachedToken {
- get {
- if (_sqlAuthLogger.IsLoggingEnabled) {
+ public SqlFedAuthToken CachedToken
+ {
+ get
+ {
+ if (_sqlAuthLogger.IsLoggingEnabled)
+ {
_sqlAuthLogger.LogInfo(_typeName, "GetCachedToken", $"Retrieved cached token {GetTokenHash(_token)}.");
}
return _token;
}
- set {
- if (_sqlAuthLogger.IsLoggingEnabled) {
+ set
+ {
+ if (_sqlAuthLogger.IsLoggingEnabled)
+ {
_sqlAuthLogger.LogInfo(_typeName, "SetCachedToken", $"CachedToken changed from {GetTokenHash(_token)} to {GetTokenHash(value)}.");
}
_token = value;
@@ -84,31 +98,38 @@ public SqlFedAuthToken CachedToken {
///
/// Whether login can be retried after a client/server connection timeout due to a long-time token acquisition.
///
- public bool CanRetryWithSqlException(SqlException sqlex) {
+ public bool CanRetryWithSqlException(SqlException sqlex)
+ {
var methodName = "CheckCanRetry";
if (_sqlAuthLogger.LogAssert(_state == ActiveDirectoryAuthenticationTimeoutRetryState.NotStarted, _typeName, methodName, $"Cannot retry due to state == {_state}.")
&& _sqlAuthLogger.LogAssert(CachedToken != null, _typeName, methodName, $"Cannot retry when cached token is null.")
- && _sqlAuthLogger.LogAssert(IsConnectTimeoutError(sqlex), _typeName, methodName, $"Cannot retry when exception is not timeout.")) {
+ && _sqlAuthLogger.LogAssert(IsConnectTimeoutError(sqlex), _typeName, methodName, $"Cannot retry when exception is not timeout."))
+ {
_sqlAuthLogger.LogInfo(_typeName, methodName, "All checks passed.");
return true;
}
return false;
}
- private static bool IsConnectTimeoutError(SqlException sqlex) {
+ private static bool IsConnectTimeoutError(SqlException sqlex)
+ {
var innerException = sqlex.InnerException as Win32Exception;
- if (innerException == null) return false;
+ if (innerException == null)
+ return false;
return innerException.NativeErrorCode == 10054 // Server timeout
|| innerException.NativeErrorCode == 258; // Client timeout
}
- private static string GetTokenHash(SqlFedAuthToken token) {
- if (token == null) return "null";
+ private static string GetTokenHash(SqlFedAuthToken token)
+ {
+ if (token == null)
+ return "null";
// Here we mimic how ADAL calculates hash for token. They use UTF8 instead of Unicode.
var originalTokenString = SqlAuthenticationToken.AccessTokenStringFromBytes(token.accessToken);
var bytesInUtf8 = Encoding.UTF8.GetBytes(originalTokenString);
- using (var sha256 = SHA256.Create()) {
+ using (var sha256 = SHA256.Create())
+ {
var hash = sha256.ComputeHash(bytesInUtf8);
return Convert.ToBase64String(hash);
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryNativeAuthenticationProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryNativeAuthenticationProvider.cs
index 5471ef92a9..daed2323e7 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryNativeAuthenticationProvider.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryNativeAuthenticationProvider.cs
@@ -2,9 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Identity.Client;
using System.Security;
using System.Threading.Tasks;
+using Microsoft.Identity.Client;
namespace Microsoft.Data.SqlClient
{
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AppContextDefaultValues.Defaults.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AppContextDefaultValues.Defaults.cs
index cec9213ad9..6f42414b2d 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AppContextDefaultValues.Defaults.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AppContextDefaultValues.Defaults.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using Microsoft.Data.SqlClient;
namespace System
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ApplicationIntent.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ApplicationIntent.cs
index d516b26f81..d402ecdaec 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ApplicationIntent.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ApplicationIntent.cs
@@ -4,14 +4,16 @@
using System;
-namespace Microsoft.Data.SqlClient {
+namespace Microsoft.Data.SqlClient
+{
///
/// represents the application workload type when connecting to a server
///
[Serializable]
- public enum ApplicationIntent {
- ReadWrite = 0,
- ReadOnly = 1,
+ public enum ApplicationIntent
+ {
+ ReadWrite = 0,
+ ReadOnly = 1,
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AssemblyRef.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AssemblyRef.cs
index 535cce1f7c..720022b3e6 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AssemblyRef.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AssemblyRef.cs
@@ -7,15 +7,14 @@
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
//------------------------------------------------------------------------------
-
namespace Microsoft.Data.SqlClient
{
internal static class AssemblyRef
- {
- internal const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
- internal const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
- internal const string EcmaPublicKey = "b77a5c561934e089";
- internal const string EcmaPublicKeyFull = "00000000000000000400000000000000";
- internal const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
- }
+ {
+ internal const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
+ internal const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
+ internal const string EcmaPublicKey = "b77a5c561934e089";
+ internal const string EcmaPublicKeyFull = "00000000000000000400000000000000";
+ internal const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
}
+}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs
index 95387363e8..eaecec4f9d 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs
@@ -4,12 +4,14 @@
using System;
-namespace Microsoft.Data.SqlClient {
+namespace Microsoft.Data.SqlClient
+{
///
/// Class encapsulating Column encryption key info
///
- internal class ColumnEncryptionKeyInfo {
+ internal class ColumnEncryptionKeyInfo
+ {
internal readonly int KeyId;
internal readonly int DatabaseId;
internal readonly byte[] DecryptedKeyBytes;
@@ -22,7 +24,7 @@ internal class ColumnEncryptionKeyInfo {
private static readonly string _className = "ColumnEncryptionKeyInfo";
private static readonly string _bytePackageName = "BytePackage";
private static readonly string _serializeToBufferMethodName = "SerializeToBuffer";
- private static readonly string _startOffsetName="StartOffset";
+ private static readonly string _startOffsetName = "StartOffset";
///
/// Constructor
@@ -31,12 +33,17 @@ internal class ColumnEncryptionKeyInfo {
/// database id for this column encryption key
/// key metadata version for this column encryption key
/// key id for this column encryption key
- internal ColumnEncryptionKeyInfo(byte[] decryptedKey, int databaseId, byte[] keyMetadataVersion, int keyid) {
-
- if (null == decryptedKey) { throw SQL.NullArgumentInConstructorInternal(_decryptedKeyName, _className); }
- if (0 == decryptedKey.Length) { throw SQL.EmptyArgumentInConstructorInternal(_decryptedKeyName, _className); }
- if (null == keyMetadataVersion) { throw SQL.NullArgumentInConstructorInternal(_keyMetadataVersionName, _className); }
- if (0 == keyMetadataVersion.Length) { throw SQL.EmptyArgumentInConstructorInternal(_keyMetadataVersionName, _className); }
+ internal ColumnEncryptionKeyInfo(byte[] decryptedKey, int databaseId, byte[] keyMetadataVersion, int keyid)
+ {
+
+ if (null == decryptedKey)
+ throw SQL.NullArgumentInConstructorInternal(_decryptedKeyName, _className);
+ if (0 == decryptedKey.Length)
+ throw SQL.EmptyArgumentInConstructorInternal(_decryptedKeyName, _className);
+ if (null == keyMetadataVersion)
+ throw SQL.NullArgumentInConstructorInternal(_keyMetadataVersionName, _className);
+ if (0 == keyMetadataVersion.Length)
+ throw SQL.EmptyArgumentInConstructorInternal(_keyMetadataVersionName, _className);
KeyId = keyid;
DatabaseId = databaseId;
@@ -46,9 +53,12 @@ internal ColumnEncryptionKeyInfo(byte[] decryptedKey, int databaseId, byte[] key
//Covert keyId to Bytes
ushort keyIdUShort;
- try {
+ try
+ {
keyIdUShort = (ushort)keyid;
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
throw SQL.InvalidKeyIdUnableToCastToUnsignedShort(keyid, e);
}
@@ -57,9 +67,12 @@ internal ColumnEncryptionKeyInfo(byte[] decryptedKey, int databaseId, byte[] key
//Covert databaseId to Bytes
uint databaseIdUInt;
- try {
+ try
+ {
databaseIdUInt = (uint)databaseId;
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
throw SQL.InvalidDatabaseIdUnableToCastToUnsignedInt(databaseId, e);
}
@@ -70,7 +83,8 @@ internal ColumnEncryptionKeyInfo(byte[] decryptedKey, int databaseId, byte[] key
/// Calculates number of bytes required to serialize this object
///
/// Number of bytes required for serialization
- internal int GetLengthForSerialization() {
+ internal int GetLengthForSerialization()
+ {
int lengthForSerialization = 0;
lengthForSerialization += DecryptedKeyBytes.Length;
lengthForSerialization += KeyIdBytes.Length;
@@ -85,12 +99,17 @@ internal int GetLengthForSerialization() {
/// byte array for serialization
/// start offset in byte array
/// next available offset
- internal int SerializeToBuffer(byte[] bytePackage, int startOffset) {
-
- if(null == bytePackage) { throw SQL.NullArgumentInternal(_bytePackageName, _className, _serializeToBufferMethodName); }
- if(0==bytePackage.Length) { throw SQL.EmptyArgumentInternal(_bytePackageName, _className, _serializeToBufferMethodName); }
- if (!(startOffset < bytePackage.Length)) { throw SQL.OffsetOutOfBounds(_startOffsetName, _className, _serializeToBufferMethodName); }
- if ( (bytePackage.Length - startOffset) < GetLengthForSerialization() ) { throw SQL.InsufficientBuffer(_bytePackageName, _className, _serializeToBufferMethodName); }
+ internal int SerializeToBuffer(byte[] bytePackage, int startOffset)
+ {
+
+ if (null == bytePackage)
+ throw SQL.NullArgumentInternal(_bytePackageName, _className, _serializeToBufferMethodName);
+ if (0 == bytePackage.Length)
+ throw SQL.EmptyArgumentInternal(_bytePackageName, _className, _serializeToBufferMethodName);
+ if (!(startOffset < bytePackage.Length))
+ throw SQL.OffsetOutOfBounds(_startOffsetName, _className, _serializeToBufferMethodName);
+ if ((bytePackage.Length - startOffset) < GetLengthForSerialization())
+ throw SQL.InsufficientBuffer(_bytePackageName, _className, _serializeToBufferMethodName);
Buffer.BlockCopy(DatabaseIdBytes, 0, bytePackage, startOffset, DatabaseIdBytes.Length);
startOffset += DatabaseIdBytes.Length;
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/DataClassification/SensitivityClassification.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/DataClassification/SensitivityClassification.cs
index 84455ae06d..845d139a77 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/DataClassification/SensitivityClassification.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/DataClassification/SensitivityClassification.cs
@@ -5,19 +5,23 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
-namespace Microsoft.Data.SqlClient.DataClassification {
+namespace Microsoft.Data.SqlClient.DataClassification
+{
- public class Label {
+ public class Label
+ {
public string Name { get; private set; }
public string Id { get; private set; }
- public Label(string name, string id) {
+ public Label(string name, string id)
+ {
Name = name;
Id = id;
}
}
- public class InformationType {
+ public class InformationType
+ {
public string Name { get; private set; }
public string Id { get; private set; }
@@ -28,30 +32,36 @@ public InformationType(string name, string id)
}
}
- public class SensitivityProperty {
+ public class SensitivityProperty
+ {
public Label Label { get; private set; }
public InformationType InformationType { get; private set; }
- public SensitivityProperty(Label label, InformationType informationType) {
+ public SensitivityProperty(Label label, InformationType informationType)
+ {
Label = label;
InformationType = informationType;
}
}
- public class ColumnSensitivity {
+ public class ColumnSensitivity
+ {
public ReadOnlyCollection SensitivityProperties { get; private set; }
- public ColumnSensitivity(IList sensitivityProperties) {
+ public ColumnSensitivity(IList sensitivityProperties)
+ {
SensitivityProperties = new ReadOnlyCollection(sensitivityProperties);
}
}
- public class SensitivityClassification {
+ public class SensitivityClassification
+ {
public ReadOnlyCollection Labels { get; private set; }
public ReadOnlyCollection InformationTypes { get; private set; }
public ReadOnlyCollection ColumnSensitivities { get; private set; }
- public SensitivityClassification(IList labels, IList informationTypes, IList columnSensitivity) {
+ public SensitivityClassification(IList labels, IList informationTypes, IList columnSensitivity)
+ {
Labels = new ReadOnlyCollection(labels);
InformationTypes = new ReadOnlyCollection(informationTypes);
ColumnSensitivities = new ReadOnlyCollection(columnSensitivity);
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveDelegate.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveDelegate.cs
index b1cc704500..bbc2aa901f 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveDelegate.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveDelegate.cs
@@ -8,12 +8,14 @@
using System.Security.Cryptography;
using System.Text;
-namespace Microsoft.Data.SqlClient {
+namespace Microsoft.Data.SqlClient
+{
///
/// A delegate for communicating with secure enclave
///
- internal class EnclaveDelegate {
+ internal class EnclaveDelegate
+ {
private static readonly SqlAeadAes256CbcHmac256Factory SqlAeadAes256CbcHmac256Factory = new SqlAeadAes256CbcHmac256Factory();
private static readonly string GetAttestationInfoQueryString = String.Format(@"Select GetTrustedModuleIdentityAndAttestationInfo({0}) as attestationInfo", 0);
@@ -23,7 +25,7 @@ internal class EnclaveDelegate {
private static readonly string GetDecryptedKeysToBeSentToEnclaveName = "GetDecryptedKeysToBeSentToEnclave";
private static readonly string GetSerializedAttestationParametersName = "GetSerializedAttestationParameters";
private static readonly string ComputeQueryStringHashName = "ComputeQueryStringHash";
-
+
private readonly Object _lock = new Object();
//singleton instance
@@ -39,13 +41,17 @@ private EnclaveDelegate() { }
/// server name
/// url for attestation endpoint
///
- internal EnclavePackage GenerateEnclavePackage(Dictionary keysTobeSentToEnclave, string queryText, string enclaveType, string serverName, string enclaveAttestationUrl) {
-
+ internal EnclavePackage GenerateEnclavePackage(Dictionary keysTobeSentToEnclave, string queryText, string enclaveType, string serverName, string enclaveAttestationUrl)
+ {
+
SqlEnclaveSession sqlEnclaveSession = null;
long counter;
- try {
+ try
+ {
GetEnclaveSession(enclaveType, serverName, enclaveAttestationUrl, out sqlEnclaveSession, out counter, throwIfNull: true);
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
throw new RetriableEnclaveQueryExecutionException(e.Message, e);
}
@@ -59,72 +65,85 @@ internal EnclavePackage GenerateEnclavePackage(Dictionaryattestation url for attestation service endpoint
/// attestation info from SQL Server
/// attestation parameters
- internal void CreateEnclaveSession(string enclaveType, string serverName, string attestationUrl,
- byte[] attestationInfo, SqlEnclaveAttestationParameters attestationParameters) {
+ internal void CreateEnclaveSession(string enclaveType, string serverName, string attestationUrl,
+ byte[] attestationInfo, SqlEnclaveAttestationParameters attestationParameters)
+ {
- lock (_lock) {
+ lock (_lock)
+ {
SqlColumnEncryptionEnclaveProvider sqlColumnEncryptionEnclaveProvider = GetEnclaveProvider(enclaveType);
long counter;
SqlEnclaveSession sqlEnclaveSession = null;
sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(serverName, attestationUrl, out sqlEnclaveSession, out counter);
- if (sqlEnclaveSession != null) {
+ if (sqlEnclaveSession != null)
+ {
return;
}
sqlColumnEncryptionEnclaveProvider.CreateEnclaveSession(attestationInfo, attestationParameters.ClientDiffieHellmanKey, attestationUrl, serverName, out sqlEnclaveSession, out counter);
- if (sqlEnclaveSession == null) throw SQL.NullEnclaveSessionReturnedFromProvider(enclaveType, attestationUrl);
+ if (sqlEnclaveSession == null)
+ throw SQL.NullEnclaveSessionReturnedFromProvider(enclaveType, attestationUrl);
}
}
- private SqlColumnEncryptionEnclaveProvider GetEnclaveProvider(string enclaveType) {
+ private SqlColumnEncryptionEnclaveProvider GetEnclaveProvider(string enclaveType)
+ {
if (SqlConnection.sqlColumnEncryptionEnclaveProviderConfigurationManager == null)
throw SQL.EnclaveProvidersNotConfiguredForEnclaveBasedQuery();
@@ -165,7 +189,8 @@ private SqlColumnEncryptionEnclaveProvider GetEnclaveProvider(string enclaveType
SqlConnection.sqlColumnEncryptionEnclaveProviderConfigurationManager.GetSqlColumnEncryptionEnclaveProvider(
enclaveType);
- if (sqlColumnEncryptionEnclaveProvider == null) throw SQL.EnclaveProviderNotFound(enclaveType);
+ if (sqlColumnEncryptionEnclaveProvider == null)
+ throw SQL.EnclaveProviderNotFound(enclaveType);
return sqlColumnEncryptionEnclaveProvider;
}
@@ -175,18 +200,23 @@ private SqlColumnEncryptionEnclaveProvider GetEnclaveProvider(string enclaveType
/// Keys that need to sent to the enclave
/// active connection
///
- private List GetDecryptedKeysToBeSentToEnclave(Dictionary keysTobeSentToEnclave, string serverName) {
+ private List GetDecryptedKeysToBeSentToEnclave(Dictionary keysTobeSentToEnclave, string serverName)
+ {
List decryptedKeysToBeSentToEnclave = new List();
- foreach (SqlTceCipherInfoEntry cipherInfo in keysTobeSentToEnclave.Values) {
+ foreach (SqlTceCipherInfoEntry cipherInfo in keysTobeSentToEnclave.Values)
+ {
SqlClientSymmetricKey sqlClientSymmetricKey = null;
SqlEncryptionKeyInfo? encryptionkeyInfoChosen = null;
SqlSecurityUtility.DecryptSymmetricKey(cipherInfo, serverName, out sqlClientSymmetricKey,
out encryptionkeyInfoChosen);
- if (sqlClientSymmetricKey == null) throw SQL.NullArgumentInternal("sqlClientSymmetricKey", ClassName, GetDecryptedKeysToBeSentToEnclaveName);
- if (cipherInfo.ColumnEncryptionKeyValues == null) throw SQL.NullArgumentInternal("ColumnEncryptionKeyValues", ClassName, GetDecryptedKeysToBeSentToEnclaveName);
- if (!(cipherInfo.ColumnEncryptionKeyValues.Count > 0)) throw SQL.ColumnEncryptionKeysNotFound();
+ if (sqlClientSymmetricKey == null)
+ throw SQL.NullArgumentInternal("sqlClientSymmetricKey", ClassName, GetDecryptedKeysToBeSentToEnclaveName);
+ if (cipherInfo.ColumnEncryptionKeyValues == null)
+ throw SQL.NullArgumentInternal("ColumnEncryptionKeyValues", ClassName, GetDecryptedKeysToBeSentToEnclaveName);
+ if (!(cipherInfo.ColumnEncryptionKeyValues.Count > 0))
+ throw SQL.ColumnEncryptionKeysNotFound();
//cipherInfo.CekId is always 0, hence used cipherInfo.ColumnEncryptionKeyValues[0].cekId. Even when cek has multiple ColumnEncryptionKeyValues
//the cekid and the plaintext value will remain the same, what varies is the encrypted cek value, since the cek can be encrypted by
@@ -204,7 +234,8 @@ private List GetDecryptedKeysToBeSentToEnclave(Dictiona
/// counter to avoid replay attacks
///
///
- private byte[] GenerateBytePackageForKeys(long enclaveSessionCounter, byte[] queryStringHashBytes, List keys) {
+ private byte[] GenerateBytePackageForKeys(long enclaveSessionCounter, byte[] queryStringHashBytes, List keys)
+ {
//Format GUID | counter | queryStringHash | key[1]id | key[1]Bytes | ...... key[n]id | key[n]bytes
Guid guid = Guid.NewGuid();
@@ -215,7 +246,8 @@ private byte[] GenerateBytePackageForKeys(long enclaveSessionCounter, byte[] que
lengthOfByteArrayToAllocate += counterBytes.Length;
lengthOfByteArrayToAllocate += queryStringHashBytes.Length;
- foreach (ColumnEncryptionKeyInfo key in keys) {
+ foreach (ColumnEncryptionKeyInfo key in keys)
+ {
lengthOfByteArrayToAllocate += key.GetLengthForSerialization();
}
@@ -231,7 +263,8 @@ private byte[] GenerateBytePackageForKeys(long enclaveSessionCounter, byte[] que
Buffer.BlockCopy(queryStringHashBytes, 0, bytePackage, startOffset, queryStringHashBytes.Length);
startOffset += queryStringHashBytes.Length;
- foreach (ColumnEncryptionKeyInfo key in keys) {
+ foreach (ColumnEncryptionKeyInfo key in keys)
+ {
startOffset = key.SerializeToBuffer(bytePackage, startOffset);
}
@@ -245,18 +278,24 @@ private byte[] GenerateBytePackageForKeys(long enclaveSessionCounter, byte[] que
/// session key used to encrypt the package
/// server hosting the enclave
///
- private byte[] EncryptBytePackage(byte[] bytePackage, byte[] sessionKey, string serverName) {
- if (sessionKey == null) throw SQL.NullArgumentInternal("sessionKey", ClassName, "EncryptBytePackage");
- if (sessionKey.Length == 0) throw SQL.EmptyArgumentInternal("sessionKey", ClassName, "EncryptBytePackage");
+ private byte[] EncryptBytePackage(byte[] bytePackage, byte[] sessionKey, string serverName)
+ {
+ if (sessionKey == null)
+ throw SQL.NullArgumentInternal("sessionKey", ClassName, "EncryptBytePackage");
+ if (sessionKey.Length == 0)
+ throw SQL.EmptyArgumentInternal("sessionKey", ClassName, "EncryptBytePackage");
//bytePackage is created internally in this class and is guaranteed to be non null and non empty
- try {
+ try
+ {
SqlClientSymmetricKey symmetricKey = new SqlClientSymmetricKey(sessionKey);
SqlClientEncryptionAlgorithm sqlClientEncryptionAlgorithm =
SqlAeadAes256CbcHmac256Factory.Create(symmetricKey, SqlClientEncryptionType.Randomized,
SqlAeadAes256CbcHmac256Algorithm.AlgorithmName);
return sqlClientEncryptionAlgorithm.EncryptData(bytePackage);
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
throw SQL.FailedToEncryptRegisterRulesBytePackage(e);
}
}
@@ -266,10 +305,12 @@ private byte[] EncryptBytePackage(byte[] bytePackage, byte[] sessionKey, string
///
/// byte arrays to be combined
///
- private byte[] CombineByteArrays(byte[][] byteArraysToCombine) {
+ private byte[] CombineByteArrays(byte[][] byteArraysToCombine)
+ {
byte[] combinedArray = new byte[byteArraysToCombine.Sum(ba => ba.Length)];
int offset = 0;
- foreach (byte[] byteArray in byteArraysToCombine) {
+ foreach (byte[] byteArray in byteArraysToCombine)
+ {
Buffer.BlockCopy(byteArray, 0, combinedArray, offset, byteArray.Length);
offset += byteArray.Length;
}
@@ -279,7 +320,8 @@ private byte[] CombineByteArrays(byte[][] byteArraysToCombine) {
private byte[] ComputeQueryStringHash(string queryString)
{
// Validate the input parameters
- if (string.IsNullOrWhiteSpace(queryString)) {
+ if (string.IsNullOrWhiteSpace(queryString))
+ {
string argumentName = "queryString";
if (null == queryString)
{
@@ -306,24 +348,27 @@ private byte[] ComputeQueryStringHash(string queryString)
///
/// Exception when executing a enclave based Always Encrypted query
///
- internal class RetriableEnclaveQueryExecutionException : Exception {
+ internal class RetriableEnclaveQueryExecutionException : Exception
+ {
internal RetriableEnclaveQueryExecutionException(string message, Exception innerException) : base(message, innerException) { }
}
///
/// Class encapsulating necessary information about the byte package that needs to be sent to the enclave
///
- internal class EnclavePackage {
+ internal class EnclavePackage
+ {
- public SqlEnclaveSession EnclaveSession { get;}
- public byte[] EnclavePackageBytes { get;}
+ public SqlEnclaveSession EnclaveSession { get; }
+ public byte[] EnclavePackageBytes { get; }
///
/// Constructor
///
/// byte package to be sent to enclave
/// enclave session to be used
- internal EnclavePackage(byte[] enclavePackageBytes, SqlEnclaveSession enclaveSession) {
+ internal EnclavePackage(byte[] enclavePackageBytes, SqlEnclaveSession enclaveSession)
+ {
EnclavePackageBytes = enclavePackageBytes;
EnclaveSession = enclaveSession;
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
index aed364068f..68bfdfa52c 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs
@@ -2,18 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System;
+using System.Collections.Generic;
using System.Configuration;
-using System.Threading;
-using System.Runtime.InteropServices;
-using Microsoft.Data.Common;
+using System.Diagnostics;
using System.Globalization;
-using Microsoft.Data.SqlClient;
-using System.Collections.Generic;
using System.Runtime.CompilerServices;
-using System.Text;
-using System.Diagnostics;
+using System.Runtime.InteropServices;
using System.Security;
-using System;
+using System.Text;
+using System.Threading;
+using Microsoft.Data.SqlClient;
namespace Microsoft.Data
{
@@ -51,18 +50,18 @@ internal static void ReleaseDLLHandles()
s_localDBCreateInstance = null;
}
-
+
//This is copy of handle that SNI maintains, so we are responsible for freeing it - therefore there we are not using SafeHandle
- static IntPtr s_userInstanceDLLHandle = IntPtr.Zero;
+ static IntPtr s_userInstanceDLLHandle = IntPtr.Zero;
static object s_dllLock = new object();
-
+
static IntPtr UserInstanceDLLHandle
{
get
{
- if (s_userInstanceDLLHandle==IntPtr.Zero)
+ if (s_userInstanceDLLHandle == IntPtr.Zero)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
@@ -74,7 +73,7 @@ static IntPtr UserInstanceDLLHandle
SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle);
if (s_userInstanceDLLHandle != IntPtr.Zero)
{
- Bid.Trace(" LocalDB - handle obtained");
+ Bid.Trace(" LocalDB - handle obtained");
}
else
{
@@ -89,7 +88,7 @@ static IntPtr UserInstanceDLLHandle
if (lockTaken)
Monitor.Exit(s_dllLock);
}
- }
+ }
return s_userInstanceDLLHandle;
}
}
@@ -104,7 +103,7 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance
{
get
{
- if (s_localDBCreateInstance==null)
+ if (s_localDBCreateInstance == null)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
@@ -117,13 +116,13 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance
if (functionAddr == IntPtr.Zero)
{
- int hResult=Marshal.GetLastWin32Error();
- Bid.Trace(" GetProcAddress for LocalDBCreateInstance error 0x{%X}",hResult);
+ int hResult = Marshal.GetLastWin32Error();
+ Bid.Trace(" GetProcAddress for LocalDBCreateInstance error 0x{%X}", hResult);
throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound"));
}
s_localDBCreateInstance = (LocalDBCreateInstanceDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBCreateInstanceDelegate));
}
- }
+ }
finally
{
if (lockTaken)
@@ -136,7 +135,7 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance
[SuppressUnmanagedCodeSecurity]
- [UnmanagedFunctionPointer(CallingConvention.Cdecl,CharSet=CharSet.Unicode)]
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private delegate int LocalDBFormatMessageDelegate(int hrLocalDB, UInt32 dwFlags, UInt32 dwLanguageId, StringBuilder buffer, ref UInt32 buflen);
static LocalDBFormatMessageDelegate s_localDBFormatMessage = null;
@@ -144,8 +143,8 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance
static LocalDBFormatMessageDelegate LocalDBFormatMessage
{
get
- {
- if (s_localDBFormatMessage==null)
+ {
+ if (s_localDBFormatMessage == null)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
@@ -159,13 +158,13 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage
if (functionAddr == IntPtr.Zero)
{
// SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossibe to get this error.
- int hResult=Marshal.GetLastWin32Error();
+ int hResult = Marshal.GetLastWin32Error();
Bid.Trace(" GetProcAddress for LocalDBFormatMessage error 0x{%X}", hResult);
throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound"));
}
- s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate));
+ s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate));
}
- }
+ }
finally
{
if (lockTaken)
@@ -179,7 +178,7 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage
const UInt32 const_LOCALDB_TRUNCATE_ERR_MESSAGE = 1;// flag for LocalDBFormatMessage that indicates that message can be truncated if it does not fit in the buffer
const int const_ErrorMessageBufferSize = 1024; // Buffer size for Local DB error message, according to Serverless team, 1K will be enough for all messages
-
+
internal static string GetLocalDBMessage(int hrCode)
{
Debug.Assert(hrCode < 0, "HRCode does not indicate error");
@@ -188,18 +187,18 @@ internal static string GetLocalDBMessage(int hrCode)
StringBuilder buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
UInt32 len = (UInt32)buffer.Capacity;
-
+
// First try for current culture
- int hResult=LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: (UInt32)CultureInfo.CurrentCulture.LCID,
+ int hResult = LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: (UInt32)CultureInfo.CurrentCulture.LCID,
buffer: buffer, buflen: ref len);
- if (hResult>=0)
+ if (hResult >= 0)
return buffer.ToString();
else
{
// Message is not available for current culture, try default
buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
- len = (UInt32) buffer.Capacity;
- hResult=LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: 0 /* thread locale with fallback to English */,
+ len = (UInt32)buffer.Capacity;
+ hResult = LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: 0 /* thread locale with fallback to English */,
buffer: buffer, buflen: ref len);
if (hResult >= 0)
return buffer.ToString();
@@ -213,7 +212,7 @@ internal static string GetLocalDBMessage(int hrCode)
}
}
-
+
static SqlException CreateLocalDBException(string errorMessage, string instance = null, int localDbError = 0, int sniError = 0)
{
Debug.Assert((localDbError == 0) || (sniError == 0), "LocalDB error and SNI error cannot be specified simultaneously");
@@ -222,17 +221,17 @@ static SqlException CreateLocalDBException(string errorMessage, string instance
int errorCode = (localDbError == 0) ? sniError : localDbError;
- if (sniError!=0)
+ if (sniError != 0)
{
string sniErrorMessage = SQL.GetSNIErrorMessage(sniError);
errorMessage = String.Format((IFormatProvider)null, "{0} (error: {1} - {2})",
errorMessage, sniError, sniErrorMessage);
}
-
+
collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, errorMessage, null, 0));
if (localDbError != 0)
- collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, GetLocalDBMessage(localDbError), null, 0));
+ collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, GetLocalDBMessage(localDbError), null, 0));
SqlException exc = SqlException.CreateException(collection, null);
@@ -253,39 +252,39 @@ internal InstanceInfo(string version)
internal bool created;
}
- static object s_configLock=new object();
+ static object s_configLock = new object();
static Dictionary s_configurableInstances = null;
internal static void DemandLocalDBPermissions()
{
- if (!_partialTrustAllowed)
- {
- if (!_partialTrustFlagChecked)
+ if (!_partialTrustAllowed)
+ {
+ if (!_partialTrustFlagChecked)
{
object partialTrustFlagValue = AppDomain.CurrentDomain.GetData(const_partialTrustFlagKey);
- if (partialTrustFlagValue != null && partialTrustFlagValue is bool)
+ if (partialTrustFlagValue != null && partialTrustFlagValue is bool)
{
- _partialTrustAllowed = (bool)partialTrustFlagValue;
+ _partialTrustAllowed = (bool)partialTrustFlagValue;
}
- _partialTrustFlagChecked = true;
- if (_partialTrustAllowed)
+ _partialTrustFlagChecked = true;
+ if (_partialTrustAllowed)
{
return;
}
}
- if (_fullTrust == null)
+ if (_fullTrust == null)
{
_fullTrust = new NamedPermissionSet("FullTrust");
}
_fullTrust.Demand();
}
- }
+ }
internal static void AssertLocalDBPermissions()
{
_partialTrustAllowed = true;
}
-
+
internal static void CreateLocalDBInstance(string instance)
{
@@ -306,7 +305,7 @@ internal static void CreateLocalDBInstance(string instance)
{
// validate section type
LocalDBConfigurationSection configSection = section as LocalDBConfigurationSection;
- if (configSection == null)
+ if (configSection == null)
throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_BadConfigSectionType"));
foreach (LocalDBInstanceElement confElement in configSection.LocalDbInstances)
{
@@ -315,7 +314,7 @@ internal static void CreateLocalDBInstance(string instance)
}
}
else
- Bid.Trace( " No system.data.localdb section found in configuration");
+ Bid.Trace(" No system.data.localdb section found in configuration");
s_configurableInstances = tempConfigurableInstances;
}
}
@@ -325,10 +324,10 @@ internal static void CreateLocalDBInstance(string instance)
Monitor.Exit(s_configLock);
}
}
-
+
InstanceInfo instanceInfo = null;
- if (!s_configurableInstances.TryGetValue(instance,out instanceInfo))
+ if (!s_configurableInstances.TryGetValue(instance, out instanceInfo))
return; // instance name was not in the config
if (instanceInfo.created)
@@ -338,14 +337,14 @@ internal static void CreateLocalDBInstance(string instance)
if (instanceInfo.version.Contains("\0"))
throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_InvalidVersion"), instance: instance);
-
+
// LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously
int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0);
Bid.Trace(" Starting creation of instance %ls version %ls", instance, instanceInfo.version);
if (hr < 0)
throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr);
Bid.Trace(" Finished creation of instance %ls", instance);
- instanceInfo.created=true; // mark instance as created
+ instanceInfo.created = true; // mark instance as created
} // CreateLocalDbInstance
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBConfig.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBConfig.cs
index d493bbfe65..4c830520d9 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBConfig.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBConfig.cs
@@ -4,9 +4,9 @@
namespace Microsoft.Data
{
- using System.Configuration;
- using System.Collections;
using System;
+ using System.Collections;
+ using System.Configuration;
internal sealed class LocalDBInstanceElement : ConfigurationElement
{
@@ -44,7 +44,7 @@ public int Compare(object x, object y)
if (yStr != null)
y = yStr.Trim();
- return StringComparer.OrdinalIgnoreCase.Compare(x,y);
+ return StringComparer.OrdinalIgnoreCase.Compare(x, y);
}
}
@@ -64,7 +64,7 @@ protected override object GetElementKey(ConfigurationElement element)
{
return ((LocalDBInstanceElement)element).Name;
}
-
+
}
internal sealed class LocalDBConfigurationSection : ConfigurationSection
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/OnChangedEventHandler.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/OnChangedEventHandler.cs
index f65f754be2..07620907ea 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/OnChangedEventHandler.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/OnChangedEventHandler.cs
@@ -2,8 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.SqlClient {
-
+namespace Microsoft.Data.SqlClient
+{
public delegate void OnChangeEventHandler(object sender, SqlNotificationEventArgs e);
}
-
+
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ParameterPeekAheadValue.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ParameterPeekAheadValue.cs
index dacbb31606..5da62e1106 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ParameterPeekAheadValue.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ParameterPeekAheadValue.cs
@@ -5,7 +5,8 @@
using System.Collections.Generic;
using Microsoft.Data.SqlClient.Server;
-namespace Microsoft.Data.SqlClient {
+namespace Microsoft.Data.SqlClient
+{
// simple storage to contain objects that must be generated prior to sending data, but
// that we cannot re-generate at the time of sending the data. The entire purpose is
@@ -18,10 +19,11 @@ namespace Microsoft.Data.SqlClient {
// but to properly stream the value, we can't ask the IEnumerable for these objects again
// when it's time to send the actual values.
- internal class ParameterPeekAheadValue {
+ internal class ParameterPeekAheadValue
+ {
// Peekahead for IEnumerable
internal IEnumerator Enumerator;
- internal SqlDataRecord FirstRecord;
+ internal SqlDataRecord FirstRecord;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/PoolBlockingPeriod.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/PoolBlockingPeriod.cs
index ccd2fec70e..0504e62977 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/PoolBlockingPeriod.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/PoolBlockingPeriod.cs
@@ -16,4 +16,4 @@ public enum PoolBlockingPeriod
AlwaysBlock = 1,
NeverBlock = 2,
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/RowsCopiedEventArgs.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/RowsCopiedEventArgs.cs
index ef38eb7ac4..d4b9f53484 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/RowsCopiedEventArgs.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/RowsCopiedEventArgs.cs
@@ -2,28 +2,36 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.SqlClient {
+namespace Microsoft.Data.SqlClient
+{
- public class SqlRowsCopiedEventArgs : System.EventArgs {
- private bool _abort;
- private long _rowsCopied;
+ public class SqlRowsCopiedEventArgs : System.EventArgs
+ {
+ private bool _abort;
+ private long _rowsCopied;
- public SqlRowsCopiedEventArgs (long rowsCopied) {
+ public SqlRowsCopiedEventArgs(long rowsCopied)
+ {
_rowsCopied = rowsCopied;
}
- public bool Abort {
- get {
+ public bool Abort
+ {
+ get
+ {
return _abort;
}
- set {
+ set
+ {
_abort = value;
}
}
- public long RowsCopied {
- get {
+ public long RowsCopied
+ {
+ get
+ {
return _rowsCopied;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/RowsCopiedEventHandler.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/RowsCopiedEventHandler.cs
index b77fe61f13..a8a88194ce 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/RowsCopiedEventHandler.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/RowsCopiedEventHandler.cs
@@ -2,7 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.SqlClient {
+namespace Microsoft.Data.SqlClient
+{
public delegate void SqlRowsCopiedEventHandler(object sender, SqlRowsCopiedEventArgs e);
}
-
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ExtendedClrTypeCode.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ExtendedClrTypeCode.cs
index f5e11dc099..d1525cb597 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ExtendedClrTypeCode.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ExtendedClrTypeCode.cs
@@ -2,9 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
- internal enum ExtendedClrTypeCode {
+ internal enum ExtendedClrTypeCode
+ {
Invalid = -1,
Boolean, // System.Boolean
Byte, // System.Byte
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedGetters.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedGetters.cs
index 4bedbbe202..281edd25ac 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedGetters.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedGetters.cs
@@ -6,77 +6,79 @@
using System.Data;
using System.Data.SqlTypes;
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
// Interface for strongly-typed value getters
- internal interface ITypedGetters {
+ internal interface ITypedGetters
+ {
// Null test
- bool IsDBNull( int ordinal );
+ bool IsDBNull(int ordinal);
// Check what type current sql_variant value is
- SqlDbType GetVariantType( int ordinal );
+ SqlDbType GetVariantType(int ordinal);
// By value accessors (data copy across the interface boundary implied)
- Boolean GetBoolean( int ordinal );
+ Boolean GetBoolean(int ordinal);
- Byte GetByte( int ordinal );
+ Byte GetByte(int ordinal);
- Int64 GetBytes( int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length );
+ Int64 GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length);
- Char GetChar( int ordinal );
+ Char GetChar(int ordinal);
- Int64 GetChars( int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length );
+ Int64 GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length);
- Int16 GetInt16( int ordinal );
+ Int16 GetInt16(int ordinal);
- Int32 GetInt32( int ordinal );
+ Int32 GetInt32(int ordinal);
- Int64 GetInt64( int ordinal );
+ Int64 GetInt64(int ordinal);
- Single GetFloat( int ordinal );
+ Single GetFloat(int ordinal);
- Double GetDouble( int ordinal );
+ Double GetDouble(int ordinal);
- String GetString( int ordinal );
+ String GetString(int ordinal);
- Decimal GetDecimal( int ordinal );
+ Decimal GetDecimal(int ordinal);
- DateTime GetDateTime( int ordinal );
+ DateTime GetDateTime(int ordinal);
- Guid GetGuid( int ordinal );
+ Guid GetGuid(int ordinal);
- SqlBoolean GetSqlBoolean( int ordinal );
+ SqlBoolean GetSqlBoolean(int ordinal);
- SqlByte GetSqlByte( int ordinal );
+ SqlByte GetSqlByte(int ordinal);
- SqlInt16 GetSqlInt16( int ordinal );
+ SqlInt16 GetSqlInt16(int ordinal);
- SqlInt32 GetSqlInt32( int ordinal );
+ SqlInt32 GetSqlInt32(int ordinal);
- SqlInt64 GetSqlInt64( int ordinal );
+ SqlInt64 GetSqlInt64(int ordinal);
- SqlSingle GetSqlSingle( int ordinal );
+ SqlSingle GetSqlSingle(int ordinal);
- SqlDouble GetSqlDouble( int ordinal );
+ SqlDouble GetSqlDouble(int ordinal);
- SqlMoney GetSqlMoney( int ordinal );
+ SqlMoney GetSqlMoney(int ordinal);
- SqlDateTime GetSqlDateTime( int ordinal );
+ SqlDateTime GetSqlDateTime(int ordinal);
- SqlDecimal GetSqlDecimal( int ordinal );
+ SqlDecimal GetSqlDecimal(int ordinal);
- SqlString GetSqlString( int ordinal );
+ SqlString GetSqlString(int ordinal);
- SqlBinary GetSqlBinary( int ordinal );
+ SqlBinary GetSqlBinary(int ordinal);
- SqlGuid GetSqlGuid( int ordinal );
+ SqlGuid GetSqlGuid(int ordinal);
- SqlChars GetSqlChars( int ordinal );
+ SqlChars GetSqlChars(int ordinal);
- SqlBytes GetSqlBytes( int ordinal );
+ SqlBytes GetSqlBytes(int ordinal);
- SqlXml GetSqlXml( int ordinal );
+ SqlXml GetSqlXml(int ordinal);
// "By reference" accessors
@@ -90,10 +92,10 @@ internal interface ITypedGetters {
// won't change the value until the next event is consumed.
//
// Simplest way to guarantee this behavior is to simply call the corresponding by-value accessor.
- SqlBytes GetSqlBytesRef( int ordinal );
+ SqlBytes GetSqlBytesRef(int ordinal);
- SqlChars GetSqlCharsRef( int ordinal );
+ SqlChars GetSqlCharsRef(int ordinal);
- SqlXml GetSqlXmlRef( int ordinal );
+ SqlXml GetSqlXmlRef(int ordinal);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedGettersV3.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedGettersV3.cs
index e08ab09b5d..eb2ecdfcc3 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedGettersV3.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedGettersV3.cs
@@ -5,18 +5,20 @@
using System;
using System.Data.SqlTypes;
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
// Interface for strongly-typed value getters
- internal interface ITypedGettersV3 {
+ internal interface ITypedGettersV3
+ {
// Null test
// valid for all types
- bool IsDBNull( SmiEventSink sink, int ordinal );
+ bool IsDBNull(SmiEventSink sink, int ordinal);
// Check what type current sql_variant value is
// valid for SqlDbType.Variant
- SmiMetaData GetVariantType( SmiEventSink sink, int ordinal );
+ SmiMetaData GetVariantType(SmiEventSink sink, int ordinal);
//
// Actual value accessors
@@ -25,44 +27,44 @@ internal interface ITypedGettersV3 {
//
// valid for SqlDbType.Bit
- Boolean GetBoolean( SmiEventSink sink, int ordinal );
+ Boolean GetBoolean(SmiEventSink sink, int ordinal);
// valid for SqlDbType.TinyInt
- Byte GetByte( SmiEventSink sink, int ordinal );
+ Byte GetByte(SmiEventSink sink, int ordinal);
// valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml, Char, VarChar, Text, NChar, NVarChar, NText
// (Character type support needed for ExecuteXmlReader handling)
- Int64 GetBytesLength( SmiEventSink sink, int ordinal );
- int GetBytes( SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length );
+ Int64 GetBytesLength(SmiEventSink sink, int ordinal);
+ int GetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length);
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
- Int64 GetCharsLength( SmiEventSink sink, int ordinal );
- int GetChars( SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length );
- String GetString( SmiEventSink sink, int ordinal );
+ Int64 GetCharsLength(SmiEventSink sink, int ordinal);
+ int GetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length);
+ String GetString(SmiEventSink sink, int ordinal);
// valid for SqlDbType.SmallInt
- Int16 GetInt16( SmiEventSink sink, int ordinal );
+ Int16 GetInt16(SmiEventSink sink, int ordinal);
// valid for SqlDbType.Int
- Int32 GetInt32( SmiEventSink sink, int ordinal );
+ Int32 GetInt32(SmiEventSink sink, int ordinal);
// valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
- Int64 GetInt64( SmiEventSink sink, int ordinal );
+ Int64 GetInt64(SmiEventSink sink, int ordinal);
// valid for SqlDbType.Real
- Single GetSingle( SmiEventSink sink, int ordinal );
+ Single GetSingle(SmiEventSink sink, int ordinal);
// valid for SqlDbType.Float
- Double GetDouble( SmiEventSink sink, int ordinal );
+ Double GetDouble(SmiEventSink sink, int ordinal);
// valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
- SqlDecimal GetSqlDecimal( SmiEventSink sink, int ordinal );
+ SqlDecimal GetSqlDecimal(SmiEventSink sink, int ordinal);
// valid for DateTime & SmallDateTime
- DateTime GetDateTime( SmiEventSink sink, int ordinal );
+ DateTime GetDateTime(SmiEventSink sink, int ordinal);
// valid for UniqueIdentifier
- Guid GetGuid( SmiEventSink sink, int ordinal );
+ Guid GetGuid(SmiEventSink sink, int ordinal);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedSetters.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedSetters.cs
index ada0ab2de3..83e0a8b8ae 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedSetters.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedSetters.cs
@@ -5,92 +5,94 @@
using System;
using System.Data.SqlTypes;
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
// interface for strongly-typed value setters
- internal interface ITypedSetters {
+ internal interface ITypedSetters
+ {
// By value setters (data copy across the interface boundary implied)
- void SetDBNull( int ordinal );
+ void SetDBNull(int ordinal);
- void SetBoolean( int ordinal, Boolean value );
+ void SetBoolean(int ordinal, Boolean value);
- void SetByte( int ordinal, Byte value );
+ void SetByte(int ordinal, Byte value);
- void SetBytes( int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length );
+ void SetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length);
- void SetChar( int ordinal, char value );
+ void SetChar(int ordinal, char value);
- void SetChars( int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length );
+ void SetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length);
- void SetInt16( int ordinal, Int16 value );
+ void SetInt16(int ordinal, Int16 value);
- void SetInt32( int ordinal, Int32 value );
+ void SetInt32(int ordinal, Int32 value);
- void SetInt64( int ordinal, Int64 value );
+ void SetInt64(int ordinal, Int64 value);
- void SetFloat( int ordinal, Single value );
+ void SetFloat(int ordinal, Single value);
- void SetDouble( int ordinal, Double value );
+ void SetDouble(int ordinal, Double value);
- [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset." )]
- void SetString( int ordinal, string value );
+ [ObsoleteAttribute("Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset.")]
+ void SetString(int ordinal, string value);
// Method introduced as of SMI V2
- void SetString( int ordinal, string value, int offset );
+ void SetString(int ordinal, string value, int offset);
- void SetDecimal( int ordinal, Decimal value );
+ void SetDecimal(int ordinal, Decimal value);
- void SetDateTime( int ordinal, DateTime value );
+ void SetDateTime(int ordinal, DateTime value);
- void SetGuid( int ordinal, Guid value );
+ void SetGuid(int ordinal, Guid value);
- void SetSqlBoolean( int ordinal, SqlBoolean value );
+ void SetSqlBoolean(int ordinal, SqlBoolean value);
- void SetSqlByte( int ordinal, SqlByte value );
+ void SetSqlByte(int ordinal, SqlByte value);
- void SetSqlInt16( int ordinal, SqlInt16 value );
+ void SetSqlInt16(int ordinal, SqlInt16 value);
- void SetSqlInt32( int ordinal, SqlInt32 value );
+ void SetSqlInt32(int ordinal, SqlInt32 value);
- void SetSqlInt64( int ordinal, SqlInt64 value );
+ void SetSqlInt64(int ordinal, SqlInt64 value);
- void SetSqlSingle( int ordinal, SqlSingle value );
+ void SetSqlSingle(int ordinal, SqlSingle value);
- void SetSqlDouble( int ordinal, SqlDouble value );
+ void SetSqlDouble(int ordinal, SqlDouble value);
- void SetSqlMoney( int ordinal, SqlMoney value );
+ void SetSqlMoney(int ordinal, SqlMoney value);
- void SetSqlDateTime( int ordinal, SqlDateTime value );
+ void SetSqlDateTime(int ordinal, SqlDateTime value);
- void SetSqlDecimal( int ordinal, SqlDecimal value );
+ void SetSqlDecimal(int ordinal, SqlDecimal value);
- [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset." )]
- void SetSqlString( int ordinal, SqlString value );
+ [ObsoleteAttribute("Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset.")]
+ void SetSqlString(int ordinal, SqlString value);
// Method introduced as of SMI V2
- void SetSqlString( int ordinal, SqlString value, int offset );
+ void SetSqlString(int ordinal, SqlString value, int offset);
- [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset." )]
- void SetSqlBinary( int ordinal, SqlBinary value );
+ [ObsoleteAttribute("Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset.")]
+ void SetSqlBinary(int ordinal, SqlBinary value);
// Method introduced as of SMI V2
- void SetSqlBinary( int ordinal, SqlBinary value, int offset );
+ void SetSqlBinary(int ordinal, SqlBinary value, int offset);
- void SetSqlGuid( int ordinal, SqlGuid value );
+ void SetSqlGuid(int ordinal, SqlGuid value);
- [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset." )]
- void SetSqlChars( int ordinal, SqlChars value );
+ [ObsoleteAttribute("Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset.")]
+ void SetSqlChars(int ordinal, SqlChars value);
// Method introduced as of SMI V2
- void SetSqlChars( int ordinal, SqlChars value, int offset );
+ void SetSqlChars(int ordinal, SqlChars value, int offset);
- [ObsoleteAttribute( "Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset." )]
- void SetSqlBytes( int ordinal, SqlBytes value );
+ [ObsoleteAttribute("Not supported as of SMI v2. Will be removed when v1 support dropped. Use setter with offset.")]
+ void SetSqlBytes(int ordinal, SqlBytes value);
// Method introduced as of SMI V2
- void SetSqlBytes( int ordinal, SqlBytes value, int offset );
+ void SetSqlBytes(int ordinal, SqlBytes value, int offset);
- void SetSqlXml( int ordinal, SqlXml value );
+ void SetSqlXml(int ordinal, SqlXml value);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedSettersV3.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedSettersV3.cs
index b5a8fdfb55..d0bf5a86dc 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedSettersV3.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/ITypedSettersV3.cs
@@ -5,10 +5,12 @@
using System;
using System.Data.SqlTypes;
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
// interface for strongly-typed value setters
- internal interface ITypedSettersV3 {
+ internal interface ITypedSettersV3
+ {
// By value setters (data copy across the interface boundary implied)
// All setters are valid for SqlDbType.Variant
@@ -21,58 +23,58 @@ internal interface ITypedSettersV3 {
// the following pairs are the only setters/sqldbtypes that need this call:
// NVarChar/VarChar + SetString (needed only for non-global collation, i.e. SqlString)
// Money/SmallMoney + SetInt64
- void SetVariantMetaData( SmiEventSink sink, int ordinal, SmiMetaData metaData );
+ void SetVariantMetaData(SmiEventSink sink, int ordinal, SmiMetaData metaData);
// Set value to null
// valid for all types
- void SetDBNull( SmiEventSink sink, int ordinal );
+ void SetDBNull(SmiEventSink sink, int ordinal);
// valid for SqlDbType.Bit
- void SetBoolean( SmiEventSink sink, int ordinal, Boolean value );
+ void SetBoolean(SmiEventSink sink, int ordinal, Boolean value);
// valid for SqlDbType.TinyInt
- void SetByte( SmiEventSink sink, int ordinal, Byte value );
+ void SetByte(SmiEventSink sink, int ordinal, Byte value);
// Semantics for SetBytes are to modify existing value, not overwrite
// Use in combination with SetLength to ensure overwriting when necessary
// valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml
// (VarBinary assumed for variants)
- int SetBytes( SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length );
- void SetBytesLength( SmiEventSink sink, int ordinal, long length );
+ int SetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length);
+ void SetBytesLength(SmiEventSink sink, int ordinal, long length);
// Semantics for SetChars are to modify existing value, not overwrite
// Use in combination with SetLength to ensure overwriting when necessary
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
// (NVarChar and global clr collation assumed for variants)
- int SetChars( SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length );
- void SetCharsLength( SmiEventSink sink, int ordinal, long length );
+ int SetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length);
+ void SetCharsLength(SmiEventSink sink, int ordinal, long length);
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
- void SetString( SmiEventSink sink, int ordinal, string value, int offset, int length );
+ void SetString(SmiEventSink sink, int ordinal, string value, int offset, int length);
// valid for SqlDbType.SmallInt
- void SetInt16( SmiEventSink sink, int ordinal, Int16 value );
+ void SetInt16(SmiEventSink sink, int ordinal, Int16 value);
// valid for SqlDbType.Int
- void SetInt32( SmiEventSink sink, int ordinal, Int32 value );
+ void SetInt32(SmiEventSink sink, int ordinal, Int32 value);
// valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
- void SetInt64( SmiEventSink sink, int ordinal, Int64 value );
+ void SetInt64(SmiEventSink sink, int ordinal, Int64 value);
// valid for SqlDbType.Real
- void SetSingle( SmiEventSink sink, int ordinal, Single value );
+ void SetSingle(SmiEventSink sink, int ordinal, Single value);
// valid for SqlDbType.Float
- void SetDouble( SmiEventSink sink, int ordinal, Double value );
+ void SetDouble(SmiEventSink sink, int ordinal, Double value);
// valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
- void SetSqlDecimal( SmiEventSink sink, int ordinal, SqlDecimal value );
+ void SetSqlDecimal(SmiEventSink sink, int ordinal, SqlDecimal value);
// valid for DateTime & SmallDateTime
- void SetDateTime( SmiEventSink sink, int ordinal, DateTime value );
+ void SetDateTime(SmiEventSink sink, int ordinal, DateTime value);
// valid for UniqueIdentifier
- void SetGuid( SmiEventSink sink, int ordinal, Guid value );
+ void SetGuid(SmiEventSink sink, int ordinal, Guid value);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/InvalidUdtException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/InvalidUdtException.cs
index 5ba6b30088..df006f67e6 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/InvalidUdtException.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/InvalidUdtException.cs
@@ -2,9 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Data.Common;
using System;
using System.Runtime.Serialization;
+using Microsoft.Data.Common;
namespace Microsoft.Data.SqlClient.Server
{
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MemoryRecordBuffer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MemoryRecordBuffer.cs
index 8f76ab2bf8..1fdb0cbc42 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MemoryRecordBuffer.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MemoryRecordBuffer.cs
@@ -3,22 +3,26 @@
// See the LICENSE file in the project root for more information.
using System;
-using System.Diagnostics;
using System.Data.SqlTypes;
+using System.Diagnostics;
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
// Class for implementing a record object used in out-of-proc scenarios.
- internal sealed class MemoryRecordBuffer : SmiRecordBuffer {
+ internal sealed class MemoryRecordBuffer : SmiRecordBuffer
+ {
private SqlRecordBuffer[] _buffer;
- internal MemoryRecordBuffer(SmiMetaData[] metaData) {
+ internal MemoryRecordBuffer(SmiMetaData[] metaData)
+ {
Debug.Assert(null != metaData, "invalid attempt to instantiate MemoryRecordBuffer with null SmiMetaData[]");
_buffer = new SqlRecordBuffer[metaData.Length];
- for (int i = 0; i < _buffer.Length; ++i) {
+ for (int i = 0; i < _buffer.Length; ++i)
+ {
_buffer[i] = new SqlRecordBuffer(metaData[i]);
}
}
@@ -26,93 +30,112 @@ internal MemoryRecordBuffer(SmiMetaData[] metaData) {
#region Getters
// Null test
// valid for all types
- public override bool IsDBNull(SmiEventSink sink, int ordinal) {
+ public override bool IsDBNull(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].IsNull;
}
// Check what type current sql_variant value is
// valid for SqlDbType.Variant
- public override SmiMetaData GetVariantType(SmiEventSink sink, int ordinal) {
+ public override SmiMetaData GetVariantType(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].VariantType;
}
// valid for SqlDbType.Bit
- public override Boolean GetBoolean(SmiEventSink sink, int ordinal) {
+ public override Boolean GetBoolean(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].Boolean;
}
// valid for SqlDbType.TinyInt
- public override Byte GetByte(SmiEventSink sink, int ordinal) {
+ public override Byte GetByte(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].Byte;
}
// valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml, Char, VarChar, Text, NChar, NVarChar, NText
// (Character type support needed for ExecuteXmlReader handling)
- public override Int64 GetBytesLength(SmiEventSink sink, int ordinal) {
+ public override Int64 GetBytesLength(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].BytesLength;
}
- public override int GetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) {
+ public override int GetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
+ {
return _buffer[ordinal].GetBytes(fieldOffset, buffer, bufferOffset, length);
}
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
- public override Int64 GetCharsLength(SmiEventSink sink, int ordinal) {
+ public override Int64 GetCharsLength(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].CharsLength;
}
- public override int GetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) {
+ public override int GetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
+ {
return _buffer[ordinal].GetChars(fieldOffset, buffer, bufferOffset, length);
}
- public override String GetString(SmiEventSink sink, int ordinal) {
+ public override String GetString(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].String;
}
// valid for SqlDbType.SmallInt
- public override Int16 GetInt16(SmiEventSink sink, int ordinal) {
+ public override Int16 GetInt16(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].Int16;
}
// valid for SqlDbType.Int
- public override Int32 GetInt32(SmiEventSink sink, int ordinal) {
+ public override Int32 GetInt32(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].Int32;
}
// valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
- public override Int64 GetInt64(SmiEventSink sink, int ordinal) {
+ public override Int64 GetInt64(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].Int64;
}
// valid for SqlDbType.Real
- public override Single GetSingle(SmiEventSink sink, int ordinal) {
+ public override Single GetSingle(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].Single;
}
// valid for SqlDbType.Float
- public override Double GetDouble(SmiEventSink sink, int ordinal) {
+ public override Double GetDouble(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].Double;
}
// valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
- public override SqlDecimal GetSqlDecimal(SmiEventSink sink, int ordinal) {
+ public override SqlDecimal GetSqlDecimal(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].SqlDecimal;
}
// valid for DateTime, SmallDateTime, Date, and DateTime2
- public override DateTime GetDateTime(SmiEventSink sink, int ordinal) {
+ public override DateTime GetDateTime(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].DateTime;
}
// valid for UniqueIdentifier
- public override Guid GetGuid(SmiEventSink sink, int ordinal) {
+ public override Guid GetGuid(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].Guid;
}
// valid for SqlDbType.Time
- public override TimeSpan GetTimeSpan(SmiEventSink sink, int ordinal) {
+ public override TimeSpan GetTimeSpan(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].TimeSpan;
}
// valid for DateTimeOffset
- public override DateTimeOffset GetDateTimeOffset(SmiEventSink sink, int ordinal) {
+ public override DateTimeOffset GetDateTimeOffset(SmiEventSink sink, int ordinal)
+ {
return _buffer[ordinal].DateTimeOffset;
}
#endregion
@@ -120,17 +143,20 @@ public override DateTimeOffset GetDateTimeOffset(SmiEventSink sink, int ordinal)
#region Setters
// Set value to null
// valid for all types
- public override void SetDBNull(SmiEventSink sink, int ordinal) {
+ public override void SetDBNull(SmiEventSink sink, int ordinal)
+ {
_buffer[ordinal].SetNull();
}
// valid for SqlDbType.Bit
- public override void SetBoolean(SmiEventSink sink, int ordinal, Boolean value) {
+ public override void SetBoolean(SmiEventSink sink, int ordinal, Boolean value)
+ {
_buffer[ordinal].Boolean = value;
}
// valid for SqlDbType.TinyInt
- public override void SetByte(SmiEventSink sink, int ordinal, Byte value) {
+ public override void SetByte(SmiEventSink sink, int ordinal, Byte value)
+ {
_buffer[ordinal].Byte = value;
}
@@ -138,10 +164,12 @@ public override void SetByte(SmiEventSink sink, int ordinal, Byte value) {
// Use in combination with SetLength to ensure overwriting when necessary
// valid for SqlDbTypes: Binary, VarBinary, Image, Udt, Xml
// (VarBinary assumed for variants)
- public override int SetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) {
+ public override int SetBytes(SmiEventSink sink, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
+ {
return _buffer[ordinal].SetBytes(fieldOffset, buffer, bufferOffset, length);
}
- public override void SetBytesLength(SmiEventSink sink, int ordinal, long length) {
+ public override void SetBytesLength(SmiEventSink sink, int ordinal, long length)
+ {
_buffer[ordinal].BytesLength = length;
}
@@ -149,72 +177,86 @@ public override void SetBytesLength(SmiEventSink sink, int ordinal, long length)
// Use in combination with SetLength to ensure overwriting when necessary
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
// (NVarChar and global clr collation assumed for variants)
- public override int SetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) {
+ public override int SetChars(SmiEventSink sink, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
+ {
return _buffer[ordinal].SetChars(fieldOffset, buffer, bufferOffset, length);
}
- public override void SetCharsLength(SmiEventSink sink, int ordinal, long length) {
+ public override void SetCharsLength(SmiEventSink sink, int ordinal, long length)
+ {
_buffer[ordinal].CharsLength = length;
}
// valid for character types: Char, VarChar, Text, NChar, NVarChar, NText
- public override void SetString(SmiEventSink sink, int ordinal, string value, int offset, int length) {
+ public override void SetString(SmiEventSink sink, int ordinal, string value, int offset, int length)
+ {
Debug.Assert(offset == 0 && length <= value.Length, "Invalid string length or offset"); // for sqlvariant, length could be less than value.Length
_buffer[ordinal].String = value.Substring(offset, length); // Perf test shows that Substring method has already optimized the case where length = value.Length
}
// valid for SqlDbType.SmallInt
- public override void SetInt16(SmiEventSink sink, int ordinal, Int16 value) {
+ public override void SetInt16(SmiEventSink sink, int ordinal, Int16 value)
+ {
_buffer[ordinal].Int16 = value;
}
// valid for SqlDbType.Int
- public override void SetInt32(SmiEventSink sink, int ordinal, Int32 value) {
+ public override void SetInt32(SmiEventSink sink, int ordinal, Int32 value)
+ {
_buffer[ordinal].Int32 = value;
}
// valid for SqlDbType.BigInt, SqlDbType.Money, SqlDbType.SmallMoney
- public override void SetInt64(SmiEventSink sink, int ordinal, Int64 value) {
+ public override void SetInt64(SmiEventSink sink, int ordinal, Int64 value)
+ {
_buffer[ordinal].Int64 = value;
}
// valid for SqlDbType.Real
- public override void SetSingle(SmiEventSink sink, int ordinal, Single value) {
+ public override void SetSingle(SmiEventSink sink, int ordinal, Single value)
+ {
_buffer[ordinal].Single = value;
}
// valid for SqlDbType.Float
- public override void SetDouble(SmiEventSink sink, int ordinal, Double value) {
+ public override void SetDouble(SmiEventSink sink, int ordinal, Double value)
+ {
_buffer[ordinal].Double = value;
}
// valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
- public override void SetSqlDecimal(SmiEventSink sink, int ordinal, SqlDecimal value) {
+ public override void SetSqlDecimal(SmiEventSink sink, int ordinal, SqlDecimal value)
+ {
_buffer[ordinal].SqlDecimal = value;
}
// valid for DateTime, SmallDateTime, Date, and DateTime2
- public override void SetDateTime(SmiEventSink sink, int ordinal, DateTime value) {
+ public override void SetDateTime(SmiEventSink sink, int ordinal, DateTime value)
+ {
_buffer[ordinal].DateTime = value;
}
// valid for UniqueIdentifier
- public override void SetGuid(SmiEventSink sink, int ordinal, Guid value) {
+ public override void SetGuid(SmiEventSink sink, int ordinal, Guid value)
+ {
_buffer[ordinal].Guid = value;
}
// SqlDbType.Time
- public override void SetTimeSpan(SmiEventSink sink, int ordinal, TimeSpan value) {
+ public override void SetTimeSpan(SmiEventSink sink, int ordinal, TimeSpan value)
+ {
_buffer[ordinal].TimeSpan = value;
}
// DateTimeOffset
- public override void SetDateTimeOffset(SmiEventSink sink, int ordinal, DateTimeOffset value) {
+ public override void SetDateTimeOffset(SmiEventSink sink, int ordinal, DateTimeOffset value)
+ {
_buffer[ordinal].DateTimeOffset = value;
}
// valid for SqlDbType.Variant
- public override void SetVariantMetaData(SmiEventSink sink, int ordinal, SmiMetaData metaData) {
+ public override void SetVariantMetaData(SmiEventSink sink, int ordinal, SmiMetaData metaData)
+ {
_buffer[ordinal].VariantType = metaData;
}
#endregion
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
index d52eb25909..d69406c202 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs
@@ -5,16 +5,16 @@
using System;
using System.Collections;
using System.Collections.Generic;
-using Microsoft.Data.Common;
-using Microsoft.Data.SqlClient;
-using System.Data.SqlTypes;
-using System.Diagnostics;
using System.Data;
using System.Data.Common;
+using System.Data.SqlTypes;
+using System.Diagnostics;
using System.Globalization;
using System.Reflection;
+using Microsoft.Data.Common;
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
// Utilities for manipulating smi-related metadata.
//
@@ -22,10 +22,11 @@ namespace Microsoft.Data.SqlClient.Server {
//
// These are all based off of knowing the clr type of the value
// as an ExtendedClrTypeCode enum for rapid access (lookup in static array is best, if possible).
- internal class MetaDataUtilsSmi {
+ internal class MetaDataUtilsSmi
+ {
- internal const SqlDbType InvalidSqlDbType = (SqlDbType) (-1);
- internal const long InvalidMaxLength = -2;
+ internal const SqlDbType InvalidSqlDbType = (SqlDbType)(-1);
+ internal const long InvalidMaxLength = -2;
// Standard type inference map to get SqlDbType when all you know is the value's type (typecode)
// This map's index is off by one (add one to typecode locate correct entry) in order
@@ -83,83 +84,89 @@ internal class MetaDataUtilsSmi {
// class ctor
- static MetaDataUtilsSmi() {
+ static MetaDataUtilsSmi()
+ {
// set up type mapping hash table
// keep this initialization list in the same order as ExtendedClrTypeCode for ease in validating!
Hashtable ht = new Hashtable(42);
- ht.Add( typeof( System.Boolean ), ExtendedClrTypeCode.Boolean );
- ht.Add( typeof( System.Byte ), ExtendedClrTypeCode.Byte );
- ht.Add( typeof( System.Char ), ExtendedClrTypeCode.Char );
- ht.Add( typeof( System.DateTime ), ExtendedClrTypeCode.DateTime );
- ht.Add( typeof( System.DBNull ), ExtendedClrTypeCode.DBNull );
- ht.Add( typeof( System.Decimal ), ExtendedClrTypeCode.Decimal );
- ht.Add( typeof( System.Double ), ExtendedClrTypeCode.Double );
+ ht.Add(typeof(System.Boolean), ExtendedClrTypeCode.Boolean);
+ ht.Add(typeof(System.Byte), ExtendedClrTypeCode.Byte);
+ ht.Add(typeof(System.Char), ExtendedClrTypeCode.Char);
+ ht.Add(typeof(System.DateTime), ExtendedClrTypeCode.DateTime);
+ ht.Add(typeof(System.DBNull), ExtendedClrTypeCode.DBNull);
+ ht.Add(typeof(System.Decimal), ExtendedClrTypeCode.Decimal);
+ ht.Add(typeof(System.Double), ExtendedClrTypeCode.Double);
// lookup code will have to special-case null-ref anyway, so don't bother adding ExtendedTypeCode.Empty to the table
- ht.Add( typeof( System.Int16 ), ExtendedClrTypeCode.Int16 );
- ht.Add( typeof( System.Int32 ), ExtendedClrTypeCode.Int32 );
- ht.Add( typeof( System.Int64 ), ExtendedClrTypeCode.Int64 );
- ht.Add( typeof( System.SByte ), ExtendedClrTypeCode.SByte );
- ht.Add( typeof( System.Single ), ExtendedClrTypeCode.Single );
- ht.Add( typeof( System.String ), ExtendedClrTypeCode.String );
- ht.Add( typeof( System.UInt16 ), ExtendedClrTypeCode.UInt16 );
- ht.Add( typeof( System.UInt32 ), ExtendedClrTypeCode.UInt32 );
- ht.Add( typeof( System.UInt64 ), ExtendedClrTypeCode.UInt64 );
- ht.Add( typeof( System.Object ), ExtendedClrTypeCode.Object );
- ht.Add( typeof( System.Byte[] ), ExtendedClrTypeCode.ByteArray );
- ht.Add( typeof( System.Char[] ), ExtendedClrTypeCode.CharArray );
- ht.Add( typeof( System.Guid ), ExtendedClrTypeCode.Guid );
- ht.Add( typeof( SqlBinary ), ExtendedClrTypeCode.SqlBinary );
- ht.Add( typeof( SqlBoolean ), ExtendedClrTypeCode.SqlBoolean );
- ht.Add( typeof( SqlByte ), ExtendedClrTypeCode.SqlByte );
- ht.Add( typeof( SqlDateTime ), ExtendedClrTypeCode.SqlDateTime );
- ht.Add( typeof( SqlDouble ), ExtendedClrTypeCode.SqlDouble );
- ht.Add( typeof( SqlGuid ), ExtendedClrTypeCode.SqlGuid );
- ht.Add( typeof( SqlInt16 ), ExtendedClrTypeCode.SqlInt16 );
- ht.Add( typeof( SqlInt32 ), ExtendedClrTypeCode.SqlInt32 );
- ht.Add( typeof( SqlInt64 ), ExtendedClrTypeCode.SqlInt64 );
- ht.Add( typeof( SqlMoney ), ExtendedClrTypeCode.SqlMoney );
- ht.Add( typeof( SqlDecimal ), ExtendedClrTypeCode.SqlDecimal );
- ht.Add( typeof( SqlSingle ), ExtendedClrTypeCode.SqlSingle );
- ht.Add( typeof( SqlString ), ExtendedClrTypeCode.SqlString );
- ht.Add( typeof( SqlChars ), ExtendedClrTypeCode.SqlChars );
- ht.Add( typeof( SqlBytes ), ExtendedClrTypeCode.SqlBytes );
- ht.Add( typeof( SqlXml ), ExtendedClrTypeCode.SqlXml );
- ht.Add( typeof( DataTable ), ExtendedClrTypeCode.DataTable );
- ht.Add( typeof( DbDataReader ), ExtendedClrTypeCode.DbDataReader );
- ht.Add( typeof( IEnumerable ), ExtendedClrTypeCode.IEnumerableOfSqlDataRecord );
- ht.Add( typeof( System.TimeSpan ), ExtendedClrTypeCode.TimeSpan );
- ht.Add( typeof( System.DateTimeOffset ), ExtendedClrTypeCode.DateTimeOffset );
+ ht.Add(typeof(System.Int16), ExtendedClrTypeCode.Int16);
+ ht.Add(typeof(System.Int32), ExtendedClrTypeCode.Int32);
+ ht.Add(typeof(System.Int64), ExtendedClrTypeCode.Int64);
+ ht.Add(typeof(System.SByte), ExtendedClrTypeCode.SByte);
+ ht.Add(typeof(System.Single), ExtendedClrTypeCode.Single);
+ ht.Add(typeof(System.String), ExtendedClrTypeCode.String);
+ ht.Add(typeof(System.UInt16), ExtendedClrTypeCode.UInt16);
+ ht.Add(typeof(System.UInt32), ExtendedClrTypeCode.UInt32);
+ ht.Add(typeof(System.UInt64), ExtendedClrTypeCode.UInt64);
+ ht.Add(typeof(System.Object), ExtendedClrTypeCode.Object);
+ ht.Add(typeof(System.Byte[]), ExtendedClrTypeCode.ByteArray);
+ ht.Add(typeof(System.Char[]), ExtendedClrTypeCode.CharArray);
+ ht.Add(typeof(System.Guid), ExtendedClrTypeCode.Guid);
+ ht.Add(typeof(SqlBinary), ExtendedClrTypeCode.SqlBinary);
+ ht.Add(typeof(SqlBoolean), ExtendedClrTypeCode.SqlBoolean);
+ ht.Add(typeof(SqlByte), ExtendedClrTypeCode.SqlByte);
+ ht.Add(typeof(SqlDateTime), ExtendedClrTypeCode.SqlDateTime);
+ ht.Add(typeof(SqlDouble), ExtendedClrTypeCode.SqlDouble);
+ ht.Add(typeof(SqlGuid), ExtendedClrTypeCode.SqlGuid);
+ ht.Add(typeof(SqlInt16), ExtendedClrTypeCode.SqlInt16);
+ ht.Add(typeof(SqlInt32), ExtendedClrTypeCode.SqlInt32);
+ ht.Add(typeof(SqlInt64), ExtendedClrTypeCode.SqlInt64);
+ ht.Add(typeof(SqlMoney), ExtendedClrTypeCode.SqlMoney);
+ ht.Add(typeof(SqlDecimal), ExtendedClrTypeCode.SqlDecimal);
+ ht.Add(typeof(SqlSingle), ExtendedClrTypeCode.SqlSingle);
+ ht.Add(typeof(SqlString), ExtendedClrTypeCode.SqlString);
+ ht.Add(typeof(SqlChars), ExtendedClrTypeCode.SqlChars);
+ ht.Add(typeof(SqlBytes), ExtendedClrTypeCode.SqlBytes);
+ ht.Add(typeof(SqlXml), ExtendedClrTypeCode.SqlXml);
+ ht.Add(typeof(DataTable), ExtendedClrTypeCode.DataTable);
+ ht.Add(typeof(DbDataReader), ExtendedClrTypeCode.DbDataReader);
+ ht.Add(typeof(IEnumerable), ExtendedClrTypeCode.IEnumerableOfSqlDataRecord);
+ ht.Add(typeof(System.TimeSpan), ExtendedClrTypeCode.TimeSpan);
+ ht.Add(typeof(System.DateTimeOffset), ExtendedClrTypeCode.DateTimeOffset);
__typeToExtendedTypeCodeMap = ht;
}
- internal static bool IsCharOrXmlType(SqlDbType type) {
- return IsUnicodeType(type) ||
+ internal static bool IsCharOrXmlType(SqlDbType type)
+ {
+ return IsUnicodeType(type) ||
IsAnsiType(type) ||
type == SqlDbType.Xml;
}
- internal static bool IsUnicodeType(SqlDbType type) {
- return type == SqlDbType.NChar ||
+ internal static bool IsUnicodeType(SqlDbType type)
+ {
+ return type == SqlDbType.NChar ||
type == SqlDbType.NVarChar ||
type == SqlDbType.NText;
}
- internal static bool IsAnsiType(SqlDbType type) {
- return type == SqlDbType.Char ||
+ internal static bool IsAnsiType(SqlDbType type)
+ {
+ return type == SqlDbType.Char ||
type == SqlDbType.VarChar ||
type == SqlDbType.Text;
}
- internal static bool IsBinaryType(SqlDbType type) {
- return type == SqlDbType.Binary ||
+ internal static bool IsBinaryType(SqlDbType type)
+ {
+ return type == SqlDbType.Binary ||
type == SqlDbType.VarBinary ||
type == SqlDbType.Image;
}
// Does this type use PLP format values?
- internal static bool IsPlpFormat(SmiMetaData metaData) {
- return metaData.MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator ||
+ internal static bool IsPlpFormat(SmiMetaData metaData)
+ {
+ return metaData.MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator ||
metaData.SqlDbType == SqlDbType.Image ||
metaData.SqlDbType == SqlDbType.NText ||
metaData.SqlDbType == SqlDbType.Text ||
@@ -180,23 +187,27 @@ internal static bool IsPlpFormat(SmiMetaData metaData) {
// must instantiate a Type object. The typecode switch also degenerates into a large if-then-else for
// all but the primitive clr types.
internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType(
- SqlDbType dbType,
- bool isMultiValued,
- object value,
- Type udtType,
- ulong smiVersion) {
+ SqlDbType dbType,
+ bool isMultiValued,
+ object value,
+ Type udtType,
+ ulong smiVersion)
+ {
ExtendedClrTypeCode extendedCode = ExtendedClrTypeCode.Invalid;
// fast-track null, which is valid for all types
- if ( null == value ) {
+ if (null == value)
+ {
extendedCode = ExtendedClrTypeCode.Empty;
}
- else if ( DBNull.Value == value ) {
+ else if (DBNull.Value == value)
+ {
extendedCode = ExtendedClrTypeCode.DBNull;
}
- else {
- switch(dbType)
- {
+ else
+ {
+ switch (dbType)
+ {
case SqlDbType.BigInt:
if (value.GetType() == typeof(Int64))
extendedCode = ExtendedClrTypeCode.Int64;
@@ -209,19 +220,19 @@ internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType
case SqlDbType.VarBinary:
case SqlDbType.Image:
case SqlDbType.Timestamp:
- if (value.GetType() == typeof( byte[] ))
+ if (value.GetType() == typeof(byte[]))
extendedCode = ExtendedClrTypeCode.ByteArray;
- else if (value.GetType() == typeof( SqlBinary ))
+ else if (value.GetType() == typeof(SqlBinary))
extendedCode = ExtendedClrTypeCode.SqlBinary;
- else if (value.GetType() == typeof( SqlBytes ))
+ else if (value.GetType() == typeof(SqlBytes))
extendedCode = ExtendedClrTypeCode.SqlBytes;
else if (value.GetType() == typeof(StreamDataFeed))
extendedCode = ExtendedClrTypeCode.Stream;
break;
case SqlDbType.Bit:
- if (value.GetType() == typeof( bool ))
+ if (value.GetType() == typeof(bool))
extendedCode = ExtendedClrTypeCode.Boolean;
- else if (value.GetType() == typeof( SqlBoolean ))
+ else if (value.GetType() == typeof(SqlBoolean))
extendedCode = ExtendedClrTypeCode.SqlBoolean;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.Boolean)
extendedCode = ExtendedClrTypeCode.Boolean;
@@ -232,10 +243,10 @@ internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.VarChar:
- if (value.GetType() == typeof( string ))
+ if (value.GetType() == typeof(string))
extendedCode = ExtendedClrTypeCode.String;
if (value.GetType() == typeof(TextDataFeed))
- extendedCode = ExtendedClrTypeCode.TextReader;
+ extendedCode = ExtendedClrTypeCode.TextReader;
else if (value.GetType() == typeof(SqlString))
extendedCode = ExtendedClrTypeCode.SqlString;
else if (value.GetType() == typeof(char[]))
@@ -251,100 +262,104 @@ internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType
break;
case SqlDbType.Date:
case SqlDbType.DateTime2:
- if (smiVersion >= SmiContextFactory.KatmaiVersion) {
+ if (smiVersion >= SmiContextFactory.KatmaiVersion)
+ {
goto case SqlDbType.DateTime;
}
break;
case SqlDbType.DateTime:
case SqlDbType.SmallDateTime:
- if (value.GetType() == typeof( DateTime ))
+ if (value.GetType() == typeof(DateTime))
extendedCode = ExtendedClrTypeCode.DateTime;
- else if (value.GetType() == typeof( SqlDateTime ))
+ else if (value.GetType() == typeof(SqlDateTime))
extendedCode = ExtendedClrTypeCode.SqlDateTime;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.DateTime)
extendedCode = ExtendedClrTypeCode.DateTime;
break;
case SqlDbType.Decimal:
- if (value.GetType() == typeof( Decimal ))
+ if (value.GetType() == typeof(Decimal))
extendedCode = ExtendedClrTypeCode.Decimal;
- else if (value.GetType() == typeof( SqlDecimal ))
+ else if (value.GetType() == typeof(SqlDecimal))
extendedCode = ExtendedClrTypeCode.SqlDecimal;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.Decimal)
extendedCode = ExtendedClrTypeCode.Decimal;
break;
case SqlDbType.Real:
- if (value.GetType() == typeof( Single ))
+ if (value.GetType() == typeof(Single))
extendedCode = ExtendedClrTypeCode.Single;
- else if (value.GetType() == typeof( SqlSingle ))
+ else if (value.GetType() == typeof(SqlSingle))
extendedCode = ExtendedClrTypeCode.SqlSingle;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.Single)
extendedCode = ExtendedClrTypeCode.Single;
break;
case SqlDbType.Int:
- if (value.GetType() == typeof( Int32 ))
+ if (value.GetType() == typeof(Int32))
extendedCode = ExtendedClrTypeCode.Int32;
- else if (value.GetType() == typeof( SqlInt32 ))
+ else if (value.GetType() == typeof(SqlInt32))
extendedCode = ExtendedClrTypeCode.SqlInt32;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.Int32)
extendedCode = ExtendedClrTypeCode.Int32;
break;
case SqlDbType.Money:
case SqlDbType.SmallMoney:
- if (value.GetType() == typeof( SqlMoney ))
+ if (value.GetType() == typeof(SqlMoney))
extendedCode = ExtendedClrTypeCode.SqlMoney;
- else if (value.GetType() == typeof( Decimal ))
+ else if (value.GetType() == typeof(Decimal))
extendedCode = ExtendedClrTypeCode.Decimal;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.Decimal)
extendedCode = ExtendedClrTypeCode.Decimal;
break;
case SqlDbType.Float:
- if (value.GetType() == typeof( SqlDouble ))
+ if (value.GetType() == typeof(SqlDouble))
extendedCode = ExtendedClrTypeCode.SqlDouble;
- else if (value.GetType() == typeof( Double ))
+ else if (value.GetType() == typeof(Double))
extendedCode = ExtendedClrTypeCode.Double;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.Double)
extendedCode = ExtendedClrTypeCode.Double;
break;
case SqlDbType.UniqueIdentifier:
- if (value.GetType() == typeof( SqlGuid ))
+ if (value.GetType() == typeof(SqlGuid))
extendedCode = ExtendedClrTypeCode.SqlGuid;
- else if (value.GetType() == typeof( Guid ))
+ else if (value.GetType() == typeof(Guid))
extendedCode = ExtendedClrTypeCode.Guid;
break;
case SqlDbType.SmallInt:
- if (value.GetType() == typeof( Int16 ))
+ if (value.GetType() == typeof(Int16))
extendedCode = ExtendedClrTypeCode.Int16;
- else if (value.GetType() == typeof( SqlInt16 ))
+ else if (value.GetType() == typeof(SqlInt16))
extendedCode = ExtendedClrTypeCode.SqlInt16;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.Int16)
extendedCode = ExtendedClrTypeCode.Int16;
break;
case SqlDbType.TinyInt:
- if (value.GetType() == typeof( Byte ))
+ if (value.GetType() == typeof(Byte))
extendedCode = ExtendedClrTypeCode.Byte;
- else if (value.GetType() == typeof( SqlByte ))
+ else if (value.GetType() == typeof(SqlByte))
extendedCode = ExtendedClrTypeCode.SqlByte;
else if (Type.GetTypeCode(value.GetType()) == TypeCode.Byte)
extendedCode = ExtendedClrTypeCode.Byte;
break;
case SqlDbType.Variant:
// SqlDbType doesn't help us here, call general-purpose function
- extendedCode = DetermineExtendedTypeCode( value );
+ extendedCode = DetermineExtendedTypeCode(value);
// Some types aren't allowed for Variants but are for the general-purpos function.
// Match behavior of other types and return invalid in these cases.
- if ( ExtendedClrTypeCode.SqlXml == extendedCode ) {
+ if (ExtendedClrTypeCode.SqlXml == extendedCode)
+ {
extendedCode = ExtendedClrTypeCode.Invalid;
}
break;
case SqlDbType.Udt:
// Validate UDT type if caller gave us a type to validate against
- if ( null == udtType ||
+ if (null == udtType ||
value.GetType() == udtType
- ) {
+ )
+ {
extendedCode = ExtendedClrTypeCode.Object;
}
- else {
+ else
+ {
extendedCode = ExtendedClrTypeCode.Invalid;
}
break;
@@ -357,24 +372,28 @@ internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType
extendedCode = ExtendedClrTypeCode.DateTimeOffset;
break;
case SqlDbType.Xml:
- if (value.GetType() == typeof( SqlXml ))
+ if (value.GetType() == typeof(SqlXml))
extendedCode = ExtendedClrTypeCode.SqlXml;
if (value.GetType() == typeof(XmlDataFeed))
extendedCode = ExtendedClrTypeCode.XmlReader;
- else if (value.GetType() == typeof( System.String ))
+ else if (value.GetType() == typeof(System.String))
extendedCode = ExtendedClrTypeCode.String;
break;
case SqlDbType.Structured:
- if (isMultiValued) {
- if (value is DataTable) {
+ if (isMultiValued)
+ {
+ if (value is DataTable)
+ {
extendedCode = ExtendedClrTypeCode.DataTable;
}
// Order is important, since some of these types are base types of the others.
// Evaluate from most derived to parent types
- else if (value is IEnumerable) {
+ else if (value is IEnumerable)
+ {
extendedCode = ExtendedClrTypeCode.IEnumerableOfSqlDataRecord;
}
- else if (value is DbDataReader) {
+ else if (value is DbDataReader)
+ {
extendedCode = ExtendedClrTypeCode.DbDataReader;
}
}
@@ -382,7 +401,7 @@ internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType
default:
// Leave as invalid
break;
- }
+ }
}
return extendedCode;
@@ -390,21 +409,24 @@ internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType
}
// Method to map from Type to ExtendedTypeCode
- static internal ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrType) {
+ static internal ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrType)
+ {
object result = __typeToExtendedTypeCodeMap[clrType];
ExtendedClrTypeCode resultCode;
- if ( null == result ) {
+ if (null == result)
+ {
resultCode = ExtendedClrTypeCode.Invalid;
}
- else {
- resultCode = (ExtendedClrTypeCode) result;
+ else
+ {
+ resultCode = (ExtendedClrTypeCode)result;
}
return resultCode;
}
- // Returns the ExtendedClrTypeCode that describes the given value
+ // Returns the ExtendedClrTypeCode that describes the given value
// UNDONE: see if switch on Type.GetTypeCode() + conditionals for object types would be even faster than hash table.
// something like:
// Type type = value.GetType();
@@ -417,12 +439,15 @@ static internal ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrTy
// }
// else if ( type == typeof( char[] ) {
// ...
- static internal ExtendedClrTypeCode DetermineExtendedTypeCode( object value ) {
+ static internal ExtendedClrTypeCode DetermineExtendedTypeCode(object value)
+ {
ExtendedClrTypeCode resultCode;
- if ( null == value ) {
+ if (null == value)
+ {
resultCode = ExtendedClrTypeCode.Empty;
}
- else {
+ else
+ {
resultCode = DetermineExtendedTypeCodeFromType(value.GetType());
}
@@ -430,21 +455,25 @@ static internal ExtendedClrTypeCode DetermineExtendedTypeCode( object value ) {
}
// returns a sqldbtype for the given type code
- static internal SqlDbType InferSqlDbTypeFromTypeCode( ExtendedClrTypeCode typeCode ) {
- Debug.Assert( typeCode >= ExtendedClrTypeCode.Invalid && typeCode <= ExtendedClrTypeCode.Last, "Someone added a typecode without adding support here!" );
+ static internal SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCode)
+ {
+ Debug.Assert(typeCode >= ExtendedClrTypeCode.Invalid && typeCode <= ExtendedClrTypeCode.Last, "Someone added a typecode without adding support here!");
- return __extendedTypeCodeToSqlDbTypeMap[ (int) typeCode+1 ];
+ return __extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1];
}
// Infer SqlDbType from Type in the general case. Katmai-only (or later) features that need to
// infer types should use InferSqlDbTypeFromType_Katmai.
- static internal SqlDbType InferSqlDbTypeFromType(Type type) {
+ static internal SqlDbType InferSqlDbTypeFromType(Type type)
+ {
ExtendedClrTypeCode typeCode = DetermineExtendedTypeCodeFromType(type);
SqlDbType returnType;
- if (ExtendedClrTypeCode.Invalid == typeCode) {
+ if (ExtendedClrTypeCode.Invalid == typeCode)
+ {
returnType = InvalidSqlDbType; // Return invalid type so caller can generate specific error
}
- else {
+ else
+ {
returnType = InferSqlDbTypeFromTypeCode(typeCode);
}
@@ -456,19 +485,24 @@ static internal SqlDbType InferSqlDbTypeFromType(Type type) {
// example: TVP's are a new Katmai feature (no back compat issues) so can infer DATETIME2
// when mapping System.DateTime from DateTable or DbDataReader. DATETIME2 is better because
// of greater range that can handle all DateTime values.
- static internal SqlDbType InferSqlDbTypeFromType_Katmai(Type type) {
+ static internal SqlDbType InferSqlDbTypeFromType_Katmai(Type type)
+ {
SqlDbType returnType = InferSqlDbTypeFromType(type);
- if (SqlDbType.DateTime == returnType) {
+ if (SqlDbType.DateTime == returnType)
+ {
returnType = SqlDbType.DateTime2;
}
return returnType;
}
- static internal bool IsValidForSmiVersion(SmiExtendedMetaData md, ulong smiVersion) {
- if (SmiContextFactory.LatestVersion == smiVersion) {
+ static internal bool IsValidForSmiVersion(SmiExtendedMetaData md, ulong smiVersion)
+ {
+ if (SmiContextFactory.LatestVersion == smiVersion)
+ {
return true;
}
- else {
+ else
+ {
// Yukon doesn't support Structured nor the new time types
Debug.Assert(SmiContextFactory.YukonVersion == smiVersion, "Other versions should have been eliminated during link stage");
return md.SqlDbType != SqlDbType.Structured &&
@@ -512,51 +546,60 @@ static internal SqlMetaData SmiExtendedMetaDataToSqlMetaData(SmiExtendedMetaData
// Convert SqlMetaData instance to an SmiExtendedMetaData instance.
- internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData( SqlMetaData source ) {
+ internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData source)
+ {
// now map everything across to the extended metadata object
string typeSpecificNamePart1 = null;
string typeSpecificNamePart2 = null;
string typeSpecificNamePart3 = null;
-
- if (SqlDbType.Xml == source.SqlDbType) {
+
+ if (SqlDbType.Xml == source.SqlDbType)
+ {
typeSpecificNamePart1 = source.XmlSchemaCollectionDatabase;
typeSpecificNamePart2 = source.XmlSchemaCollectionOwningSchema;
typeSpecificNamePart3 = source.XmlSchemaCollectionName;
}
- else if (SqlDbType.Udt == source.SqlDbType) {
+ else if (SqlDbType.Udt == source.SqlDbType)
+ {
// Split the input name. UdtTypeName is specified as single 3 part name.
// NOTE: ParseUdtTypeName throws if format is incorrect
PropertyInfo serverTypeNameProperty = source.GetType().GetProperty("ServerTypeName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
MethodInfo getter = serverTypeNameProperty.GetGetMethod(nonPublic: true);
String typeName = (string)getter.Invoke(source, null);
- if (null != typeName) {
+ if (null != typeName)
+ {
String[] names = SqlParameter.ParseTypeName(typeName, true /* is for UdtTypeName */);
- if (1 == names.Length) {
+ if (1 == names.Length)
+ {
typeSpecificNamePart3 = names[0];
}
- else if (2 == names.Length) {
+ else if (2 == names.Length)
+ {
typeSpecificNamePart2 = names[0];
typeSpecificNamePart3 = names[1];
}
- else if (3 == names.Length) {
+ else if (3 == names.Length)
+ {
typeSpecificNamePart1 = names[0];
typeSpecificNamePart2 = names[1];
typeSpecificNamePart3 = names[2];
}
- else {
+ else
+ {
throw ADP.ArgumentOutOfRange("typeName");
}
if ((!ADP.IsEmpty(typeSpecificNamePart1) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart1.Length)
|| (!ADP.IsEmpty(typeSpecificNamePart2) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart2.Length)
- || (!ADP.IsEmpty(typeSpecificNamePart3) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart3.Length)) {
+ || (!ADP.IsEmpty(typeSpecificNamePart3) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart3.Length))
+ {
throw ADP.ArgumentOutOfRange("typeName");
}
}
- }
+ }
- return new SmiExtendedMetaData( source.SqlDbType,
+ return new SmiExtendedMetaData(source.SqlDbType,
source.MaxLength,
source.Precision,
source.Scale,
@@ -566,14 +609,15 @@ internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData( SqlMetaDat
source.Name,
typeSpecificNamePart1,
typeSpecificNamePart2,
- typeSpecificNamePart3 );
+ typeSpecificNamePart3);
}
// compare SmiMetaData to SqlMetaData and determine if they are compatible.
- static internal bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd) {
+ static internal bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd)
+ {
return firstMd.SqlDbType == secondMd.SqlDbType &&
firstMd.MaxLength == secondMd.MaxLength &&
firstMd.Precision == secondMd.Precision &&
@@ -585,43 +629,53 @@ static internal bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd) {
!firstMd.IsMultiValued; // SqlMetaData doesn't have a "multivalued" option
}
- static internal long AdjustMaxLength(SqlDbType dbType, long maxLength) {
- if (SmiMetaData.UnlimitedMaxLengthIndicator != maxLength) {
- if (maxLength < 0) {
+ static internal long AdjustMaxLength(SqlDbType dbType, long maxLength)
+ {
+ if (SmiMetaData.UnlimitedMaxLengthIndicator != maxLength)
+ {
+ if (maxLength < 0)
+ {
maxLength = InvalidMaxLength;
}
- switch(dbType) {
+ switch (dbType)
+ {
case SqlDbType.Binary:
- if (maxLength > SmiMetaData.MaxBinaryLength) {
+ if (maxLength > SmiMetaData.MaxBinaryLength)
+ {
maxLength = InvalidMaxLength;
}
break;
case SqlDbType.Char:
- if (maxLength > SmiMetaData.MaxANSICharacters) {
+ if (maxLength > SmiMetaData.MaxANSICharacters)
+ {
maxLength = InvalidMaxLength;
}
break;
case SqlDbType.NChar:
- if (maxLength > SmiMetaData.MaxUnicodeCharacters) {
+ if (maxLength > SmiMetaData.MaxUnicodeCharacters)
+ {
maxLength = InvalidMaxLength;
}
break;
case SqlDbType.NVarChar:
// Promote to MAX type if it won't fit in a normal type
- if (SmiMetaData.MaxUnicodeCharacters < maxLength) {
+ if (SmiMetaData.MaxUnicodeCharacters < maxLength)
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
break;
case SqlDbType.VarBinary:
// Promote to MAX type if it won't fit in a normal type
- if (SmiMetaData.MaxBinaryLength < maxLength) {
+ if (SmiMetaData.MaxBinaryLength < maxLength)
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
break;
case SqlDbType.VarChar:
// Promote to MAX type if it won't fit in a normal type
- if (SmiMetaData.MaxANSICharacters < maxLength) {
+ if (SmiMetaData.MaxANSICharacters < maxLength)
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
break;
@@ -641,36 +695,45 @@ private static CultureInfo GetColumnLocale(DataColumn column)
}
// Extract metadata for a single DataColumn
- static internal SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, DataTable parent) {
+ static internal SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, DataTable parent)
+ {
SqlDbType dbType = InferSqlDbTypeFromType_Katmai(column.DataType);
- if (InvalidSqlDbType == dbType) {
+ if (InvalidSqlDbType == dbType)
+ {
throw SQL.UnsupportedColumnTypeForSqlProvider(column.ColumnName, column.DataType.Name);
}
long maxLength = AdjustMaxLength(dbType, column.MaxLength);
- if (InvalidMaxLength == maxLength) {
+ if (InvalidMaxLength == maxLength)
+ {
throw SQL.InvalidColumnMaxLength(column.ColumnName, maxLength);
}
byte precision;
byte scale;
- if (column.DataType == typeof(SqlDecimal)) {
+ if (column.DataType == typeof(SqlDecimal))
+ {
// Must scan all values in column to determine best-fit precision & scale
Debug.Assert(null != parent);
scale = 0;
byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision
- foreach (DataRow row in parent.Rows) {
+ foreach (DataRow row in parent.Rows)
+ {
object obj = row[column];
- if (!(obj is DBNull)) {
- SqlDecimal value = (SqlDecimal) obj;
- if (!value.IsNull) {
- byte tempNonFractPrec = checked((byte) (value.Precision - value.Scale));
- if (tempNonFractPrec > nonFractionalPrecision) {
+ if (!(obj is DBNull))
+ {
+ SqlDecimal value = (SqlDecimal)obj;
+ if (!value.IsNull)
+ {
+ byte tempNonFractPrec = checked((byte)(value.Precision - value.Scale));
+ if (tempNonFractPrec > nonFractionalPrecision)
+ {
nonFractionalPrecision = tempNonFractPrec;
}
- if (value.Scale > scale) {
+ if (value.Scale > scale)
+ {
scale = value.Scale;
}
}
@@ -679,33 +742,41 @@ static internal SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column,
precision = checked((byte)(nonFractionalPrecision + scale));
- if (SqlDecimal.MaxPrecision < precision) {
+ if (SqlDecimal.MaxPrecision < precision)
+ {
throw SQL.InvalidTableDerivedPrecisionForTvp(column.ColumnName, precision);
}
- else if (0 == precision) {
+ else if (0 == precision)
+ {
precision = 1;
}
}
- else if (dbType == SqlDbType.DateTime2 || dbType == SqlDbType.DateTimeOffset || dbType == SqlDbType.Time) {
+ else if (dbType == SqlDbType.DateTime2 || dbType == SqlDbType.DateTimeOffset || dbType == SqlDbType.Time)
+ {
// Time types care about scale, too. But have to infer maximums for these.
precision = 0;
scale = SmiMetaData.DefaultTime.Scale;
}
- else if (dbType == SqlDbType.Decimal) {
+ else if (dbType == SqlDbType.Decimal)
+ {
// Must scan all values in column to determine best-fit precision & scale
Debug.Assert(null != parent);
scale = 0;
byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision
- foreach (DataRow row in parent.Rows) {
+ foreach (DataRow row in parent.Rows)
+ {
object obj = row[column];
- if (!(obj is DBNull)) {
+ if (!(obj is DBNull))
+ {
SqlDecimal value = (SqlDecimal)(Decimal)obj;
byte tempNonFractPrec = checked((byte)(value.Precision - value.Scale));
- if (tempNonFractPrec > nonFractionalPrecision) {
+ if (tempNonFractPrec > nonFractionalPrecision)
+ {
nonFractionalPrecision = tempNonFractPrec;
}
- if (value.Scale > scale) {
+ if (value.Scale > scale)
+ {
scale = value.Scale;
}
}
@@ -713,60 +784,69 @@ static internal SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column,
precision = checked((byte)(nonFractionalPrecision + scale));
- if (SqlDecimal.MaxPrecision < precision) {
+ if (SqlDecimal.MaxPrecision < precision)
+ {
throw SQL.InvalidTableDerivedPrecisionForTvp(column.ColumnName, precision);
}
- else if (0 == precision) {
+ else if (0 == precision)
+ {
precision = 1;
}
}
- else {
+ else
+ {
precision = 0;
scale = 0;
}
CultureInfo locale = GetColumnLocale(column);
return new SmiExtendedMetaData(
- dbType,
- maxLength,
- precision,
+ dbType,
+ maxLength,
+ precision,
scale,
locale.LCID,
- SmiMetaData.DefaultNVarChar.CompareOptions,
- column.DataType,
+ SmiMetaData.DefaultNVarChar.CompareOptions,
+ column.DataType,
false, // no support for multi-valued columns in a TVP yet
null, // no support for structured columns yet
null, // no support for structured columns yet
- column.ColumnName,
- null,
- null,
+ column.ColumnName,
+ null,
+ null,
null);
}
// Map SmiMetaData from a schema table.
// DEVNOTE: since we're using SchemaTable, we can assume that we aren't directly using a SqlDataReader
// so we don't support the Sql-specific stuff, like collation
- static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schemaRow) {
+ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schemaRow)
+ {
// One way or another, we'll need column name, so put it in a local now to shorten code later.
string colName = "";
object temp = schemaRow[SchemaTableColumn.ColumnName];
- if (DBNull.Value != temp) {
+ if (DBNull.Value != temp)
+ {
colName = (string)temp;
}
// Determine correct SqlDbType.
temp = schemaRow[SchemaTableColumn.DataType];
- if (DBNull.Value == temp) {
+ if (DBNull.Value == temp)
+ {
throw SQL.NullSchemaTableDataTypeNotSupported(colName);
}
Type colType = (Type)temp;
SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType);
- if (InvalidSqlDbType == colDbType) {
+ if (InvalidSqlDbType == colDbType)
+ {
// Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise error
- if (typeof(object) == colType) {
+ if (typeof(object) == colType)
+ {
colDbType = SqlDbType.VarBinary;
}
- else {
+ else
+ {
throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString());
}
}
@@ -775,7 +855,8 @@ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
long maxLength = 0;
byte precision = 0;
byte scale = 0;
- switch (colDbType) {
+ switch (colDbType)
+ {
case SqlDbType.BigInt:
case SqlDbType.Bit:
case SqlDbType.DateTime:
@@ -801,28 +882,34 @@ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
case SqlDbType.VarBinary:
// These types need a binary max length
temp = schemaRow[SchemaTableColumn.ColumnSize];
- if (DBNull.Value == temp) {
+ if (DBNull.Value == temp)
+ {
// source isn't specifying a size, so assume the worst
- if (SqlDbType.Binary == colDbType) {
+ if (SqlDbType.Binary == colDbType)
+ {
maxLength = SmiMetaData.MaxBinaryLength;
}
- else {
+ else
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
}
- else {
+ else
+ {
// We (should) have a valid maxlength, so use it.
maxLength = Convert.ToInt64(temp, null);
// Max length must be 0 to MaxBinaryLength or it can be UnlimitedMAX if type is varbinary
// If it's greater than MaxBinaryLength, just promote it to UnlimitedMAX, if possible
- if (maxLength > SmiMetaData.MaxBinaryLength) {
+ if (maxLength > SmiMetaData.MaxBinaryLength)
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
if ((maxLength < 0 &&
(maxLength != SmiMetaData.UnlimitedMaxLengthIndicator ||
- SqlDbType.Binary == colDbType))) {
+ SqlDbType.Binary == colDbType)))
+ {
throw SQL.InvalidColumnMaxLength(colName, maxLength);
}
}
@@ -831,28 +918,34 @@ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
case SqlDbType.VarChar:
// These types need an ANSI max length
temp = schemaRow[SchemaTableColumn.ColumnSize];
- if (DBNull.Value == temp) {
+ if (DBNull.Value == temp)
+ {
// source isn't specifying a size, so assume the worst
- if (SqlDbType.Char == colDbType) {
+ if (SqlDbType.Char == colDbType)
+ {
maxLength = SmiMetaData.MaxANSICharacters;
}
- else {
+ else
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
}
- else {
+ else
+ {
// We (should) have a valid maxlength, so use it.
maxLength = Convert.ToInt64(temp, null);
// Max length must be 0 to MaxANSICharacters or it can be UnlimitedMAX if type is varbinary
// If it's greater than MaxANSICharacters, just promote it to UnlimitedMAX, if possible
- if (maxLength > SmiMetaData.MaxANSICharacters) {
+ if (maxLength > SmiMetaData.MaxANSICharacters)
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
- if ((maxLength < 0 &&
+ if ((maxLength < 0 &&
(maxLength != SmiMetaData.UnlimitedMaxLengthIndicator ||
- SqlDbType.Char == colDbType))) {
+ SqlDbType.Char == colDbType)))
+ {
throw SQL.InvalidColumnMaxLength(colName, maxLength);
}
}
@@ -861,28 +954,34 @@ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
case SqlDbType.NVarChar:
// These types need a unicode max length
temp = schemaRow[SchemaTableColumn.ColumnSize];
- if (DBNull.Value == temp) {
+ if (DBNull.Value == temp)
+ {
// source isn't specifying a size, so assume the worst
- if (SqlDbType.NChar == colDbType) {
+ if (SqlDbType.NChar == colDbType)
+ {
maxLength = SmiMetaData.MaxUnicodeCharacters;
}
- else {
+ else
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
}
- else {
+ else
+ {
// We (should) have a valid maxlength, so use it.
maxLength = Convert.ToInt64(temp, null);
// Max length must be 0 to MaxUnicodeCharacters or it can be UnlimitedMAX if type is varbinary
// If it's greater than MaxUnicodeCharacters, just promote it to UnlimitedMAX, if possible
- if (maxLength > SmiMetaData.MaxUnicodeCharacters) {
+ if (maxLength > SmiMetaData.MaxUnicodeCharacters)
+ {
maxLength = SmiMetaData.UnlimitedMaxLengthIndicator;
}
if ((maxLength < 0 &&
(maxLength != SmiMetaData.UnlimitedMaxLengthIndicator ||
- SqlDbType.NChar == colDbType))) {
+ SqlDbType.NChar == colDbType)))
+ {
throw SQL.InvalidColumnMaxLength(colName, maxLength);
}
}
@@ -890,26 +989,31 @@ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
case SqlDbType.Decimal:
// Decimal requires precision and scale
temp = schemaRow[SchemaTableColumn.NumericPrecision];
- if (DBNull.Value == temp) {
+ if (DBNull.Value == temp)
+ {
precision = SmiMetaData.DefaultDecimal.Precision;
}
- else {
+ else
+ {
precision = Convert.ToByte(temp, null);
}
temp = schemaRow[SchemaTableColumn.NumericScale];
- if (DBNull.Value == temp) {
+ if (DBNull.Value == temp)
+ {
scale = SmiMetaData.DefaultDecimal.Scale;
}
- else {
+ else
+ {
scale = Convert.ToByte(temp, null);
}
- if (precision < SmiMetaData.MinPrecision ||
- precision > SqlDecimal.MaxPrecision ||
- scale < SmiMetaData.MinScale ||
+ if (precision < SmiMetaData.MinPrecision ||
+ precision > SqlDecimal.MaxPrecision ||
+ scale < SmiMetaData.MinScale ||
scale > SqlDecimal.MaxScale ||
- scale > precision) {
+ scale > precision)
+ {
throw SQL.InvalidColumnPrecScale();
}
break;
@@ -918,17 +1022,21 @@ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
case SqlDbType.DateTimeOffset:
// requires scale
temp = schemaRow[SchemaTableColumn.NumericScale];
- if (DBNull.Value == temp) {
+ if (DBNull.Value == temp)
+ {
scale = SmiMetaData.DefaultTime.Scale;
}
- else {
+ else
+ {
scale = Convert.ToByte(temp, null);
}
- if (scale > SmiMetaData.MaxTimeScale) {
+ if (scale > SmiMetaData.MaxTimeScale)
+ {
throw SQL.InvalidColumnPrecScale();
}
- else if (scale < 0) {
+ else if (scale < 0)
+ {
scale = SmiMetaData.DefaultTime.Scale;
}
break;
@@ -940,19 +1048,19 @@ static internal SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schema
}
return new SmiExtendedMetaData(
- colDbType,
- maxLength,
- precision,
- scale,
- System.Globalization.CultureInfo.CurrentCulture.LCID,
- SmiMetaData.GetDefaultForType(colDbType).CompareOptions,
+ colDbType,
+ maxLength,
+ precision,
+ scale,
+ System.Globalization.CultureInfo.CurrentCulture.LCID,
+ SmiMetaData.GetDefaultForType(colDbType).CompareOptions,
null, // no support for UDTs from SchemaTable
false, // no support for multi-valued columns in a TVP yet
null, // no support for structured columns yet
null, // no support for structured columns yet
- colName,
- null,
- null,
+ colName,
+ null,
+ null,
null);
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiConnection.cs
index 7514666cc0..bf04a3a23f 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiConnection.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiConnection.cs
@@ -5,86 +5,90 @@
using System;
using System.Data;
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
- internal abstract class SmiConnection : IDisposable {
+ internal abstract class SmiConnection : IDisposable
+ {
//
// Miscellaneous directives / accessors
//
internal abstract string GetCurrentDatabase(
- SmiEventSink eventSink
+ SmiEventSink eventSink
);
- internal abstract void SetCurrentDatabase (
- string databaseName,
- SmiEventSink eventSink
+ internal abstract void SetCurrentDatabase(
+ string databaseName,
+ SmiEventSink eventSink
);
-
+
//
// IDisposable
//
- public virtual void Dispose( ) {
+ public virtual void Dispose()
+ {
// Obsoleting from SMI -- use Close( SmiEventSink ) instead.
// Intended to be removed (along with inheriting IDisposable) prior to RTM.
// Implement body with throw because there are only a couple of ways to get to this code:
// 1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
// 2) Server didn't implement V2- on some interface and negotiated V2-.
- Microsoft.Data.Common.ADP.InternalError( Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod );
+ Microsoft.Data.Common.ADP.InternalError(Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
}
public virtual void Close(
- SmiEventSink eventSink
- ) {
+ SmiEventSink eventSink
+ )
+ {
// Adding as of V3
// Implement body with throw because there are only a couple of ways to get to this code:
// 1) Client is calling this method even though the server negotiated for V2- and hasn't implemented V3 yet.
// 2) Server didn't implement V3 on some interface, but negotiated V3+.
- Microsoft.Data.Common.ADP.InternalError( Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod );
+ Microsoft.Data.Common.ADP.InternalError(Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
}
//
// Transaction API (should we encapsulate in it's own class or interface?)
//
- internal abstract void BeginTransaction (
- string name,
- IsolationLevel level,
- SmiEventSink eventSink
+ internal abstract void BeginTransaction(
+ string name,
+ IsolationLevel level,
+ SmiEventSink eventSink
);
- internal abstract void CommitTransaction (
- long transactionId,
- SmiEventSink eventSink
+ internal abstract void CommitTransaction(
+ long transactionId,
+ SmiEventSink eventSink
);
- internal abstract void CreateTransactionSavePoint (
- long transactionId,
- string name,
- SmiEventSink eventSink
+ internal abstract void CreateTransactionSavePoint(
+ long transactionId,
+ string name,
+ SmiEventSink eventSink
);
internal abstract byte[] GetDTCAddress( // better buffer management needed? I.e. non-allocating call needed/possible?
- SmiEventSink eventSink
+ SmiEventSink eventSink
);
- internal abstract void EnlistTransaction (
- byte[] token, // better buffer management needed? I.e. non-allocating call needed/possible?
- SmiEventSink eventSink
+ internal abstract void EnlistTransaction(
+ byte[] token, // better buffer management needed? I.e. non-allocating call needed/possible?
+ SmiEventSink eventSink
);
- internal abstract byte[] PromoteTransaction ( // better buffer management needed? I.e. non-allocating call needed/possible?
- long transactionId,
- SmiEventSink eventSink
+ internal abstract byte[] PromoteTransaction( // better buffer management needed? I.e. non-allocating call needed/possible?
+ long transactionId,
+ SmiEventSink eventSink
);
- internal abstract void RollbackTransaction (
- long transactionId,
- string savePointName, // only roll back to save point if name non-null
- SmiEventSink eventSink
+ internal abstract void RollbackTransaction(
+ long transactionId,
+ string savePointName, // only roll back to save point if name non-null
+ SmiEventSink eventSink
);
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContext.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContext.cs
index 5a98ee5773..efdb16e287 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContext.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContext.cs
@@ -3,16 +3,18 @@
// See the LICENSE file in the project root for more information.
using System;
-using System.Security.Principal;
-using System.Data.SqlTypes;
using System.Data;
+using System.Data.SqlTypes;
+using System.Security.Principal;
-namespace Microsoft.Data.SqlClient.Server {
+namespace Microsoft.Data.SqlClient.Server
+{
// NOTE: connection, transaction and context pipe operations could be
// encapsulated in their own classes, and should if they get complex
// (transaction is borderline at this point).
- internal abstract class SmiContext {
+ internal abstract class SmiContext
+ {
internal abstract event EventHandler OutOfScope;
@@ -25,48 +27,49 @@ internal abstract class SmiContext {
internal abstract bool HasContextPipe { get; }
internal abstract WindowsIdentity WindowsIdentity { get; }
-
- internal abstract SmiRecordBuffer CreateRecordBuffer (
- SmiExtendedMetaData[] columnMetaData, // Extended metadata because it requires names, udttypename and xmlschemaname ignored
- SmiEventSink eventSink
+
+ internal abstract SmiRecordBuffer CreateRecordBuffer(
+ SmiExtendedMetaData[] columnMetaData, // Extended metadata because it requires names, udttypename and xmlschemaname ignored
+ SmiEventSink eventSink
);
- internal abstract SmiRequestExecutor CreateRequestExecutor (
- string commandText,
- CommandType commandType,
- SmiParameterMetaData[] parameterMetaData,
- SmiEventSink eventSink
+ internal abstract SmiRequestExecutor CreateRequestExecutor(
+ string commandText,
+ CommandType commandType,
+ SmiParameterMetaData[] parameterMetaData,
+ SmiEventSink eventSink
);
// TODO: Consider making ContextConnection, TransactionId and TriggerInfo simply objects you get from the context.
- internal abstract object GetContextValue ( int key );
+ internal abstract object GetContextValue(int key);
- internal abstract void GetTriggerInfo (
- SmiEventSink eventSink,
- out bool[] columnsUpdated,
- out TriggerAction action,
- out SqlXml eventInstanceData
+ internal abstract void GetTriggerInfo(
+ SmiEventSink eventSink,
+ out bool[] columnsUpdated,
+ out TriggerAction action,
+ out SqlXml eventInstanceData
);
- internal abstract void SendMessageToPipe( string message, SmiEventSink eventSink );
+ internal abstract void SendMessageToPipe(string message, SmiEventSink eventSink);
- internal abstract void SendResultsStartToPipe( SmiRecordBuffer recordBuffer, SmiEventSink eventSink );
+ internal abstract void SendResultsStartToPipe(SmiRecordBuffer recordBuffer, SmiEventSink eventSink);
- internal abstract void SendResultsRowToPipe( SmiRecordBuffer recordBuffer, SmiEventSink eventSink );
+ internal abstract void SendResultsRowToPipe(SmiRecordBuffer recordBuffer, SmiEventSink eventSink);
- internal abstract void SendResultsEndToPipe( SmiRecordBuffer recordBuffer, SmiEventSink eventSink );
+ internal abstract void SendResultsEndToPipe(SmiRecordBuffer recordBuffer, SmiEventSink eventSink);
- internal abstract void SetContextValue ( int key, object value );
+ internal abstract void SetContextValue(int key, object value);
// Scratch LOB storage region
- internal virtual SmiStream GetScratchStream( SmiEventSink sink ) {
+ internal virtual SmiStream GetScratchStream(SmiEventSink sink)
+ {
// Adding as of V3
// Implement body with throw because there are only a couple of ways to get to this code:
// 1) Client is calling this method even though the server negotiated for V2- and hasn't implemented V3 yet.
// 2) Server didn't implement V3, but negotiated V3+.
- Microsoft.Data.Common.ADP.InternalError( Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod );
+ Microsoft.Data.Common.ADP.InternalError(Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
return null;
}
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs
index 84b6b7873f..aadbc0d4b1 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs
@@ -3,85 +3,100 @@
// See the LICENSE file in the project root for more information.
using System;
-using Microsoft.Data.SqlClient;
using System.Diagnostics;
-namespace Microsoft.Data.SqlClient.Server {
-
- sealed internal class SmiContextFactory {
+namespace Microsoft.Data.SqlClient.Server
+{
+
+ sealed internal class SmiContextFactory
+ {
public static readonly SmiContextFactory Instance = new SmiContextFactory();
- private readonly SmiLink _smiLink;
- private readonly ulong _negotiatedSmiVersion;
- private readonly byte _majorVersion;
- private readonly byte _minorVersion;
- private readonly short _buildNum;
- private readonly string _serverVersion;
- private readonly SmiEventSink_Default _eventSinkForGetCurrentContext;
+ private readonly SmiLink _smiLink;
+ private readonly ulong _negotiatedSmiVersion;
+ private readonly byte _majorVersion;
+ private readonly byte _minorVersion;
+ private readonly short _buildNum;
+ private readonly string _serverVersion;
+ private readonly SmiEventSink_Default _eventSinkForGetCurrentContext;
internal const ulong YukonVersion = 100;
internal const ulong KatmaiVersion = 210;
internal const ulong LatestVersion = KatmaiVersion;
- private readonly ulong[] __supportedSmiVersions = new ulong[] {YukonVersion, KatmaiVersion};
+ private readonly ulong[] __supportedSmiVersions = new ulong[] { YukonVersion, KatmaiVersion };
// Used as the key for SmiContext.GetContextValue()
- internal enum ContextKey {
+ internal enum ContextKey
+ {
Connection = 0,
SqlContext = 1
}
-
- private SmiContextFactory() {
- if (InOutOfProcHelper.InProc) {
+
+ private SmiContextFactory()
+ {
+ if (InOutOfProcHelper.InProc)
+ {
Type smiLinkType = Type.GetType("Microsoft.SqlServer.Server.InProcLink, SqlAccess, PublicKeyToken=89845dcd8080cc91");
- if (null == smiLinkType) {
+ if (null == smiLinkType)
+ {
Debug.Assert(false, "could not get InProcLink type");
throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server.
}
System.Reflection.FieldInfo instanceField = GetStaticField(smiLinkType, "Instance");
- if (instanceField != null) {
+ if (instanceField != null)
+ {
_smiLink = (SmiLink)GetValue(instanceField);
}
- else {
+ else
+ {
Debug.Assert(false, "could not get InProcLink.Instance");
throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server.
}
-
+
System.Reflection.FieldInfo buildVersionField = GetStaticField(smiLinkType, "BuildVersion");
- if (buildVersionField != null) {
+ if (buildVersionField != null)
+ {
UInt32 buildVersion = (UInt32)GetValue(buildVersionField);
_majorVersion = (byte)(buildVersion >> 24);
_minorVersion = (byte)((buildVersion >> 16) & 0xff);
- _buildNum = (short)(buildVersion & 0xffff);
- _serverVersion = (String.Format((IFormatProvider)null, "{0:00}.{1:00}.{2:0000}", _majorVersion, (short) _minorVersion, _buildNum));
+ _buildNum = (short)(buildVersion & 0xffff);
+ _serverVersion = (String.Format((IFormatProvider)null, "{0:00}.{1:00}.{2:0000}", _majorVersion, (short)_minorVersion, _buildNum));
}
- else {
+ else
+ {
_serverVersion = String.Empty; // default value if nothing exists.
}
- _negotiatedSmiVersion = _smiLink.NegotiateVersion(SmiLink.InterfaceVersion);
+ _negotiatedSmiVersion = _smiLink.NegotiateVersion(SmiLink.InterfaceVersion);
bool isSupportedVersion = false;
- for(int i=0; !isSupportedVersion && i<__supportedSmiVersions.Length; i++) {
- if (__supportedSmiVersions[i] == _negotiatedSmiVersion) {
+ for (int i = 0; !isSupportedVersion && i < __supportedSmiVersions.Length; i++)
+ {
+ if (__supportedSmiVersions[i] == _negotiatedSmiVersion)
+ {
isSupportedVersion = true;
}
}
// Disconnect if we didn't get a supported version!!
- if (!isSupportedVersion) {
+ if (!isSupportedVersion)
+ {
_smiLink = null;
}
_eventSinkForGetCurrentContext = new SmiEventSink_Default();
}
}
-
- internal ulong NegotiatedSmiVersion {
- get {
- if (null == _smiLink) {
+
+ internal ulong NegotiatedSmiVersion
+ {
+ get
+ {
+ if (null == _smiLink)
+ {
throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server, or not be SqlCLR
}
@@ -89,40 +104,48 @@ internal ulong NegotiatedSmiVersion {
}
}
- internal string ServerVersion {
- get {
- if (null == _smiLink) {
+ internal string ServerVersion
+ {
+ get
+ {
+ if (null == _smiLink)
+ {
throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server, or not be SqlCLR
}
return _serverVersion;
}
}
-
- internal SmiContext GetCurrentContext() {
- if (null == _smiLink) {
+
+ internal SmiContext GetCurrentContext()
+ {
+ if (null == _smiLink)
+ {
throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server, or not be SqlCLR
}
object result = _smiLink.GetCurrentContext(_eventSinkForGetCurrentContext);
_eventSinkForGetCurrentContext.ProcessMessagesAndThrow();
- if (null == result) {
- throw SQL.ContextUnavailableWhileInProc();
- }
+ if (null == result)
+ {
+ throw SQL.ContextUnavailableWhileInProc();
+ }
Debug.Assert(typeof(SmiContext).IsInstanceOfType(result), "didn't get SmiContext from GetCurrentContext?");
return (SmiContext)result;
}
- [System.Security.Permissions.ReflectionPermission(System.Security.Permissions.SecurityAction.Assert, MemberAccess=true)]
- private object GetValue(System.Reflection.FieldInfo fieldInfo) {
+ [System.Security.Permissions.ReflectionPermission(System.Security.Permissions.SecurityAction.Assert, MemberAccess = true)]
+ private object GetValue(System.Reflection.FieldInfo fieldInfo)
+ {
object result = fieldInfo.GetValue(null);
return result;
}
- [System.Security.Permissions.ReflectionPermission(System.Security.Permissions.SecurityAction.Assert, MemberAccess=true)]
- private System.Reflection.FieldInfo GetStaticField(Type aType, string fieldName) {
+ [System.Security.Permissions.ReflectionPermission(System.Security.Permissions.SecurityAction.Assert, MemberAccess = true)]
+ private System.Reflection.FieldInfo GetStaticField(Type aType, string fieldName)
+ {
System.Reflection.FieldInfo result = aType.GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.GetField);
return result;
}
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink.cs
index 188004568b..96f493bb69 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink.cs
@@ -2,8 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Data.SqlClient.Server {
-
+namespace Microsoft.Data.SqlClient.Server
+{
// SqlEventSink is implemented by calling code. In all methods that accept
// a SqlEventSink directly the sink must be able to handle multiple callbacks
@@ -19,106 +19,112 @@ namespace Microsoft.Data.SqlClient.Server {
// effect -- the managed to native boundary will eat any exceptions,
// and will cause a simple "Something bad happened" exception to be
// thrown in the native to managed boundary...
- internal abstract class SmiEventSink {
+ internal abstract class SmiEventSink
+ {
#region Active methods
// Called at end of stream whether errors or no
- internal abstract void BatchCompleted( );
+ internal abstract void BatchCompleted();
// Called zero or one time when output parameters are available (errors could prevent event from occuring)
- internal virtual void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter paramValue, int ordinal) {
+ internal virtual void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter paramValue, int ordinal)
+ {
// Adding as of V200
// Implement body with throw because there are only a couple of ways to get to this code:
// 1) Client is calling this method even though the server negotiated for V3- and hasn't implemented V200 yet.
// 2) Server didn't implement V200 on some interface, but negotiated V200+.
- Microsoft.Data.Common.ADP.InternalError( Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod );
+ Microsoft.Data.Common.ADP.InternalError(Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
}
// Called when the server database context changes (ENVCHANGE token)
- internal abstract void DefaultDatabaseChanged( string databaseName );
+ internal abstract void DefaultDatabaseChanged(string databaseName);
// Called for messages and errors (ERROR and INFO tokens)
- internal abstract void MessagePosted ( int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber );
+ internal abstract void MessagePosted(int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber);
// Called for new resultset starting (COLMETADATA token)
- internal abstract void MetaDataAvailable( SmiQueryMetaData[] metaData, bool nextEventIsRow );
+ internal abstract void MetaDataAvailable(SmiQueryMetaData[] metaData, bool nextEventIsRow);
- internal virtual void RowAvailable(SmiTypedGetterSetter rowData) {
+ internal virtual void RowAvailable(SmiTypedGetterSetter rowData)
+ {
// Adding as of V200
// Implement body with throw because there are only a couple of ways to get to this code:
// 1) Client is calling this method even though the server negotiated for V3- and hasn't implemented V200 yet.
// 2) Server didn't implement V200 on some interface, but negotiated V200+.
- Microsoft.Data.Common.ADP.InternalError( Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod );
+ Microsoft.Data.Common.ADP.InternalError(Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
}
// Called when any statement completes on server (DONE token)
- internal abstract void StatementCompleted( int rowsAffected );
+ internal abstract void StatementCompleted(int rowsAffected);
// Called when a transaction is commited (ENVCHANGE token)
- internal abstract void TransactionCommitted( long transactionId );
+ internal abstract void TransactionCommitted(long transactionId);
// Called when a transaction is commited (ENVCHANGE token)
- internal abstract void TransactionDefected( long transactionId );
+ internal abstract void TransactionDefected(long transactionId);
// Called when a transaction is commited (ENVCHANGE token)
- internal abstract void TransactionEnlisted( long transactionId );
+ internal abstract void TransactionEnlisted(long transactionId);
// Called when a transaction is forcibly ended in the server, not requested
// by the provider's batch (ENVCHANGE token)
- internal abstract void TransactionEnded( long transactionId );
+ internal abstract void TransactionEnded(long transactionId);
// Called when a transaction is rolled back (ENVCHANGE token)
- internal abstract void TransactionRolledBack( long transactionId );
+ internal abstract void TransactionRolledBack(long transactionId);
// Called when a transaction is started (ENVCHANGE token)
- internal abstract void TransactionStarted( long transactionId );
+ internal abstract void TransactionStarted(long transactionId);
#endregion
#region OBSOLETE METHODS
#region OBSOLETED as of V200 but active in previous version
// Called zero or one time when output parameters are available (errors could prevent event from occuring)
- internal virtual void ParametersAvailable( SmiParameterMetaData[] metaData, ITypedGettersV3 paramValues ) {
+ internal virtual void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 paramValues)
+ {
// Adding as of V3
// Obsoleting as of V200
// Implement body with throw because there are only a couple of ways to get to this code:
// 1) Client is calling this method even though the server negotiated for V200+ and dropped support for V200-.
// 2) Server didn't implement V3- on some interface and negotiated V3-.
- Microsoft.Data.Common.ADP.InternalError( Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod );
+ Microsoft.Data.Common.ADP.InternalError(Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
}
// Called when a new row arrives (ROW token)
- internal virtual void RowAvailable( ITypedGettersV3 rowData ) {
+ internal virtual void RowAvailable(ITypedGettersV3 rowData)
+ {
// Adding as of V3
// Obsoleting as of V200
// Implement body with throw because there are only a couple of ways to get to this code:
// 1) Client is calling this method even though the server negotiated for V200+ and dropped support for V200-.
// 2) Server didn't implement V3- on some interface and negotiated V3-.
- Microsoft.Data.Common.ADP.InternalError( Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod );
+ Microsoft.Data.Common.ADP.InternalError(Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
}
#endregion
#region OBSOLETED and never shipped (without ObsoleteAttribute)
// Called when a new row arrives (ROW token)
- internal virtual void RowAvailable( ITypedGetters rowData ) {
+ internal virtual void RowAvailable(ITypedGetters rowData)
+ {
// Obsoleting from SMI -- use end of dispose that takes an event sink instead.
// Intended to be removed (along with inheriting IDisposable) prior to RTM.
// Implement body with throw because there are only a couple of ways to get to this code:
// 1) Client is calling this method even though the server negotiated for V3+ and dropped support for V2-.
// 2) Server didn't implement V2- on some interface and negotiated V2-.
- Microsoft.Data.Common.ADP.InternalError( Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod );
+ Microsoft.Data.Common.ADP.InternalError(Microsoft.Data.Common.ADP.InternalErrorCode.UnimplementedSMIMethod);
}
#endregion
#endregion
}
}
-
+
diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs
index 210ef564d0..5fd1cc87cd 100644
--- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs
+++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs
@@ -2,109 +2,138 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using Microsoft.Data.SqlClient;
using System.Diagnostics;
-namespace Microsoft.Data.SqlClient.Server {
-
- internal class SmiEventSink_Default : SmiEventSink {
+namespace Microsoft.Data.SqlClient.Server
+{
- private SmiEventSink _parent; // next level up, which we'll defer to if we don't need to handle the event.
+ internal class SmiEventSink_Default : SmiEventSink
+ {
+
+ private SmiEventSink _parent; // next level up, which we'll defer to if we don't need to handle the event.
private SqlErrorCollection _errors;
private SqlErrorCollection _warnings;
- private SqlErrorCollection Errors {
- get {
- if ( null == _errors ) {
- _errors = new SqlErrorCollection( );
+ private SqlErrorCollection Errors
+ {
+ get
+ {
+ if (null == _errors)
+ {
+ _errors = new SqlErrorCollection();
}
return _errors;
}
}
- internal bool HasMessages {
- get {
+ internal bool HasMessages
+ {
+ get
+ {
SmiEventSink_Default parent = (SmiEventSink_Default)_parent;
- if (null != parent) {
+ if (null != parent)
+ {
return parent.HasMessages;
}
- else {
+ else
+ {
bool result = (null != _errors || null != _warnings);
return result;
}
}
}
- virtual internal string ServerVersion {
- get {
+ virtual internal string ServerVersion
+ {
+ get
+ {
return null;
}
}
- internal SmiEventSink Parent {
- get {
+ internal SmiEventSink Parent
+ {
+ get
+ {
return _parent;
}
- set {
+ set
+ {
_parent = value;
}
}
- private SqlErrorCollection Warnings {
- get {
- if ( null == _warnings ) {
- _warnings = new SqlErrorCollection( );
+ private SqlErrorCollection Warnings
+ {
+ get
+ {
+ if (null == _warnings)
+ {
+ _warnings = new SqlErrorCollection();
}
return _warnings;
}
}
- protected virtual void DispatchMessages(bool ignoreNonFatalMessages) {
+ protected virtual void DispatchMessages(bool ignoreNonFatalMessages)
+ {
// virtual because we want a default implementation in the cases
// where we don't have a connection to process stuff, but we want to
// provide the connection the ability to fire info messages when it
// hooks up.
SmiEventSink_Default parent = (SmiEventSink_Default)_parent;
- if (null != parent) {
+ if (null != parent)
+ {
parent.DispatchMessages(ignoreNonFatalMessages);
}
- else {
+ else
+ {
SqlException errors = ProcessMessages(true, ignoreNonFatalMessages); // ignore warnings, because there's no place to send them...
- if (null != errors) {
+ if (null != errors)
+ {
throw errors;
}
}
}
- protected SqlException ProcessMessages(bool ignoreWarnings, bool ignoreNonFatalMessages) {
+ protected SqlException ProcessMessages(bool ignoreWarnings, bool ignoreNonFatalMessages)
+ {
SqlException result = null;
SqlErrorCollection temp = null; // temp variable to store that which is being thrown - so that local copies can be deleted
- if ( null != _errors ) {
- Debug.Assert( 0 != _errors.Count, "empty error collection?" ); // must be something in the collection
+ if (null != _errors)
+ {
+ Debug.Assert(0 != _errors.Count, "empty error collection?"); // must be something in the collection
- if (ignoreNonFatalMessages) {
+ if (ignoreNonFatalMessages)
+ {
temp = new SqlErrorCollection();
- foreach(SqlError error in _errors) {
- if (error.Class >= TdsEnums.FATAL_ERROR_CLASS){
+ foreach (SqlError error in _errors)
+ {
+ if (error.Class >= TdsEnums.FATAL_ERROR_CLASS)
+ {
temp.Add(error);
}
}
- if (temp.Count <= 0) {
+ if (temp.Count <= 0)
+ {
temp = null;
}
}
- else {
- if (null != _warnings ) {
+ else
+ {
+ if (null != _warnings)
+ {
// When we throw an exception we place all the warnings that
// occurred at the end of the collection - after all the errors.
// That way the user can see all the errors AND warnings that
// occurred for the exception.
- foreach ( SqlError warning in _warnings ) {
- _errors.Add( warning );
+ foreach (SqlError warning in _warnings)
+ {
+ _errors.Add(warning);
}
}
temp = _errors;
@@ -113,43 +142,53 @@ protected SqlException ProcessMessages(bool ignoreWarnings, bool ignoreNonFatalM
_errors = null;
_warnings = null;
}
- else {
- Debug.Assert( null == _warnings || 0 != _warnings.Count, "empty warning collection?" );// must be something in the collection
+ else
+ {
+ Debug.Assert(null == _warnings || 0 != _warnings.Count, "empty warning collection?");// must be something in the collection
- if (!ignoreWarnings) {
+ if (!ignoreWarnings)
+ {
temp = _warnings;
}
_warnings = null;
}
- if ( null != temp ) {
- result = SqlException.CreateException( temp, ServerVersion );
+ if (null != temp)
+ {
+ result = SqlException.CreateException(temp, ServerVersion);
}
return result;
}
- internal void CleanMessages() {
+ internal void CleanMessages()
+ {
SmiEventSink_Default parent = (SmiEventSink_Default)_parent;
- if (null != parent) {
+ if (null != parent)
+ {
parent.CleanMessages();
}
- else {
+ else
+ {
_errors = null;
_warnings = null;
}
}
- internal void ProcessMessagesAndThrow() {
+ internal void ProcessMessagesAndThrow()
+ {
ProcessMessagesAndThrow(false);
}
- internal void ProcessMessagesAndThrow(bool ignoreNonFatalMessages) {
- if (HasMessages) {
+ internal void ProcessMessagesAndThrow(bool ignoreNonFatalMessages)
+ {
+ if (HasMessages)
+ {
DispatchMessages(ignoreNonFatalMessages);
}
}
- internal enum UnexpectedEventType {
+ internal enum UnexpectedEventType
+ {
BatchCompleted,
ColumnInfoAvailable,
DefaultDatabaseChanged,
@@ -169,10 +208,12 @@ internal enum UnexpectedEventType {
}
- internal SmiEventSink_Default () {
+ internal SmiEventSink_Default()
+ {
}
- internal SmiEventSink_Default ( SmiEventSink parent ) {
+ internal SmiEventSink_Default(SmiEventSink parent)
+ {
_parent = parent;
}
@@ -185,144 +226,178 @@ internal SmiEventSink_Default ( SmiEventSink parent ) {
// Called at end of stream
- internal override void BatchCompleted( ) {
- if (null == _parent) {
+ internal override void BatchCompleted()
+ {
+ if (null == _parent)
+ {
throw SQL.UnexpectedSmiEvent(UnexpectedEventType.BatchCompleted);
}
_parent.BatchCompleted();
}
- internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 paramValues) {
- if (null == _parent) {
+ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 paramValues)
+ {
+ if (null == _parent)
+ {
throw SQL.UnexpectedSmiEvent(UnexpectedEventType.ParametersAvailable);
}
_parent.ParametersAvailable(metaData, paramValues);
}
- internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter paramValue, int ordinal) {
- if (null == _parent) {
+ internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter paramValue, int ordinal)
+ {
+ if (null == _parent)
+ {
throw SQL.UnexpectedSmiEvent(UnexpectedEventType.ParameterAvailable);
}
_parent.ParameterAvailable(metaData, paramValue, ordinal);
}
// Called when the server database context changes (ENVCHANGE token)
- internal override void DefaultDatabaseChanged( string databaseName ) {
- if (null == _parent) {
+ internal override void DefaultDatabaseChanged(string databaseName)
+ {
+ if (null == _parent)
+ {
throw SQL.UnexpectedSmiEvent(UnexpectedEventType.DefaultDatabaseChanged);
}
- _parent.DefaultDatabaseChanged( databaseName );
+ _parent.DefaultDatabaseChanged(databaseName);
}
// Called for messages and errors (ERROR and INFO tokens)
- internal override void MessagePosted ( int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber ) {
- if (null == _parent) {
- if (Bid.AdvancedOn) {
- Bid.Trace(" %d#, number=%d state=%d errorClass=%d server='%ls' message='%ls' procedure='%ls' linenumber=%d.\n",
+ internal override void MessagePosted(int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber)
+ {
+ if (null == _parent)
+ {
+ if (Bid.AdvancedOn)
+ {
+ Bid.Trace(" %d#, number=%d state=%d errorClass=%d server='%ls' message='%ls' procedure='%ls' linenumber=%d.\n",
0,
- number,
- state,
- errorClass,
- (null != server) ? server : "",
- (null != message) ? message : "",
- (null != procedure) ? procedure : "",
+ number,
+ state,
+ errorClass,
+ (null != server) ? server : "