Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,18 @@
//------------------------------------------------------------------------------
// <copyright file="ApplicationIntent.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">adoprov</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
/// <summary>
/// represents the application workload type when connecting to a server
/// </summary>
[Serializable]
public enum ApplicationIntent {
ReadWrite = 0,
ReadOnly = 1,
}
}

View File

@@ -0,0 +1,357 @@
//------------------------------------------------------------------------------
// <copyright file="LocalDB.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">antonam</owner>
//------------------------------------------------------------------------------
namespace System.Data
{
using System.Configuration;
using System.Threading;
using System.Runtime.InteropServices;
using System.Data.Common;
using System.Globalization;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
internal static class LocalDBAPI
{
const string const_localDbPrefix = @"(localdb)\";
const string const_partialTrustFlagKey = "ALLOW_LOCALDB_IN_PARTIAL_TRUST";
static PermissionSet _fullTrust = null;
static bool _partialTrustFlagChecked = false;
static bool _partialTrustAllowed = false;
// check if name is in format (localdb)\<InstanceName - not empty> and return instance name if it is
internal static string GetLocalDbInstanceNameFromServerName(string serverName)
{
if (serverName == null)
return null;
serverName = serverName.TrimStart(); // it can start with spaces if specified in quotes
if (!serverName.StartsWith(const_localDbPrefix, StringComparison.OrdinalIgnoreCase))
return null;
string instanceName = serverName.Substring(const_localDbPrefix.Length).Trim();
if (instanceName.Length == 0)
return null;
else
return instanceName;
}
internal static void ReleaseDLLHandles()
{
s_userInstanceDLLHandle = IntPtr.Zero;
s_localDBFormatMessage = null;
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 object s_dllLock = new object();
static IntPtr UserInstanceDLLHandle
{
get
{
if (s_userInstanceDLLHandle==IntPtr.Zero)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_dllLock, ref lockTaken);
if (s_userInstanceDLLHandle == IntPtr.Zero)
{
SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle);
if (s_userInstanceDLLHandle != IntPtr.Zero)
{
Bid.Trace("<sc.LocalDBAPI.UserInstanceDLLHandle> LocalDB - handle obtained");
}
else
{
SNINativeMethodWrapper.SNI_Error sniError = new SNINativeMethodWrapper.SNI_Error();
SNINativeMethodWrapper.SNIGetLastError(sniError);
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_FailedGetDLLHandle"), sniError: (int)sniError.sniError);
}
}
}
finally
{
if (lockTaken)
Monitor.Exit(s_dllLock);
}
}
return s_userInstanceDLLHandle;
}
}
[SuppressUnmanagedCodeSecurity]
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int LocalDBCreateInstanceDelegate([MarshalAs(UnmanagedType.LPWStr)] string version, [MarshalAs(UnmanagedType.LPWStr)] string instance, UInt32 flags);
static LocalDBCreateInstanceDelegate s_localDBCreateInstance = null;
static LocalDBCreateInstanceDelegate LocalDBCreateInstance
{
get
{
if (s_localDBCreateInstance==null)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_dllLock, ref lockTaken);
if (s_localDBCreateInstance == null)
{
IntPtr functionAddr = SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "LocalDBCreateInstance");
if (functionAddr == IntPtr.Zero)
{
int hResult=Marshal.GetLastWin32Error();
Bid.Trace("<sc.LocalDBAPI.LocalDBCreateInstance> GetProcAddress for LocalDBCreateInstance error 0x{%X}",hResult);
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_MethodNotFound"));
}
s_localDBCreateInstance = (LocalDBCreateInstanceDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBCreateInstanceDelegate));
}
}
finally
{
if (lockTaken)
Monitor.Exit(s_dllLock);
}
}
return s_localDBCreateInstance;
}
}
[SuppressUnmanagedCodeSecurity]
[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;
static LocalDBFormatMessageDelegate LocalDBFormatMessage
{
get
{
if (s_localDBFormatMessage==null)
{
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_dllLock, ref lockTaken);
if (s_localDBFormatMessage == null)
{
IntPtr functionAddr = SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "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();
Bid.Trace("<sc.LocalDBAPI.LocalDBFormatMessage> GetProcAddress for LocalDBFormatMessage error 0x{%X}", hResult);
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_MethodNotFound"));
}
s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate));
}
}
finally
{
if (lockTaken)
Monitor.Exit(s_dllLock);
}
}
return s_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");
try
{
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,
buffer: buffer, buflen: ref len);
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 */,
buffer: buffer, buflen: ref len);
if (hResult >= 0)
return buffer.ToString();
else
return string.Format(CultureInfo.CurrentCulture, "{0} (0x{1:X}).", Res.GetString("LocalDB_UnobtainableMessage"), hResult);
}
}
catch (SqlException exc)
{
return string.Format(CultureInfo.CurrentCulture, "{0} ({1}).", Res.GetString("LocalDB_UnobtainableMessage"), exc.Message);
}
}
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");
Debug.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty");
SqlErrorCollection collection = new SqlErrorCollection();
int errorCode = (localDbError == 0) ? sniError : localDbError;
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));
SqlException exc = SqlException.CreateException(collection, null);
exc._doNotReconnect = true;
return exc;
}
private class InstanceInfo
{
internal InstanceInfo(string version)
{
this.version = version;
this.created = false;
}
internal readonly string version;
internal bool created;
}
static object s_configLock=new object();
static Dictionary<string, InstanceInfo> s_configurableInstances = null;
internal static void DemandLocalDBPermissions()
{
if (!_partialTrustAllowed)
{
if (!_partialTrustFlagChecked)
{
object partialTrustFlagValue = AppDomain.CurrentDomain.GetData(const_partialTrustFlagKey);
if (partialTrustFlagValue != null && partialTrustFlagValue is bool)
{
_partialTrustAllowed = (bool)partialTrustFlagValue;
}
_partialTrustFlagChecked = true;
if (_partialTrustAllowed)
{
return;
}
}
if (_fullTrust == null)
{
_fullTrust = new NamedPermissionSet("FullTrust");
}
_fullTrust.Demand();
}
}
internal static void AssertLocalDBPermissions()
{
_partialTrustAllowed = true;
}
internal static void CreateLocalDBInstance(string instance)
{
DemandLocalDBPermissions();
if (s_configurableInstances == null)
{
// load list of instances from configuration, mark them as not created
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_configLock, ref lockTaken);
if (s_configurableInstances == null)
{
Dictionary<string, InstanceInfo> tempConfigurableInstances = new Dictionary<string, InstanceInfo>(StringComparer.OrdinalIgnoreCase);
object section = PrivilegedConfigurationManager.GetSection("system.data.localdb");
if (section != null) // if no section just skip creation
{
// validate section type
LocalDBConfigurationSection configSection = section as LocalDBConfigurationSection;
if (configSection == null)
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_BadConfigSectionType"));
foreach (LocalDBInstanceElement confElement in configSection.LocalDbInstances)
{
Debug.Assert(confElement.Name != null && confElement.Version != null, "Both name and version should not be null");
tempConfigurableInstances.Add(confElement.Name.Trim(), new InstanceInfo(confElement.Version.Trim()));
}
}
else
Bid.Trace( "<sc.LocalDBAPI.CreateLocalDBInstance> No system.data.localdb section found in configuration");
s_configurableInstances = tempConfigurableInstances;
}
}
finally
{
if (lockTaken)
Monitor.Exit(s_configLock);
}
}
InstanceInfo instanceInfo = null;
if (!s_configurableInstances.TryGetValue(instance,out instanceInfo))
return; // instance name was not in the config
if (instanceInfo.created)
return; // instance has already been created
Debug.Assert(!instance.Contains("\0"), "Instance name should contain embedded nulls");
if (instanceInfo.version.Contains("\0"))
throw CreateLocalDBException(errorMessage: Res.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("<sc.LocalDBAPI.CreateLocalDBInstance> Starting creation of instance %ls version %ls", instance, instanceInfo.version);
if (hr < 0)
throw CreateLocalDBException(errorMessage: Res.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr);
Bid.Trace("<sc.LocalDBAPI.CreateLocalDBInstance> Finished creation of instance %ls", instance);
instanceInfo.created=true; // mark instance as created
} // CreateLocalDbInstance
}
}

View File

@@ -0,0 +1,84 @@
//------------------------------------------------------------------------------
// <copyright file="LocalDB.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">antonam</owner>
//------------------------------------------------------------------------------
namespace System.Data
{
using System.Configuration;
using System.Collections;
internal sealed class LocalDBInstanceElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("version", IsRequired = true)]
public string Version
{
get
{
return this["version"] as string;
}
}
}
internal sealed class LocalDBInstancesCollection : ConfigurationElementCollection
{
private class TrimOrdinalIgnoreCaseStringComparer : IComparer
{
public int Compare(object x, object y)
{
string xStr = x as string;
if (xStr != null)
x = xStr.Trim();
string yStr = y as string;
if (yStr != null)
y = yStr.Trim();
return StringComparer.OrdinalIgnoreCase.Compare(x,y);
}
}
static readonly TrimOrdinalIgnoreCaseStringComparer s_comparer = new TrimOrdinalIgnoreCaseStringComparer();
internal LocalDBInstancesCollection()
: base(s_comparer)
{
}
protected override ConfigurationElement CreateNewElement()
{
return new LocalDBInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((LocalDBInstanceElement)element).Name;
}
}
internal sealed class LocalDBConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("localdbinstances", IsRequired = true)]
public LocalDBInstancesCollection LocalDbInstances
{
get
{
return (LocalDBInstancesCollection)this["localdbinstances"] ?? new LocalDBInstancesCollection();
}
}
}
}

View File

@@ -0,0 +1,17 @@
//------------------------------------------------------------------------------
// <copyright file="OnChangedEventHandler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.ComponentModel;
using System.Collections;
using System.Data;
public delegate void OnChangeEventHandler(object sender, SqlNotificationEventArgs e);
}

View File

@@ -0,0 +1,37 @@
//------------------------------------------------------------------------------
// <copyright file="ParameterPeekAheadValue.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
// 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
// to avoid long, complicated parameter lists that take every possible set of values.
// Instead, a single peekahead object is passed in, encapsulating whatever sets are needed.
//
// Example:
// When processing IEnumerable<SqlDataRecord>, we need to obtain the enumerator and
// the first record during metadata generation (metadata is stored in the first record),
// 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 {
// Peekahead for IEnumerable<SqlDataRecord>
internal IEnumerator<SqlDataRecord> Enumerator;
internal SqlDataRecord FirstRecord;
}
}

View File

@@ -0,0 +1,35 @@
//------------------------------------------------------------------------------
// <copyright file="RowsCopiedEvent.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
public class SqlRowsCopiedEventArgs : System.EventArgs {
private bool _abort;
private long _rowsCopied;
public SqlRowsCopiedEventArgs (long rowsCopied) {
_rowsCopied = rowsCopied;
}
public bool Abort {
get {
return _abort;
}
set {
_abort = value;
}
}
public long RowsCopied {
get {
return _rowsCopied;
}
}
}
}

View File

@@ -0,0 +1,12 @@
//------------------------------------------------------------------------------
// <copyright file="RowsCopiedEventHandler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
public delegate void SqlRowsCopiedEventHandler(object sender, SqlRowsCopiedEventArgs e);
}

View File

@@ -0,0 +1,18 @@
//------------------------------------------------------------------------------
// <copyright file="SqlMetaData.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
public enum SortOrder {
Unspecified = -1,
Ascending = 0,
Descending = 1
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
91812a7b96c2d1123b38454b099aa1892ab0a3c5

View File

@@ -0,0 +1,119 @@
//------------------------------------------------------------------------------
// <copyright file="SqlBulkCopyColumnMapping.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
// Todo: rename the file
// Caution! ndp\fx\src\data\netmodule\sources needs to follow this change
namespace System.Data.SqlClient
{
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
// -------------------------------------------------------------------------------------------------
// this class helps allows the user to create association between source- and targetcolumns
//
//
public sealed class SqlBulkCopyColumnMapping {
internal string _destinationColumnName;
internal int _destinationColumnOrdinal;
internal string _sourceColumnName;
internal int _sourceColumnOrdinal;
// devnote: we don't want the user to detect the columnordinal after WriteToServer call.
// _sourceColumnOrdinal(s) will be copied to _internalSourceColumnOrdinal when WriteToServer executes.
internal int _internalDestinationColumnOrdinal;
internal int _internalSourceColumnOrdinal; // -1 indicates an undetermined value
public string DestinationColumn {
get {
if (_destinationColumnName != null) {
return _destinationColumnName;
}
return string.Empty;
}
set {
_destinationColumnOrdinal = _internalDestinationColumnOrdinal = -1;
_destinationColumnName = value;
}
}
public int DestinationOrdinal {
get {
return _destinationColumnOrdinal;
}
set {
if (value >= 0) {
_destinationColumnName = null;
_destinationColumnOrdinal = _internalDestinationColumnOrdinal = value;
}
else {
throw ADP.IndexOutOfRange(value);
}
}
}
public string SourceColumn {
get {
if (_sourceColumnName != null) {
return _sourceColumnName;
}
return string.Empty;
}
set {
_sourceColumnOrdinal = _internalSourceColumnOrdinal = -1;
_sourceColumnName = value;
}
}
public int SourceOrdinal {
get {
return _sourceColumnOrdinal;
}
set {
if (value >= 0) {
_sourceColumnName = null;
_sourceColumnOrdinal = _internalSourceColumnOrdinal = value;
}
else {
throw ADP.IndexOutOfRange(value);
}
}
}
public SqlBulkCopyColumnMapping () {
_internalSourceColumnOrdinal = -1;
}
public SqlBulkCopyColumnMapping (string sourceColumn, string destinationColumn) {
SourceColumn = sourceColumn;
DestinationColumn = destinationColumn;
}
public SqlBulkCopyColumnMapping (int sourceColumnOrdinal, string destinationColumn) {
SourceOrdinal = sourceColumnOrdinal;
DestinationColumn = destinationColumn;
}
public SqlBulkCopyColumnMapping (string sourceColumn, int destinationOrdinal) {
SourceColumn = sourceColumn;
DestinationOrdinal = destinationOrdinal;
}
public SqlBulkCopyColumnMapping (int sourceColumnOrdinal, int destinationOrdinal) {
SourceOrdinal = sourceColumnOrdinal;
DestinationOrdinal = destinationOrdinal;
}
}
}

View File

@@ -0,0 +1,164 @@
//------------------------------------------------------------------------------
// <copyright file="SqlBulkCopyMappingCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
// todo: rename the file
// Caution! ndp\fx\src\data\netmodule\sources needs to follow this name change
namespace System.Data.SqlClient
{
using System;
using System.Data;
using System.Data.Common;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
public sealed class SqlBulkCopyColumnMappingCollection : CollectionBase {
private enum MappingSchema {
Undefined = 0,
NamesNames = 1,
NemesOrdinals = 2,
OrdinalsNames = 3,
OrdinalsOrdinals = 4,
}
private bool _readOnly;
private MappingSchema _mappingSchema = MappingSchema.Undefined;
internal SqlBulkCopyColumnMappingCollection() {
}
public SqlBulkCopyColumnMapping this [int index] {
get {
return (SqlBulkCopyColumnMapping)this.List[index];
}
}
internal bool ReadOnly {
get {
return _readOnly;
}
set {
_readOnly = value;
}
}
public SqlBulkCopyColumnMapping Add(SqlBulkCopyColumnMapping bulkCopyColumnMapping) {
AssertWriteAccess();
Debug.Assert(ADP.IsEmpty(bulkCopyColumnMapping.SourceColumn) || bulkCopyColumnMapping._internalSourceColumnOrdinal == -1, "BulkLoadAmbigousSourceColumn");
if (((ADP.IsEmpty(bulkCopyColumnMapping.SourceColumn)) && (bulkCopyColumnMapping.SourceOrdinal == -1))
|| ((ADP.IsEmpty(bulkCopyColumnMapping.DestinationColumn))&&(bulkCopyColumnMapping.DestinationOrdinal == -1))) {
throw SQL.BulkLoadNonMatchingColumnMapping();
}
InnerList.Add(bulkCopyColumnMapping);
return bulkCopyColumnMapping;
}
public SqlBulkCopyColumnMapping Add(string sourceColumn, string destinationColumn) {
AssertWriteAccess();
SqlBulkCopyColumnMapping column = new SqlBulkCopyColumnMapping (sourceColumn, destinationColumn);
return Add(column);
}
public SqlBulkCopyColumnMapping Add(int sourceColumnIndex, string destinationColumn) {
AssertWriteAccess();
SqlBulkCopyColumnMapping column = new SqlBulkCopyColumnMapping (sourceColumnIndex, destinationColumn);
return Add(column);
}
public SqlBulkCopyColumnMapping Add(string sourceColumn, int destinationColumnIndex) {
AssertWriteAccess();
SqlBulkCopyColumnMapping column = new SqlBulkCopyColumnMapping (sourceColumn, destinationColumnIndex);
return Add(column);
}
public SqlBulkCopyColumnMapping Add(int sourceColumnIndex, int destinationColumnIndex) {
AssertWriteAccess();
SqlBulkCopyColumnMapping column = new SqlBulkCopyColumnMapping (sourceColumnIndex, destinationColumnIndex);
return Add(column);
}
private void AssertWriteAccess () {
if (ReadOnly) {
throw SQL.BulkLoadMappingInaccessible();
}
}
new public void Clear() {
AssertWriteAccess();
base.Clear();
}
public bool Contains(SqlBulkCopyColumnMapping value) {
return (-1 != InnerList.IndexOf(value));
}
public void CopyTo(SqlBulkCopyColumnMapping[] array, int index) {
InnerList.CopyTo(array, index);
}
internal void CreateDefaultMapping (int columnCount) {
for (int i=0; i<columnCount; i++) {
InnerList.Add(new SqlBulkCopyColumnMapping (i,i));
}
}
public int IndexOf(SqlBulkCopyColumnMapping value) {
return InnerList.IndexOf(value);
}
public void Insert(int index, SqlBulkCopyColumnMapping value) {
AssertWriteAccess();
InnerList.Insert(index, value);
}
public void Remove(SqlBulkCopyColumnMapping value) {
AssertWriteAccess();
InnerList.Remove(value);
}
new public void RemoveAt(int index) {
AssertWriteAccess();
base.RemoveAt(index);
}
internal void ValidateCollection () {
MappingSchema mappingSchema;
foreach (SqlBulkCopyColumnMapping a in this) {
if (a.SourceOrdinal != -1) {
if(a.DestinationOrdinal != -1) {
mappingSchema = MappingSchema.OrdinalsOrdinals;
}
else {
mappingSchema = MappingSchema.OrdinalsNames;
}
}
else {
if(a.DestinationOrdinal != -1) {
mappingSchema = MappingSchema.NemesOrdinals;
}
else {
mappingSchema = MappingSchema.NamesNames;
}
}
if (_mappingSchema == MappingSchema.Undefined) {
_mappingSchema = mappingSchema;
}
else {
if (_mappingSchema != mappingSchema) {
throw SQL.BulkLoadMappingsNamesOrOrdinalsOnly();
}
}
}
}
}
}

View File

@@ -0,0 +1,25 @@
//------------------------------------------------------------------------------
// <copyright file="SqlBulkCopyOptions.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
[Flags]
public enum SqlBulkCopyOptions {
Default = 0,
KeepIdentity = 1 << 0,
CheckConstraints = 1 << 1,
TableLock = 1 << 2,
KeepNulls = 1 << 3,
FireTriggers = 1 << 4,
UseInternalTransaction = 1 << 5,
}
}

View File

@@ -0,0 +1,156 @@
//------------------------------------------------------------------------------
// <copyright file="SqlCachedBuffer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
using System.Data.SqlTypes;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.CompilerServices;
// Caches the bytes returned from partial length prefixed datatypes, like XML
sealed internal class SqlCachedBuffer : System.Data.SqlTypes.INullable{
public static readonly SqlCachedBuffer Null = new SqlCachedBuffer();
private const int _maxChunkSize = 2048; // Arbitrary value for chunk size. Revisit this later for better perf
private List<byte[]> _cachedBytes;
private SqlCachedBuffer() {
// For constructing Null
}
private SqlCachedBuffer(List<byte[]> cachedBytes) {
_cachedBytes = cachedBytes;
}
internal List<byte[]> CachedBytes {
get { return _cachedBytes; }
}
// Reads off from the network buffer and caches bytes. Only reads one column value in the current row.
static internal bool TryCreate(SqlMetaDataPriv metadata, TdsParser parser, TdsParserStateObject stateObj, out SqlCachedBuffer buffer) {
int cb = 0;
ulong plplength;
byte[] byteArr;
List<byte[]> cachedBytes = new List<byte[]>();
buffer = null;
// the very first length is already read.
if (!parser.TryPlpBytesLeft(stateObj, out plplength)) {
return false;
}
// For now we only handle Plp data from the parser directly.
Debug.Assert(metadata.metaType.IsPlp, "SqlCachedBuffer call on a non-plp data");
do {
if (plplength == 0)
break;
do {
cb = (plplength > (ulong) _maxChunkSize) ? _maxChunkSize : (int)plplength ;
byteArr = new byte[cb];
if (!stateObj.TryReadPlpBytes(ref byteArr, 0, cb, out cb)) {
return false;
}
Debug.Assert(cb == byteArr.Length);
if (cachedBytes.Count == 0) {
// Add the Byte order mark if needed if we read the first array
AddByteOrderMark(byteArr, cachedBytes);
}
cachedBytes.Add(byteArr);
plplength -= (ulong)cb;
} while (plplength > 0);
if (!parser.TryPlpBytesLeft(stateObj, out plplength)) {
return false;
}
} while (plplength > 0);
Debug.Assert(stateObj._longlen == 0 && stateObj._longlenleft == 0);
buffer = new SqlCachedBuffer(cachedBytes);
return true;
}
private static void AddByteOrderMark(byte[] byteArr, List<byte[]> cachedBytes) {
// Need to find out if we should add byte order mark or not.
// We need to add this if we are getting ntext xml, not if we are getting binary xml
// Binary Xml always begins with the bytes 0xDF and 0xFF
// If we aren't getting these, then we are getting unicode xml
if ((byteArr.Length < 2 ) || (byteArr[0] != 0xDF) || (byteArr[1] != 0xFF)){
Debug.Assert(cachedBytes.Count == 0);
cachedBytes.Add(TdsEnums.XMLUNICODEBOMBYTES);
}
}
internal Stream ToStream() {
return new SqlCachedStream(this);
}
override public string ToString() {
if (IsNull)
throw new SqlNullValueException();
if (_cachedBytes.Count == 0) {
return String.Empty;
}
SqlXml sxml = new SqlXml(ToStream());
return sxml.Value;
}
internal SqlString ToSqlString() {
if (IsNull)
return SqlString.Null;
string str = ToString();
return new SqlString(str);
}
internal SqlXml ToSqlXml() {
SqlXml sx = new SqlXml(ToStream());
return sx;
}
// Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
[MethodImpl(MethodImplOptions.NoInlining)]
internal XmlReader ToXmlReader() {
//XmlTextReader xr = new XmlTextReader(fragment, XmlNodeType.Element, null);
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
// Call internal XmlReader.CreateSqlReader from System.Xml.
// Signature: internal static XmlReader CreateSqlReader(Stream input, XmlReaderSettings settings, XmlParserContext inputContext);
MethodInfo createSqlReaderMethodInfo = typeof(System.Xml.XmlReader).GetMethod("CreateSqlReader", BindingFlags.Static | BindingFlags.NonPublic);
object[] args = new object[3] { ToStream(), readerSettings, null };
XmlReader xr;
new System.Security.Permissions.ReflectionPermission(System.Security.Permissions.ReflectionPermissionFlag.MemberAccess).Assert();
try {
xr = (XmlReader)createSqlReaderMethodInfo.Invoke(null, args);
}
finally {
System.Security.Permissions.ReflectionPermission.RevertAssert();
}
return xr;
}
public bool IsNull {
get {
return (_cachedBytes == null) ? true : false ;
}
}
}
}

View File

@@ -0,0 +1,77 @@
//------------------------------------------------------------------------------
// <copyright file="SqlClientFactory.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Security;
using System.Security.Permissions;
namespace System.Data.SqlClient {
public sealed class SqlClientFactory : DbProviderFactory, IServiceProvider {
public static readonly SqlClientFactory Instance = new SqlClientFactory();
private SqlClientFactory() {
}
public override bool CanCreateDataSourceEnumerator {
get {
return true;
}
}
public override DbCommand CreateCommand() {
return new SqlCommand();
}
public override DbCommandBuilder CreateCommandBuilder() {
return new SqlCommandBuilder();
}
public override DbConnection CreateConnection() {
return new SqlConnection();
}
public override DbConnectionStringBuilder CreateConnectionStringBuilder() {
return new SqlConnectionStringBuilder();
}
public override DbDataAdapter CreateDataAdapter() {
return new SqlDataAdapter();
}
public override DbParameter CreateParameter() {
return new SqlParameter();
}
public override CodeAccessPermission CreatePermission(PermissionState state) {
return new SqlClientPermission(state);
}
public override DbDataSourceEnumerator CreateDataSourceEnumerator() {
return SqlDataSourceEnumerator.Instance;
}
/// <summary>
/// Extension mechanism for additional services; currently the only service
/// supported is the DbProviderServices
/// </summary>
/// <returns>requested service provider or null.</returns>
object IServiceProvider.GetService(Type serviceType) {
object result = null;
if (serviceType == GreenMethods.SystemDataCommonDbProviderServices_Type) {
result = GreenMethods.SystemDataSqlClientSqlProviderServices_Instance();
}
return result;
}
}
}

View File

@@ -0,0 +1,29 @@
//------------------------------------------------------------------------------
// <copyright file="SqlClientMetaDataCollectionNames.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient{
public static class SqlClientMetaDataCollectionNames {
public static readonly string Columns = "Columns";
public static readonly string Databases = "Databases";
public static readonly string ForeignKeys = "ForeignKeys";
public static readonly string IndexColumns = "IndexColumns";
public static readonly string Indexes = "Indexes";
public static readonly string Parameters = "Parameters";
public static readonly string ProcedureColumns = "ProcedureColumns";
public static readonly string Procedures = "Procedures";
public static readonly string Tables = "Tables";
public static readonly string UserDefinedTypes = "UserDefinedTypes";
public static readonly string Users = "Users";
public static readonly string ViewColumns = "ViewColumns";
public static readonly string Views = "Views";
}
}

View File

@@ -0,0 +1,65 @@
//------------------------------------------------------------------------------
// <copyright file="SqlClientPermission.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System.Collections;
using System.Data.Common;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
[Serializable]
public sealed class SqlClientPermission : DBDataPermission {
[ Obsolete("SqlClientPermission() has been deprecated. Use the SqlClientPermission(PermissionState.None) constructor. http://go.microsoft.com/fwlink/?linkid=14202", true) ] // MDAC 86034
public SqlClientPermission() : this(PermissionState.None) {
}
public SqlClientPermission(PermissionState state) : base(state) {
}
[ Obsolete("SqlClientPermission(PermissionState state, Boolean allowBlankPassword) has been deprecated. Use the SqlClientPermission(PermissionState.None) constructor. http://go.microsoft.com/fwlink/?linkid=14202", true) ] // MDAC 86034
public SqlClientPermission(PermissionState state, bool allowBlankPassword) : this(state) {
AllowBlankPassword = allowBlankPassword;
}
private SqlClientPermission(SqlClientPermission permission) : base(permission) { // for Copy
}
internal SqlClientPermission(SqlClientPermissionAttribute permissionAttribute) : base(permissionAttribute) { // for CreatePermission
}
internal SqlClientPermission(SqlConnectionString constr) : base(constr) { // for Open
if ((null == constr) || constr.IsEmpty) {
base.Add(ADP.StrEmpty, ADP.StrEmpty, KeyRestrictionBehavior.AllowOnly);
}
}
public override void Add(string connectionString, string restrictions, KeyRestrictionBehavior behavior) {
DBConnectionString constr = new DBConnectionString(connectionString, restrictions, behavior, SqlConnectionString.GetParseSynonyms(), false);
AddPermissionEntry(constr);
}
override public IPermission Copy () {
return new SqlClientPermission(this);
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
[Serializable]
public sealed class SqlClientPermissionAttribute : DBDataPermissionAttribute {
public SqlClientPermissionAttribute(SecurityAction action) : base(action) {
}
override public IPermission CreatePermission() {
return new SqlClientPermission(this);
}
}
}

View File

@@ -0,0 +1,97 @@
//------------------------------------------------------------------------------
// <copyright file="SqlClientWrapperSmiStream.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace Microsoft.SqlServer.Server {
using System;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
// Simple wrapper over SmiStream that handles server events on the SqlClient side of Smi
internal class SqlClientWrapperSmiStream : Stream {
private SmiEventSink_Default _sink;
private SmiStream _stream;
internal SqlClientWrapperSmiStream( SmiEventSink_Default sink, SmiStream stream ) {
Debug.Assert( null != sink );
Debug.Assert( null != stream );
_sink = sink;
_stream = stream;
}
public override bool CanRead {
get {
return _stream.CanRead;
}
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public override bool CanSeek {
get {
return _stream.CanSeek;
}
}
public override bool CanWrite {
get {
return _stream.CanWrite;
}
}
public override long Length {
get {
long length = _stream.GetLength( _sink );
_sink.ProcessMessagesAndThrow();
return length;
}
}
public override long Position {
get {
long position = _stream.GetPosition( _sink );
_sink.ProcessMessagesAndThrow();
return position;
}
set {
_stream.SetPosition( _sink, value );
_sink.ProcessMessagesAndThrow();
}
}
public override void Flush() {
_stream.Flush( _sink );
_sink.ProcessMessagesAndThrow();
}
public override long Seek(long offset, SeekOrigin origin) {
long result = _stream.Seek( _sink, offset, origin );
_sink.ProcessMessagesAndThrow();
return result;
}
public override void SetLength(long value) {
_stream.SetLength( _sink, value );
_sink.ProcessMessagesAndThrow();
}
public override int Read(byte[] buffer, int offset, int count) {
int bytesRead = _stream.Read( _sink, buffer, offset, count );
_sink.ProcessMessagesAndThrow();
return bytesRead;
}
public override void Write(byte[] buffer, int offset, int count) {
_stream.Write( _sink, buffer, offset, count );
_sink.ProcessMessagesAndThrow();
}
}
}

View File

@@ -0,0 +1,128 @@
//------------------------------------------------------------------------------
// <copyright file="SqlClientWrapperSmiStream.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace Microsoft.SqlServer.Server {
using System;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
// Simple SqlStreamChars wrapper over SmiStream that handles server events on the
// SqlClient side of Smi
internal class SqlClientWrapperSmiStreamChars : SqlStreamChars {
private SmiEventSink_Default _sink;
private SmiStream _stream;
internal SqlClientWrapperSmiStreamChars( SmiEventSink_Default sink, SmiStream stream ) {
Debug.Assert( null != sink );
Debug.Assert( null != stream );
_sink = sink;
_stream = stream;
}
public override bool IsNull {
get {
return null == _stream;
}
}
public override bool CanRead {
get {
return _stream.CanRead;
}
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public override bool CanSeek {
get {
return _stream.CanSeek;
}
}
public override bool CanWrite {
get {
return _stream.CanWrite;
}
}
public override long Length {
get {
long length = _stream.GetLength( _sink );
_sink.ProcessMessagesAndThrow();
if ( length > 0 )
return length / sizeof( char );
else
return length;
}
}
public override long Position {
get {
long position = _stream.GetPosition( _sink ) / sizeof( char );
_sink.ProcessMessagesAndThrow();
return position;
}
set {
if ( value < 0 ) {
throw ADP.ArgumentOutOfRange("Position");
}
_stream.SetPosition( _sink, value * sizeof( char ) );
_sink.ProcessMessagesAndThrow();
}
}
public override void Flush() {
_stream.Flush( _sink );
_sink.ProcessMessagesAndThrow();
}
public override long Seek(long offset, SeekOrigin origin) {
long result = _stream.Seek( _sink, offset * sizeof( char ), origin );
_sink.ProcessMessagesAndThrow();
return result;
}
public override void SetLength(long value) {
if ( value < 0 ) {
throw ADP.ArgumentOutOfRange("value");
}
_stream.SetLength( _sink, value * sizeof( char ) );
_sink.ProcessMessagesAndThrow();
}
public override int Read(char[] buffer, int offset, int count) {
int bytesRead = _stream.Read( _sink, buffer, offset * sizeof( char ), count );
_sink.ProcessMessagesAndThrow();
return bytesRead;
}
public override void Write(char[] buffer, int offset, int count) {
_stream.Write( _sink, buffer, offset, count );
_sink.ProcessMessagesAndThrow();
}
// Convenience methods to allow simple pulling/pushing of raw bytes
internal int Read(byte[] buffer, int offset, int count) {
int bytesRead = _stream.Read( _sink, buffer, offset, count );
_sink.ProcessMessagesAndThrow();
return bytesRead;
}
internal void Write(byte[] buffer, int offset, int count) {
_stream.Write( _sink, buffer, offset, count );
_sink.ProcessMessagesAndThrow();
}
}
}

View File

@@ -0,0 +1 @@
3079ff01518b29dae0a29e6e9b2b0d9efaeaa68e

Some files were not shown because too many files have changed in this diff Show More