Exemple #1
0
        static private string GetFullPathInternal(string path)
        {
            //-----------------------------------------------------------------
            // precondition validation should be validated by callers of this method
            // NOTE: if this method moves elsewhere, this assert should become an actual runtime check
            // as the implicit assumptions here cannot be relied upon in an inter-class context
            Debug.Assert(path != null);

            // remove leading and trailing whitespace
            path = path.Trim();
            if (path.Length == 0)
            {
                throw ADP.Argument(StringsHelper.GetString(Strings.SqlFileStream_InvalidPath), "path");
            }

            // make sure path is not DOS device path
            if (!path.StartsWith(@"\\") && !System.IO.PathInternal.IsDevice(path.AsSpan()))
            {
                throw ADP.Argument(StringsHelper.GetString(Strings.SqlFileStream_InvalidPath), "path");
            }

            // normalize the path
            path = System.IO.Path.GetFullPath(path);

            // make sure path is a UNC path
            if (System.IO.PathInternal.IsDeviceUNC(path.AsSpan()))
            {
                throw ADP.Argument(StringsHelper.GetString(Strings.SqlFileStream_PathNotValidDiskResource), "path");
            }

            return(path);
        }
Exemple #2
0
        private static bool ApplySwitchValues(string[] switches)
        {
            string methodName = MethodBase.GetCurrentMethod().Name;

            SqlClientEventSource.Log.TryTraceEvent("<sc.{0}.{1}|INFO> Entry point.", TypeName, methodName);

            if (switches == null || switches.Length == 0 || switches.Length % 2 == 1)
            {
                return(false);
            }

            for (int i = 0; i < switches.Length / 2; i++)
            {
                try
                {
                    AppContext.SetSwitch(switches[i], Convert.ToBoolean(switches[i + 1]));
                    SqlClientEventSource.Log.TryTraceEvent("<sc.{0}.{1}|INFO> Successfully assigned the AppContext switch '{2}'={3}.",
                                                           TypeName, methodName, switches[i], switches[i + 1]);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(StringsHelper.GetString(Strings.SqlAppContextSwitchManager_InvalidValue, switches[i], switches[i + 1]), e);
                }
            }
            SqlClientEventSource.Log.TryTraceEvent("<sc.{0}.{1}|INFO> Exit point.", TypeName, methodName);
            return(true);
        }
Exemple #3
0
        internal static InvalidUdtException Create(Type udtType, string resourceReason)
        {
            string reason         = StringsHelper.GetString(resourceReason);
            string message        = StringsHelper.GetString(Strings.SqlUdt_InvalidUdtMessage, udtType.FullName, reason);
            InvalidUdtException e = new InvalidUdtException(message);

            ADP.TraceExceptionAsReturnValue(e);
            return(e);
        }
Exemple #4
0
        private async Task RestoreDefaults()
        {
            var result = await _dialogService.ShowMessageDialogAsnyc(StringsHelper.GetString("PleaseConfirm"), StringsHelper.GetString("ConfirmRestoreKeybindings"), DialogButton.OK, DialogButton.Cancel).ConfigureAwait(true);

            if (result == DialogButton.OK)
            {
                _settingsService.ResetKeyBindings();
                Initialize(_settingsService.GetCommandKeyBindings());
            }
        }
Exemple #5
0
        static private string GetFullPathInternal(string path)
        {
            //-----------------------------------------------------------------
            // precondition validation

            // should be validated by callers of this method
            // NOTE: if this method moves elsewhere, this assert should become an actual runtime check
            //   as the implicit assumptions here cannot be relied upon in an inter-class context
            Debug.Assert(path != null);

            // remove leading and trailing whitespace
            path = path.Trim();
            if (path.Length == 0)
            {
                throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path");
            }

            // check for the path length before we normalize it with GetFullPathName
            if (path.Length > MaxWin32PathLength)
            {
                // cannot use PathTooLongException here since our length limit is 32K while
                // PathTooLongException error message states that the path should be limited to 260
                throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path");
            }

            // GetFullPathName does not check for invalid characters so we still have to validate them before
            if (path.IndexOfAny(InvalidPathChars) >= 0)
            {
                throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path");
            }

            // make sure path is a UNC path
            if (!path.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase))
            {
                throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path");
            }

            //-----------------------------------------------------------------

            // normalize the path
            path = UnsafeNativeMethods.SafeGetFullPathName(path);

            // we do not expect windows API to return invalid paths
            Debug.Assert(path.Length <= MaxWin32PathLength, "GetFullPathName returns path longer than max expected!");

            // CONSIDER: is this a precondition validation that can be done above? Or must the path be normalized first?
            // after normalization, we have to ensure that the path does not attempt to refer to a root device, etc.
            if (path.StartsWith(@"\\.\", StringComparison.Ordinal))
            {
                throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_PathNotValidDiskResource), "path");
            }

            return(path);
        }
Exemple #6
0
        internal static string SafeGetFullPathName(string path)
        {
            Debug.Assert(path != null, "path is null?");
            // make sure to test for Int16.MaxValue limit before calling this method
            // see the below comment re GetLastWin32Error for the reason
            Debug.Assert(path.Length < Int16.MaxValue);

            // since we expect network paths, the 'full path' is expected to be the same size
            // as the provided one. we still need to allocate +1 for null termination
            StringBuilder buffer = new StringBuilder(path.Length + 1);

            int cchRequiredSize = GetFullPathName(path, buffer.Capacity, buffer, IntPtr.Zero);

            // if our buffer was smaller than required, GetFullPathName will succeed and return us the required buffer size with null
            if (cchRequiredSize > buffer.Capacity)
            {
                // we have to reallocate and retry
                buffer.Capacity = cchRequiredSize;
                cchRequiredSize = GetFullPathName(path, buffer.Capacity, buffer, IntPtr.Zero);
            }

            if (cchRequiredSize == 0)
            {
                // GetFullPathName call failed
                int lastError = Marshal.GetLastWin32Error();
                if (lastError == 0)
                {
                    // we found that in some cases GetFullPathName fail but does not set the last error value
                    // for example, it happens when the path provided to it is longer than 32K: return value is 0 (failure)
                    // but GetLastError was zero too so we raised Win32Exception saying "The operation completed successfully".
                    // To raise proper "path too long" failure, check the length before calling this API.
                    // For other (yet unknown cases), we will throw InvalidPath message since we do not know what exactly happened
                    throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path");
                }
                else
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(lastError);
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }
            }

            // this should not happen since we already reallocate
            Debug.Assert(cchRequiredSize <= buffer.Capacity, string.Format(
                             System.Globalization.CultureInfo.InvariantCulture,
                             "second call to GetFullPathName returned greater size: {0} > {1}",
                             cchRequiredSize,
                             buffer.Capacity));

            return(buffer.ToString());
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter is KeyBindingsPageViewModel viewModel)
            {
                ViewModel = viewModel;

                // Add the commands corresponding to all of the application's static commands
                foreach (var value in Enum.GetValues(typeof(Command)))
                {
                    Command command = (Command)value;
                    AddCommandMenu.Items.Add(new MenuFlyoutItem
                    {
                        Text             = StringsHelper.GetString(EnumHelper.GetEnumDescription(command)),
                        Command          = ViewModel.AddCommand,
                        CommandParameter = command.ToString()
                    });
                }
            }
        }
Exemple #8
0
        public XtermTerminalView()
        {
            InitializeComponent();
            StartMediatorTask();

            _webView = new WebView(WebViewExecutionMode.SeparateThread)
            {
                DefaultBackgroundColor = Colors.Transparent
            };
            Root.Children.Add(_webView);

            _webView.NavigationCompleted += _webView_NavigationCompleted;
            _webView.NavigationStarting  += _webView_NavigationStarting;

            _copyMenuItem = new MenuFlyoutItem {
                Text = StringsHelper.GetString("Copy")
            };
            _copyMenuItem.Click += Copy_Click;

            _pasteMenuItem = new MenuFlyoutItem {
                Text = StringsHelper.GetString("Paste")
            };
            _pasteMenuItem.Click += Paste_Click;

            _webView.ContextFlyout = new MenuFlyout
            {
                Items = { _copyMenuItem, _pasteMenuItem }
            };

            _optionsChanged = new DebouncedAction <TerminalOptions>(Dispatcher, TimeSpan.FromMilliseconds(800), async options =>
            {
                var serialized = JsonConvert.SerializeObject(options);
                await ExecuteScriptAsync($"changeOptions('{serialized}')");
            });

            _navigationCompleted = new SemaphoreSlim(0, 1);
            _connectedEvent      = new ManualResetEventSlim(false);

            _webView.Navigate(new Uri("ms-appx-web:///Client/index.html"));
        }
Exemple #9
0
 internal static Normalizer GetNormalizer(Type t)
 {
     Normalizer n = null;
     if (t.IsPrimitive)
     {
         if (t == typeof(byte))
             n = new ByteNormalizer();
         else if (t == typeof(sbyte))
             n = new SByteNormalizer();
         else if (t == typeof(bool))
             n = new BooleanNormalizer();
         else if (t == typeof(short))
             n = new ShortNormalizer();
         else if (t == typeof(ushort))
             n = new UShortNormalizer();
         else if (t == typeof(int))
             n = new IntNormalizer();
         else if (t == typeof(uint))
             n = new UIntNormalizer();
         else if (t == typeof(float))
             n = new FloatNormalizer();
         else if (t == typeof(double))
             n = new DoubleNormalizer();
         else if (t == typeof(long))
             n = new LongNormalizer();
         else if (t == typeof(ulong))
             n = new ULongNormalizer();
     }
     else if (t.IsValueType)
     {
         n = new BinaryOrderedUdtNormalizer(t, false);
     }
     if (n == null)
         throw new Exception(StringsHelper.GetString(Strings.SQL_CannotCreateNormalizer, t.FullName));
     n._skipNormalize = false;
     return n;
 }
        public SettingsPage()
        {
            InitializeComponent();
            Root.DataContext = this;
            var asd = StringsHelper.GetString("Setting");

            ApplicationView.GetForCurrentView().Title = StringsHelper.GetString("Setting");

            CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;

            coreTitleBar.LayoutMetricsChanged += TitleBar_LayoutMetricsChanged;
            CoreTitleBarHeight = coreTitleBar.Height;

            _titleBar   = ApplicationView.GetForCurrentView().TitleBar;
            _dispatcher = Window.Current.Dispatcher;

            SetTitleBarColors();

            _uiSettings = new UISettings();
            _uiSettings.ColorValuesChanged += OnColorValuesChanged;
            SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += SettingsPage_CloseRequested;

            hiddenNavigationItem = new NavigationViewItem();
        }
Exemple #11
0
 private void DontDoIt()
 {
     throw new Exception(StringsHelper.GetString(Strings.Sql_InternalError));
 }
Exemple #12
0
        private unsafe void OpenSqlFileStream
        (
            string sPath,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            long allocationSize
        )
        {
            //-----------------------------------------------------------------
            // precondition validation
            // these should be checked by any caller of this method
            // ensure we have validated and normalized the path before
            Debug.Assert(sPath != null);
            Debug.Assert(transactionContext != null);

            if (access != System.IO.FileAccess.Read && access != System.IO.FileAccess.Write && access != System.IO.FileAccess.ReadWrite)
            {
                throw ADP.ArgumentOutOfRange("access");
            }

            // FileOptions is a set of flags, so AND the given value against the set of values we do not support
            if ((options & ~(System.IO.FileOptions.WriteThrough | System.IO.FileOptions.Asynchronous | System.IO.FileOptions.RandomAccess | System.IO.FileOptions.SequentialScan)) != 0)
            {
                throw ADP.ArgumentOutOfRange("options");
            }

            //-----------------------------------------------------------------
            // normalize the provided path
            // * compress path to remove any occurrences of '.' or '..'
            // * trim whitespace from the beginning and end of the path
            // * ensure that the path starts with '\\'
            // * ensure that the path does not start with '\\.\'
            sPath = GetFullPathInternal(sPath);

            Microsoft.Win32.SafeHandles.SafeFileHandle hFile    = null;
            Interop.NtDll.DesiredAccess     nDesiredAccess      = Interop.NtDll.DesiredAccess.FILE_READ_ATTRIBUTES | Interop.NtDll.DesiredAccess.SYNCHRONIZE;
            Interop.NtDll.CreateOptions     dwCreateOptions     = 0;
            Interop.NtDll.CreateDisposition dwCreateDisposition = 0;
            System.IO.FileShare             nShareAccess        = System.IO.FileShare.None;

            switch (access)
            {
            case System.IO.FileAccess.Read:

                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_READ_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OPEN;
                break;

            case System.IO.FileAccess.Write:
                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
                break;

            case System.IO.FileAccess.ReadWrite:
            default:
                // we validate the value of 'access' parameter in the beginning of this method
                Debug.Assert(access == System.IO.FileAccess.ReadWrite);

                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_READ_DATA | Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
                break;
            }

            if ((options & System.IO.FileOptions.WriteThrough) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_WRITE_THROUGH;
            }

            if ((options & System.IO.FileOptions.Asynchronous) == 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT;
            }

            if ((options & System.IO.FileOptions.SequentialScan) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SEQUENTIAL_ONLY;
            }

            if ((options & System.IO.FileOptions.RandomAccess) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_RANDOM_ACCESS;
            }

            try
            {
                // NOTE: the Name property is intended to reveal the publicly available moniker for the
                // FILESTREAM attributed column data. We will not surface the internal processing that
                // takes place to create the mappedPath.
                string mappedPath = InitializeNtPath(sPath);
                int    retval     = 0;
                Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out uint oldMode);

                try
                {
                    if (transactionContext.Length >= ushort.MaxValue)
                    {
                        throw ADP.ArgumentOutOfRange("transactionContext");
                    }

                    int headerSize = sizeof(Interop.NtDll.FILE_FULL_EA_INFORMATION);
                    int fullSize   = headerSize + transactionContext.Length + s_eaNameString.Length;

                    byte[] buffer = ArrayPool <byte> .Shared.Rent(fullSize);

                    fixed(byte *b = buffer)
                    {
                        Interop.NtDll.FILE_FULL_EA_INFORMATION *ea = (Interop.NtDll.FILE_FULL_EA_INFORMATION *)b;
                        ea->NextEntryOffset = 0;
                        ea->Flags           = 0;
                        ea->EaNameLength    = (byte)(s_eaNameString.Length - 1); // Length does not include terminating null character.
                        ea->EaValueLength   = (ushort)transactionContext.Length;

                        // We could continue to do pointer math here, chose to use Span for convenience to
                        // make sure we get the other members in the right place.
                        Span <byte> data = buffer.AsSpan(headerSize);

                        s_eaNameString.AsSpan().CopyTo(data);
                        data = data.Slice(s_eaNameString.Length);
                        transactionContext.AsSpan().CopyTo(data);

                        (int status, IntPtr handle) = Interop.NtDll.CreateFile(path: mappedPath.AsSpan(),
                                                                               rootDirectory: IntPtr.Zero,
                                                                               createDisposition: dwCreateDisposition,
                                                                               desiredAccess: nDesiredAccess,
                                                                               shareAccess: nShareAccess,
                                                                               fileAttributes: 0,
                                                                               createOptions: dwCreateOptions,
                                                                               eaBuffer: b,
                                                                               eaLength: (uint)fullSize);

                        SqlClientEventSource.Log.TryAdvancedTraceEvent("SqlFileStream.OpenSqlFileStream | ADV | Object Id {0}, Desired Access 0x{1}, Allocation Size {2}, File Attributes 0, Share Access 0x{3}, Create Disposition 0x{4}, Create Options 0x{5}", ObjectID, (int)nDesiredAccess, allocationSize, (int)nShareAccess, dwCreateDisposition, dwCreateOptions);

                        retval = status;
                        hFile  = new SafeFileHandle(handle, true);
                    }

                    ArrayPool <byte> .Shared.Return(buffer);
                }
                finally
                {
                    Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
                }

                switch (retval)
                {
                case 0:
                    break;

                case Interop.Errors.ERROR_SHARING_VIOLATION:
                    throw ADP.InvalidOperation(StringsHelper.GetString(Strings.SqlFileStream_FileAlreadyInTransaction));

                case Interop.Errors.ERROR_INVALID_PARAMETER:
                    throw ADP.Argument(StringsHelper.GetString(Strings.SqlFileStream_InvalidParameter));

                case Interop.Errors.ERROR_FILE_NOT_FOUND:
                {
                    System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                default:
                {
                    uint error = Interop.NtDll.RtlNtStatusToDosError(retval);
                    if (error == ERROR_MR_MID_NOT_FOUND)
                    {
                        // status code could not be mapped to a Win32 error code
                        error = (uint)retval;
                    }

                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error));
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }
                }

                if (hFile.IsInvalid)
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Interop.Errors.ERROR_INVALID_HANDLE);
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK)
                {
                    hFile.Dispose();
                    throw ADP.Argument(StringsHelper.GetString(Strings.SqlFileStream_PathNotValidDiskResource));
                }

                // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
                // through current data and then append new data to the end, so we need to tell SQL Server to preserve
                // the existing file contents.
                if (access == System.IO.FileAccess.ReadWrite)
                {
                    uint ioControlCode = Interop.Kernel32.CTL_CODE(FILE_DEVICE_FILE_SYSTEM,
                                                                   IoControlCodeFunctionCode, (byte)Interop.Kernel32.IoControlTransferType.METHOD_BUFFERED,
                                                                   (byte)Interop.Kernel32.IoControlCodeAccess.FILE_ANY_ACCESS);

                    if (!Interop.Kernel32.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out uint cbBytesReturned, IntPtr.Zero))
                    {
                        System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(e);
                        throw e;
                    }
                }

                // now that we've successfully opened a handle on the path and verified that it is a file,
                // use the SafeFileHandle to initialize our internal System.IO.FileStream instance
                System.Diagnostics.Debug.Assert(_m_fs == null);
                _m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
            }
            catch
            {
                if (hFile != null && !hFile.IsInvalid)
                {
                    hFile.Dispose();
                }

                throw;
            }
        }
        /// <summary>
        /// Retrieves a DataTable containing information about all visible SQL Server instances
        /// </summary>
        /// <returns></returns>
        internal static DataTable GetDataSources()
        {
            (new NamedPermissionSet("FullTrust")).Demand(); // SQLBUDT 244304
            char[]        buffer  = null;
            StringBuilder strbldr = new();

            int bufferSize = 1024;
            int readLength = 0;

            buffer = new char[bufferSize];
            bool   more    = true;
            bool   failure = false;
            IntPtr handle  = ADP.s_ptrZero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                long s_timeoutTime = TdsParserStaticMethods.GetTimeoutSeconds(ADP.DefaultCommandTimeout);
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                { }
                finally
                {
                    handle = SNINativeMethodWrapper.SNIServerEnumOpen();
                    SqlClientEventSource.Log.TryTraceEvent("<sc.{0}.{1}|INFO> {2} returned handle = {3}.",
                                                           nameof(SqlDataSourceEnumeratorNativeHelper),
                                                           nameof(GetDataSources),
                                                           nameof(SNINativeMethodWrapper.SNIServerEnumOpen), handle);
                }

                if (handle != ADP.s_ptrZero)
                {
                    while (more && !TdsParserStaticMethods.TimeoutHasExpired(s_timeoutTime))
                    {
                        readLength = SNINativeMethodWrapper.SNIServerEnumRead(handle, buffer, bufferSize, out more);

                        SqlClientEventSource.Log.TryTraceEvent("<sc.{0}.{1}|INFO> {2} returned 'readlength':{3}, and 'more':{4} with 'bufferSize' of {5}",
                                                               nameof(SqlDataSourceEnumeratorNativeHelper),
                                                               nameof(GetDataSources),
                                                               nameof(SNINativeMethodWrapper.SNIServerEnumRead),
                                                               readLength, more, bufferSize);
                        if (readLength > bufferSize)
                        {
                            failure = true;
                            more    = false;
                        }
                        else if (readLength > 0)
                        {
                            strbldr.Append(buffer, 0, readLength);
                        }
                    }
                }
            }
            finally
            {
                if (handle != ADP.s_ptrZero)
                {
                    SNINativeMethodWrapper.SNIServerEnumClose(handle);
                    SqlClientEventSource.Log.TryTraceEvent("<sc.{0}.{1}|INFO> {2} called.",
                                                           nameof(SqlDataSourceEnumeratorNativeHelper),
                                                           nameof(GetDataSources),
                                                           nameof(SNINativeMethodWrapper.SNIServerEnumClose));
                }
            }

            if (failure)
            {
                Debug.Assert(false, $"{nameof(GetDataSources)}:{nameof(SNINativeMethodWrapper.SNIServerEnumRead)} returned bad length");
                SqlClientEventSource.Log.TryTraceEvent("<sc.{0}.{1}|ERR> {2} returned bad length, requested buffer {3}, received {4}",
                                                       nameof(SqlDataSourceEnumeratorNativeHelper),
                                                       nameof(GetDataSources),
                                                       nameof(SNINativeMethodWrapper.SNIServerEnumRead),
                                                       bufferSize, readLength);

                throw ADP.ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, readLength), nameof(readLength));
            }
            return(ParseServerEnumString(strbldr.ToString()));
        }
Exemple #14
0
 internal static ArgumentOutOfRangeException InvalidMinAndMaxPair(string minParamName, TimeSpan minValue, string maxParamName, TimeSpan maxValue)
 => new ArgumentOutOfRangeException(minParamName, StringsHelper.GetString(Strings.SqlRetryLogic_InvalidMinMaxPair, minValue, maxValue, minParamName, maxParamName));
Exemple #15
0
 internal static ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, TimeSpan value, TimeSpan minValue, TimeSpan MaxValue)
 => new ArgumentOutOfRangeException(paramName, StringsHelper.GetString(Strings.SqlRetryLogic_InvalidRange, value, minValue, MaxValue));
Exemple #16
0
 internal static AggregateException ConfigurableRetryFail(IList <Exception> exceptions, SqlRetryLogicBase retryLogic, bool canceled)
 => canceled ? new AggregateException(StringsHelper.GetString(Strings.SqlRetryLogic_RetryCanceled, retryLogic.Current), exceptions)
         : new AggregateException(StringsHelper.GetString(Strings.SqlRetryLogic_RetryExceeded, retryLogic.NumberOfTries), exceptions);
Exemple #17
0
        private void OpenSqlFileStream
        (
            string path,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            Int64 allocationSize
        )
        {
            //-----------------------------------------------------------------
            // precondition validation

            // these should be checked by any caller of this method

            // ensure we have validated and normalized the path before
            Debug.Assert(path != null);
            Debug.Assert(transactionContext != null);

            if (access != FileAccess.Read && access != FileAccess.Write && access != FileAccess.ReadWrite)
            {
                throw ADP.ArgumentOutOfRange("access");
            }

            // FileOptions is a set of flags, so AND the given value against the set of values we do not support
            if ((options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.SequentialScan)) != 0)
            {
                throw ADP.ArgumentOutOfRange("options");
            }

            //-----------------------------------------------------------------

            // normalize the provided path
            //   * compress path to remove any occurrences of '.' or '..'
            //   * trim whitespace from the beginning and end of the path
            //   * ensure that the path starts with '\\'
            //   * ensure that the path does not start with '\\.\'
            //   * ensure that the path is not longer than Int16.MaxValue
            path = GetFullPathInternal(path);

            // ensure the running code has permission to read/write the file
            DemandAccessPermission(path, access);

            FileFullEaInformation    eaBuffer   = null;
            SecurityQualityOfService qos        = null;
            UnicodeString            objectName = null;

            Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null;

            int nDesiredAccess = UnsafeNativeMethods.FILE_READ_ATTRIBUTES | UnsafeNativeMethods.SYNCHRONIZE;

            UInt32 dwCreateOptions     = 0;
            UInt32 dwCreateDisposition = 0;

            System.IO.FileShare shareAccess = System.IO.FileShare.None;

            switch (access)
            {
            case System.IO.FileAccess.Read:
                nDesiredAccess     |= UnsafeNativeMethods.FILE_READ_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OPEN;
                break;

            case System.IO.FileAccess.Write:
                nDesiredAccess     |= UnsafeNativeMethods.FILE_WRITE_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE;
                break;

            case System.IO.FileAccess.ReadWrite:
            default:
                // we validate the value of 'access' parameter in the beginning of this method
                Debug.Assert(access == System.IO.FileAccess.ReadWrite);

                nDesiredAccess     |= UnsafeNativeMethods.FILE_READ_DATA | UnsafeNativeMethods.FILE_WRITE_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE;
                break;
            }

            if ((options & System.IO.FileOptions.WriteThrough) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_WRITE_THROUGH;
            }

            if ((options & System.IO.FileOptions.Asynchronous) == 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SYNCHRONOUS_IO_NONALERT;
            }

            if ((options & System.IO.FileOptions.SequentialScan) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SEQUENTIAL_ONLY;
            }

            if ((options & System.IO.FileOptions.RandomAccess) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_RANDOM_ACCESS;
            }

            try
            {
                eaBuffer = new FileFullEaInformation(transactionContext);

                qos = new SecurityQualityOfService(UnsafeNativeMethods.SecurityImpersonationLevel.SecurityAnonymous,
                                                   false, false);

                // NOTE: the Name property is intended to reveal the publicly available moniker for the
                //   FILESTREAM attributed column data. We will not surface the internal processing that
                //   takes place to create the mappedPath.
                string mappedPath = InitializeNtPath(path);
                objectName = new UnicodeString(mappedPath);

                UnsafeNativeMethods.OBJECT_ATTRIBUTES oa;
                oa.length                   = Marshal.SizeOf(typeof(UnsafeNativeMethods.OBJECT_ATTRIBUTES));
                oa.rootDirectory            = IntPtr.Zero;
                oa.attributes               = (int)UnsafeNativeMethods.Attributes.CaseInsensitive;
                oa.securityDescriptor       = IntPtr.Zero;
                oa.securityQualityOfService = qos;
                oa.objectName               = objectName;

                UnsafeNativeMethods.IO_STATUS_BLOCK ioStatusBlock;

                uint oldMode;
                uint retval = 0;

                UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode);
                try
                {
                    SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.SqlFileStream.OpenSqlFileStream|ADV> {0}, desiredAccess=0x{1}, allocationSize={2}, " +
                                                                   "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition);

                    retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess,
                                                              ref oa, out ioStatusBlock, ref allocationSize,
                                                              0, shareAccess, dwCreateDisposition, dwCreateOptions,
                                                              eaBuffer, (uint)eaBuffer.Length);
                }
                finally
                {
                    UnsafeNativeMethods.SetErrorModeWrapper(oldMode, out oldMode);
                }

                switch (retval)
                {
                case 0:
                    break;

                case UnsafeNativeMethods.STATUS_SHARING_VIOLATION:
                    throw ADP.InvalidOperation(StringsHelper.GetString(StringsHelper.SqlFileStream_FileAlreadyInTransaction));

                case UnsafeNativeMethods.STATUS_INVALID_PARAMETER:
                    throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidParameter));

                case UnsafeNativeMethods.STATUS_OBJECT_NAME_NOT_FOUND:
                {
                    System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                default:
                {
                    uint error = UnsafeNativeMethods.RtlNtStatusToDosError(retval);
                    if (error == UnsafeNativeMethods.ERROR_MR_MID_NOT_FOUND)
                    {
                        // status code could not be mapped to a Win32 error code
                        error = retval;
                    }

                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error));
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }
                }

                if (hFile.IsInvalid)
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(UnsafeNativeMethods.ERROR_INVALID_HANDLE);
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                UnsafeNativeMethods.FileType fileType = UnsafeNativeMethods.GetFileType(hFile);
                if (fileType != UnsafeNativeMethods.FileType.Disk)
                {
                    hFile.Dispose();
                    throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_PathNotValidDiskResource));
                }

                // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
                //   through current data and then append new data to the end, so we need to tell SQL Server to preserve
                //   the existing file contents.
                if (access == System.IO.FileAccess.ReadWrite)
                {
                    uint ioControlCode = UnsafeNativeMethods.CTL_CODE(UnsafeNativeMethods.FILE_DEVICE_FILE_SYSTEM,
                                                                      IoControlCodeFunctionCode, (byte)UnsafeNativeMethods.Method.METHOD_BUFFERED,
                                                                      (byte)UnsafeNativeMethods.Access.FILE_ANY_ACCESS);
                    uint cbBytesReturned = 0;

                    if (!UnsafeNativeMethods.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out cbBytesReturned, IntPtr.Zero))
                    {
                        System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(e);
                        throw e;
                    }
                }

                // now that we've successfully opened a handle on the path and verified that it is a file,
                //   use the SafeFileHandle to initialize our internal System.IO.FileStream instance
                // NOTE: need to assert UnmanagedCode permissions for this constructor. This is relatively benign
                //   in that we've done much the same validation as in the FileStream(string path, ...) ctor case
                //   most notably, validating that the handle type corresponds to an on-disk file.
                bool bRevertAssert = false;
                try
                {
                    SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                    sp.Assert();
                    bRevertAssert = true;

                    System.Diagnostics.Debug.Assert(m_fs == null);
                    m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
                }
                finally
                {
                    if (bRevertAssert)
                    {
                        SecurityPermission.RevertAssert();
                    }
                }
            }
            catch
            {
                if (hFile != null && !hFile.IsInvalid)
                {
                    hFile.Dispose();
                }

                throw;
            }
            finally
            {
                if (eaBuffer != null)
                {
                    eaBuffer.Dispose();
                    eaBuffer = null;
                }

                if (qos != null)
                {
                    qos.Dispose();
                    qos = null;
                }

                if (objectName != null)
                {
                    objectName.Dispose();
                    objectName = null;
                }
            }
        }
 public InputDialog()
 {
     this.InitializeComponent();
     this.PrimaryButtonText = StringsHelper.GetString("OK");
     this.CloseButtonText   = StringsHelper.GetString("Cancel");
 }
Exemple #19
0
        private void Initialize(IDictionary <string, ICollection <KeyBinding> > keyBindings)
        {
            _keyBindings = keyBindings;

            ClearKeyBindings();

            foreach (var value in Enum.GetValues(typeof(Command)))
            {
                var command   = (Command)value;
                var viewModel = new KeyBindingsViewModel(command.ToString(), _dialogService, StringsHelper.GetString(EnumHelper.GetEnumDescription(command)), true);
                foreach (var keyBinding in _keyBindings[command.ToString()])
                {
                    viewModel.Add(keyBinding);
                }
                viewModel.Edited += OnEdited;
                KeyBindings.Add(viewModel);
            }
        }