public static void Ctor_String_Exception()
 {
     string message = "That page was missing from the directory.";
     var innerException = new Exception("Inner exception");
     var exception = new DirectoryNotFoundException(message, innerException);
     ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_DIRECTORYNOTFOUND, innerException: innerException, message: message);
 }
 /// <summary>
 /// Handles any errors that CreateDirectoryEx may encounter
 /// </summary>
 private static void HandleCreateDirectoryExError(string template, string target, int errorCode)
 {
     Win32Exception win32Exception = new Win32Exception(errorCode);
     Exception error;
     switch ((Win32Error)errorCode)
     {
         case Win32Error.ACCESS_DENIED:
             error = new UnauthorizedAccessException(
                 string.Format("Access was denied to clone '{0}' to '{1}'.", template, target),
                 win32Exception);
             break;
         case Win32Error.PATH_NOT_FOUND:
             error = new DirectoryNotFoundException(
                 string.Format("The path '{0}' or '{1}' could not be found.", template, target),
                 win32Exception);
             break;
         case Win32Error.SHARING_VIOLATION:
             error = new SharingViolationException(
                 string.Format("The source or destination file was in use when copying '{0}' to '{1}'.", template, target),
                 win32Exception);
             break;
         case Win32Error.ALREADY_EXISTS:
             //If the directory already exists don't worry about it.
             return;
         default:
             error = win32Exception;
             break;
     }
     throw error;
 }
        public static void HandleException(Window window, DirectoryNotFoundException ex)
        {
            try
            {
                string message = string.Format(Properties.Resources.MessageDirectoryNotFoundException);

                TaskDialog dialog = new TaskDialog();

                dialog.InstructionText = message;
                //dialog.Text
                dialog.Icon = TaskDialogStandardIcon.Error;
                dialog.StandardButtons = TaskDialogStandardButtons.Ok;

                dialog.DetailsExpandedText = ex.Message;

                dialog.Caption = App.Current.ApplicationTitle;
                if (window != null)
                {
                    dialog.OwnerWindowHandle = new WindowInteropHelper(window).Handle;
                }

                dialog.Show();
            }
            catch (PlatformNotSupportedException)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #4
0
        private bool Validate(string path)
        {
            if (Directory.Exists(path))
            {
                return true;
            }
            else
            {
                var message = string.Format(Resources.Error_InvalidDirectory, path);
                var ex = new DirectoryNotFoundException(message);
                var error = new ErrorRecord(ex, AddSourceCommand.ErrorId, ErrorCategory.ResourceUnavailable, path);

                base.WriteError(error);

                return false;
            }
        }
 public static void Ctor_Empty()
 {
     var exception = new DirectoryNotFoundException();
     ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_DIRECTORYNOTFOUND, validateMessage: false);
 }
Exemple #6
0
        public void Start()
        {
            if (!Directory.Exists(_sourceWatchFolder))
            {
                var inner = new DirectoryNotFoundException(_sourceWatchFolder);
                throw new NancyAutoHostException("You need to provide a valid folder to watch", inner);
            }

            _watcher = CreateFolderWatcher(_sourceWatchFolder);

            _watcher.EnableRaisingEvents = true;
            OnChange(null);
        }
Exemple #7
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);
                        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(System.SRHelper.GetString(SR.SqlFileStream_FileAlreadyInTransaction));

                case Interop.Errors.ERROR_INVALID_PARAMETER:
                    throw ADP.Argument(System.SRHelper.GetString(SR.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(System.SRHelper.GetString(SR.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;
            }
        }
 public void writeToFile(string filepath)
 {
     try
     {
         System.IO.File.WriteAllText(filepath, conversation);
         setFinalOutput("Your chat has been exported to " + filepath);
     }
     catch (DirectoryNotFoundException e)
     {
         e = new DirectoryNotFoundException(e.Message + "\nThe filepath " + filepath + " could not be found.\nPlease ensure that you are not using characters such as '\\' and try again.");
         throw e;
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Exemple #9
0
        [System.Security.SecurityCritical]  // auto-generated
        private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
        {
            System.Exception exception = null;

            switch (errorCode)
            {
                case Interop.mincore.Errors.ERROR_INVALID_NAME:
                    exception = new ArgumentException(SR.Argument_InvalidName, nameof(name));
                    break;

                case Interop.mincore.Errors.ERROR_INVALID_HANDLE:
                    exception = new ArgumentException(SR.AccessControl_InvalidHandle);
                    break;

                case Interop.mincore.Errors.ERROR_FILE_NOT_FOUND:
                    if ((context != null) && (context is bool) && ((bool)context))
                    { // DirectorySecurity
                        if ((name != null) && (name.Length != 0))
                            exception = new DirectoryNotFoundException(name);
                        else
                            exception = new DirectoryNotFoundException();
                    }
                    else
                    {
                        if ((name != null) && (name.Length != 0))
                            exception = new FileNotFoundException(name);
                        else
                            exception = new FileNotFoundException();
                    }
                    break;

                default:
                    break;
            }

            return exception;
        }
        private void OpenSqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize)
        {
            if (((access != FileAccess.Read) && (access != FileAccess.Write)) && (access != FileAccess.ReadWrite))
            {
                throw ADP.ArgumentOutOfRange("access");
            }
            if ((options & ~(FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.SequentialScan | FileOptions.WriteThrough)) != FileOptions.None)
            {
                throw ADP.ArgumentOutOfRange("options");
            }
            path = GetFullPathInternal(path);
            DemandAccessPermission(path, access);
            FileFullEaInformation eaBuffer = null;
            SecurityQualityOfService service = null;
            UnicodeString str = null;
            SafeFileHandle fileHandle = null;
            int num2 = 0x100080;
            uint num = 0;
            uint num4 = 0;
            FileShare none = FileShare.None;
            switch (access)
            {
                case FileAccess.Read:
                    num2 |= 1;
                    none = FileShare.Delete | FileShare.ReadWrite;
                    num4 = 1;
                    break;

                case FileAccess.Write:
                    num2 |= 2;
                    none = FileShare.Delete | FileShare.Read;
                    num4 = 4;
                    break;

                default:
                    num2 |= 3;
                    none = FileShare.Delete | FileShare.Read;
                    num4 = 4;
                    break;
            }
            if ((options & (FileOptions.None | FileOptions.WriteThrough)) != FileOptions.None)
            {
                num |= 2;
            }
            if ((options & FileOptions.Asynchronous) == FileOptions.None)
            {
                num |= 0x20;
            }
            if ((options & FileOptions.SequentialScan) != FileOptions.None)
            {
                num |= 4;
            }
            if ((options & FileOptions.RandomAccess) != FileOptions.None)
            {
                num |= 0x800;
            }
            try
            {
                System.Data.SqlTypes.UnsafeNativeMethods.OBJECT_ATTRIBUTES object_attributes;
                eaBuffer = new FileFullEaInformation(transactionContext);
                service = new SecurityQualityOfService(System.Data.SqlTypes.UnsafeNativeMethods.SecurityImpersonationLevel.SecurityAnonymous, false, false);
                str = new UnicodeString(InitializeNtPath(path));
                object_attributes.length = Marshal.SizeOf(typeof(System.Data.SqlTypes.UnsafeNativeMethods.OBJECT_ATTRIBUTES));
                object_attributes.rootDirectory = IntPtr.Zero;
                object_attributes.attributes = 0x40;
                object_attributes.securityDescriptor = IntPtr.Zero;
                object_attributes.securityQualityOfService = service;
                object_attributes.objectName = str;
                uint mode = System.Data.SqlTypes.UnsafeNativeMethods.SetErrorMode(1);
                uint status = 0;
                try
                {
                    System.Data.SqlTypes.UnsafeNativeMethods.IO_STATUS_BLOCK io_status_block;
                    Bid.Trace("<sc.SqlFileStream.OpenSqlFileStream|ADV> %d#, desiredAccess=0x%08x, allocationSize=%I64d, fileAttributes=0x%08x, shareAccess=0x%08x, dwCreateDisposition=0x%08x, createOptions=0x%08x\n", this.ObjectID, num2, allocationSize, 0, (int) none, num4, num);
                    status = System.Data.SqlTypes.UnsafeNativeMethods.NtCreateFile(out fileHandle, num2, ref object_attributes, out io_status_block, ref allocationSize, 0, none, num4, num, eaBuffer, (uint) eaBuffer.Length);
                }
                finally
                {
                    System.Data.SqlTypes.UnsafeNativeMethods.SetErrorMode(mode);
                }
                switch (status)
                {
                    case 0:
                        break;

                    case 0xc000000d:
                        throw ADP.Argument(Res.GetString("SqlFileStream_InvalidParameter"));

                    case 0xc0000034:
                    {
                        DirectoryNotFoundException e = new DirectoryNotFoundException();
                        ADP.TraceExceptionAsReturnValue(e);
                        throw e;
                    }
                    case 0xc0000043:
                        throw ADP.InvalidOperation(Res.GetString("SqlFileStream_FileAlreadyInTransaction"));

                    default:
                    {
                        uint num6 = System.Data.SqlTypes.UnsafeNativeMethods.RtlNtStatusToDosError(status);
                        if (num6 == 0x13d)
                        {
                            num6 = status;
                        }
                        Win32Exception exception3 = new Win32Exception((int) num6);
                        ADP.TraceExceptionAsReturnValue(exception3);
                        throw exception3;
                    }
                }
                if (fileHandle.IsInvalid)
                {
                    Win32Exception exception2 = new Win32Exception(6);
                    ADP.TraceExceptionAsReturnValue(exception2);
                    throw exception2;
                }
                if (System.Data.SqlTypes.UnsafeNativeMethods.GetFileType(fileHandle) != System.Data.SqlTypes.UnsafeNativeMethods.FileType.Disk)
                {
                    fileHandle.Dispose();
                    throw ADP.Argument(Res.GetString("SqlFileStream_PathNotValidDiskResource"));
                }
                if (access == FileAccess.ReadWrite)
                {
                    uint ioControlCode = System.Data.SqlTypes.UnsafeNativeMethods.CTL_CODE(9, 0x958, 0, 0);
                    uint cbBytesReturned = 0;
                    if (!System.Data.SqlTypes.UnsafeNativeMethods.DeviceIoControl(fileHandle, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out cbBytesReturned, IntPtr.Zero))
                    {
                        Win32Exception exception = new Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(exception);
                        throw exception;
                    }
                }
                bool flag = false;
                try
                {
                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
                    flag = true;
                    this.m_fs = new FileStream(fileHandle, access, 1, (options & FileOptions.Asynchronous) != FileOptions.None);
                }
                finally
                {
                    if (flag)
                    {
                        CodeAccessPermission.RevertAssert();
                    }
                }
            }
            catch
            {
                if ((fileHandle != null) && !fileHandle.IsInvalid)
                {
                    fileHandle.Dispose();
                }
                throw;
            }
            finally
            {
                if (eaBuffer != null)
                {
                    eaBuffer.Dispose();
                    eaBuffer = null;
                }
                if (service != null)
                {
                    service.Dispose();
                    service = null;
                }
                if (str != null)
                {
                    str.Dispose();
                    str = null;
                }
            }
        }
        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 occurences 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
                {
                    Bid.Trace("<sc.SqlFileStream.OpenSqlFileStream|ADV> %d#, desiredAccess=0x%08x, allocationSize=%I64d, fileAttributes=0x%08x, shareAccess=0x%08x, dwCreateDisposition=0x%08x, createOptions=0x%08x\n",
                        ObjectID, (int) nDesiredAccess, allocationSize, 0, (int) shareAccess, dwCreateDisposition, dwCreateOptions );
                    
                    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 ( Res.GetString ( Res.SqlFileStream_FileAlreadyInTransaction ) );

                    case UnsafeNativeMethods.STATUS_INVALID_PARAMETER:
                        throw ADP.Argument ( Res.GetString ( Res.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 ( Res.GetString ( Res.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 );
#if MOBILE
                    m_fs = new System.IO.FileStream ( hFile.DangerousGetHandle (), access, ( ( options & System.IO.FileOptions.Asynchronous ) != 0 ), DefaultBufferSize );
#else
                    m_fs = new System.IO.FileStream ( hFile, access, DefaultBufferSize, ( ( options & System.IO.FileOptions.Asynchronous ) != 0 ) );
#endif
                }
                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;
                }
            }
        }
        void IPscxErrorHandler.WriteDirectoryNotFoundError(string path)
        {
            string msg = string.Format(Resources.Errors.DirectoryNotFound, path);
            Exception ex = new DirectoryNotFoundException(msg);

            ErrorHandler.WriteFileError(path, ex);
        }
 public static void Handle(DirectoryNotFoundException exception)
 {
     ConsoleLogExceptionMessage(exception);
 }
 public ProjectExceptions(string errorText, DirectoryNotFoundException innerException)
     : base(errorText, innerException)
 {
 }
Exemple #15
0
 /// <summary>
 /// WriteXML
 /// </summary>
 /// <param name="xmlDoc"></param>
 /// <param name="fileName"></param>
 /// <param name="keyPathFile"></param>
 /// <param name="hasAppendCouter"></param>
 /// <returns></returns>
 private static FileInfo WriteXML(XmlDocument xmlDoc, string fileName, string pathFile, string appendTime, bool hasAppendCouter)
 {
     //var path = GetPathByKey(keyPathFile);
     //input is XML XmlReader
     string tmpFilePath = string.Empty;
     //Check path is valid
     if (objRegexPattern.IsMatch(pathFile) == true)
     {
         //Path not exist
         if (Directory.Exists(pathFile) == false)
         {
             //Create new path
             Directory.CreateDirectory(pathFile);
         }
         tmpFilePath = GetPath(pathFile);
     }
     //else path is not valid
     else
     {
         DirectoryNotFoundException ex = new DirectoryNotFoundException(string.Format("{0} Directory is not valid", pathFile));
         //////Throw exception
         throw ex;
     }
     //Save
     var savedPath = Path.Combine(tmpFilePath, FormatFileName(fileName, tmpFilePath, appendTime,  hasAppendCouter));
     xmlDoc.Save(savedPath);
     return new FileInfo(savedPath);
 }
        /// <summary>
        /// Deletes shapefile and associated files (.shx, .dbf, .prj).
        /// </summary>
        /// <param name="ShapefilePath">Full path to shapefile, including .shp extension</param>
        public static void Delete(string ShapefilePath)
        {
            List<string> ParamList = new List<string>();
            ParamList.Add("ShapefilePath: " + ShapefilePath);
            LogManager.DefaultLogManager.PublicMethodEntered("MapWindow.Analysis.DataManagement.Shapefile.Delete", ParamList);

            string Filename, Directory;
            if (ShapefilePath == null)
            {
                ArgumentNullException ex = new ArgumentNullException("ShapefilePath cannot be null.");
                LogManager.DefaultLogManager.Exception(ex);
                throw ex;
            }
            Directory = System.IO.Path.GetDirectoryName(ShapefilePath);

            if (System.IO.Directory.Exists(Directory) == false)
            {
                System.IO.DirectoryNotFoundException ex = new System.IO.DirectoryNotFoundException("The specified directory: " + Directory + " does not exist.");
                LogManager.DefaultLogManager.Exception(ex);
                throw ex;
            }
            Filename = ShapefilePath;

            try
            {
                if (System.IO.File.Exists(Filename)) System.IO.File.Delete(Filename);
                Filename = System.IO.Path.ChangeExtension(Filename, ".shx");
                if (System.IO.File.Exists(Filename)) System.IO.File.Delete(Filename);
                Filename = System.IO.Path.ChangeExtension(Filename, ".dbf");
                if (System.IO.File.Exists(Filename)) System.IO.File.Delete(Filename);
                Filename = System.IO.Path.ChangeExtension(Filename, ".prj");
                if (System.IO.File.Exists(Filename)) System.IO.File.Delete(Filename);
                Filename = System.IO.Path.ChangeExtension(Filename, ".spx");
                if (System.IO.File.Exists(Filename)) System.IO.File.Delete(Filename);
                Filename = System.IO.Path.ChangeExtension(Filename, ".sbn");
                if (System.IO.File.Exists(Filename)) System.IO.File.Delete(Filename);
                Filename = System.IO.Path.ChangeExtension(Filename, ".xml");
                if (System.IO.File.Exists(Filename)) System.IO.File.Delete(Filename);
                Filename = System.IO.Path.ChangeExtension(Filename, ".shp.xml");
                if (System.IO.File.Exists(Filename)) System.IO.File.Delete(Filename);
            }
            catch (Exception Ex)
            {
                LogManager.DefaultLogManager.Exception(Ex);
                throw Ex;
            }



            LogManager.DefaultLogManager.PublicMethodLeft("MapWindow.Analysis.DataManagement.Shapefile.Delete");
            return;
        }
Exemple #17
0
 /// <summary>
 /// Displays an error message when DirectoryNotFoundException is thrown.
 /// </summary>
 /// <param name="ex">The exception</param>
 private static void ShowException(DirectoryNotFoundException ex)
 {
     PrepareToShow();
     string errorMessage = Util.CombineMessageParts(SharedStrings.DIRECTORY_NOT_FOUND, ex.Message);
     ShowError(errorMessage, false);
 }
Exemple #18
0
 DirectoryNotFoundException DirectoryNotFoundExceptionWithSourceFilename(IFile file, DirectoryNotFoundException ex)
 {
     return new DirectoryNotFoundException(
         string.Format(
             "{0}{1}Referenced by an @import in '{2}'.",
             ex.Message,
             Environment.NewLine,
             file.FullPath
         ),
         ex
     );
 }
Exemple #19
0
        /// <summary>
        /// Compiles a mod from its source folder.
        /// </summary>
        /// <param name="folder">The mod's folder. Either an absolute path,
        /// relative to the working directory or the name of a folder in the Mods\Sources folder</param>
        /// <returns>The output of the compiler.</returns>
        public CompilerOutput CompileFromSource  (string folder)
        {
            for (int i = 0; i < Loggers.Count; i++)
                Loggers[i].compiler_wr = new WeakReference<ModCompiler>(this);

            folder = Environment.ExpandEnvironmentVariables(folder);

            if (folder.EndsWith("\\"))
                folder = folder.Remove(folder.Length - 1);

            if (folder[1] != ':' && !folder.StartsWith("\\")) // <drive>:\path or \\ServerName\path
                // if the folder doesn't exist, it's maybe a folder in the Mods\Sources directory?
                if (!Directory.Exists(folder))
                    folder = Mods.pathSources + "\\" + folder;
                else
                    folder = Path.GetFullPath(folder);

            Log("Compiling source " + folder, MessageImportance.Normal);

            building = new ModData(this);

            try
            {
                building.OriginPath = folder;
                building.OriginName = Path.GetFileName(folder);

                if (!BeginCompile(folder))
                {
                    Exception cause;
                    LogError(cause = new CompilerException("Mod already building!"));

                    CompilerOutput o;
                    LogResult(o = CreateOutput(new List<CompilerError>()
                    {
                        new CompilerError(building)
                        {
                            Cause = cause,
                            FilePath = folder,
                            IsWarning = true,
                            Message = "The mod is already being built."
                        }
                    }));

                    return o;
                }

                #region check if folder exists
                if (!Directory.Exists(folder))
                {
                    EndCompile(folder);

                    Exception cause;
                    LogError(cause = new DirectoryNotFoundException("Directory '" + folder + "' not found."));

                    CompilerOutput o;
                    LogResult(o = new CompilerOutput()
                    {
                        Succeeded = false,
                        errors = new List<CompilerError>()
                        {
                            new CompilerError(building)
                            {
                                Cause = cause,
                                Message = "The mod directory (" + folder + ") was not found",
                                IsWarning = false,
                                FilePath = folder
                            }
                        }
                    });

                    return o;
                }
                #endregion

                CompilerOutput outp;

                Log("Loading files.", MessageImportance.High);

                var readFiles = new FileLoader(this).LoadFiles(folder);
                outp = CreateOutput(readFiles.Item3);
                if (!outp.Succeeded)
                {
                    LogResult (outp  );
                    EndCompile(folder);
                    return outp;
                }

                Log("Validating JSONs.", MessageImportance.High);

                outp = Validate(readFiles.Item1, readFiles.Item2, true);
                if (!outp.Succeeded)
                {
                    LogResult (outp  );
                    EndCompile(folder);
                    return outp;
                }

                Log("Building sources.", MessageImportance.High);

                var compiled = new Builder(this).Build();
                outp = CreateOutput(compiled.Item3);
                outp.Succeeded &= compiled.Item1 != null;
                if (!outp.Succeeded)
                {
                    LogResult (outp  );
                    EndCompile(folder);
                    return outp;
                }

                return MainCompileStuff(building, compiled.Item1);
            }
            catch (Exception e)
            {
                LogError(e, "Unexpected error.");

                EndCompile(folder);

                CompilerOutput o;
                LogResult(o = CreateOutput(new List<CompilerError>()
                {
                    new CompilerError(building)
                    {
                        Cause     = e,
                        FilePath  = folder,
                        IsWarning = false,
                        Message   = "An unexpected error occured while compiling."
                    }
                }));

                return o;
            }
        }
        /// <summary>
        /// Serialise the CDA document to an XML file
        /// </summary>
        /// <param name="fileLocation">filename of the XML file to be created</param>
        public void CreateXML(string fileLocation)
        {
            FileInfo tagetInfo = new FileInfo(fileLocation);

            if (tagetInfo.Directory.Exists)
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.IndentChars = ("    ");

                using (XmlWriter writer = XmlWriter.Create(fileLocation, settings))
                {
                    writeXmlCommentBlock(writer);

                    writer.WriteStartElement("ClinicalDocument", "urn:hl7-org:v3");
                    writeXml(writer);
                    writer.WriteEndElement();
                    writer.Flush();
                }
            }
            else
            {
                ApplicationException exInner = new ApplicationException(tagetInfo.DirectoryName);
                DirectoryNotFoundException ex = new DirectoryNotFoundException("Target Directory does not exist", exInner);
                throw ex;
            }
        }
Exemple #21
0
        public static bool ShowFile(HttpResponse httpResponse, NameValueCollection queryString, CommonUtils.AppSettingKey settingKey, out Exception message)
        {
            try
            {
                string fileName = queryString["file"];

                if (string.IsNullOrEmpty(fileName))
                {
                    message = new Exception("Query string 'file' missing from url.");
                    return false;
                }

                string folderConfig = GetAppSettingValue(settingKey);

                string folderPath = Path.Combine(folderConfig, fileName);

                if (!Directory.Exists(folderPath))
                {
                    message = new DirectoryNotFoundException(string.Format(@"Failed to find file '{0}' from this location:  ({1}).
                                                    Please ask your administrator to check whether the folder exists.", fileName, folderPath));
                    return false;
                }

                var files = Directory.GetFiles(folderPath);

                if (files.Any())
                {
                    string filePath = files[0];

                    httpResponse.Clear();
                    httpResponse.ClearContent();

                    //Response.OutputStream.f
                    httpResponse.BufferOutput = true;
                    httpResponse.ContentType = "application/unknown";
                    httpResponse.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(filePath)));
                    byte[] fileContent = File.ReadAllBytes(filePath);

                    BinaryWriter binaryWriter = new BinaryWriter(httpResponse.OutputStream);
                    binaryWriter.Write(fileContent, 0, fileContent.Length);
                    binaryWriter.Flush();
                    binaryWriter.Close();

                    //httpResponse.Flush();
                }
            }
            catch (Exception ex)
            {
                message = ex;
                return false;
            }

            message = null;
            return true;
        }
Exemple #22
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 occurences 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
                {
                    Bid.Trace("<sc.SqlFileStream.OpenSqlFileStream|ADV> %d#, desiredAccess=0x%08x, allocationSize=%I64d, fileAttributes=0x%08x, shareAccess=0x%08x, dwCreateDisposition=0x%08x, createOptions=0x%08x\n",
                              ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition, dwCreateOptions);

                    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(Res.GetString(Res.SqlFileStream_FileAlreadyInTransaction));

                case UnsafeNativeMethods.STATUS_INVALID_PARAMETER:
                    throw ADP.Argument(Res.GetString(Res.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(Res.GetString(Res.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;
                }
            }
        }
Exemple #23
0
 public static DirectoryNotFoundException/*!*/ Create(RubyClass/*!*/ self, [DefaultProtocol, DefaultParameterValue(null)]MutableString message) {
     DirectoryNotFoundException result = new DirectoryNotFoundException(RubyExceptions.MakeMessage(ref message, "Not a directory"));
     RubyExceptionData.InitializeException(result, message);
     return result;
 }
        public void Validate()
        {
            if (!Directory.Exists(basePath))
            {
                throw new DirectoryNotFoundException(basePath);
            }

            Array serverFolders = Enum.GetValues(typeof(ServerFolders));

            foreach (Enum serverFolder in serverFolders)
            {
                string path = GetPath((ServerFolders)serverFolder);

                if ((IsVital((ServerFolders)serverFolder)) && (!Directory.Exists(path)))
                {
                    Directory.CreateDirectory(path);
                    DirectoryNotFoundException exception = new DirectoryNotFoundException(path);
                    ProcessException.WriteErrorLog(exception.StackTrace, exception.Message);
                    ProcessException.WriteInfoLog("\r\nCreated folder: " + path,"ServerEnviroment.Validate()");
                }
            }
        }
Exemple #25
-1
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Equals(""))
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                        _port,
                        _credential,
                        _proxyserver,
                        _proxytype,
                        _proxyport,
                        _proxycredential,
                        kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = _credential.GetNetworkCredential().Password;
                        }
                    };

                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                        _port,
                        _keyfile,
                        _credential,
                        _proxyserver,
                        _proxytype,
                        _proxyport,
                        _proxycredential);
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);

                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key is not being verified since Force switch is used.");
                }
                else
                {
                    var computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {

                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                        {
                            Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                        }

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                                {
                                    Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                                }
                                e.CanTrust = true;

                            }
                            else
                            {
                                e.CanTrust = false;

                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                e.CanTrust = false;
                            }
                            else
                            {
                                int choice;
                                if (_acceptkey)
                                {
                                    choice = 0;
                                }
                                else
                                {
                                    var choices = new Collection<ChoiceDescription>
                                    {
                                        new ChoiceDescription("Y"),
                                        new ChoiceDescription("N")
                                    };

                                    choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                                }
                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    keymng.SetKey(computer1, fingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        }
                    };
                }
                try
                {
                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Connect to host using Connection info
                    client.Connect();
                }
                catch (Renci.SshNet.Common.SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshAuthenticationException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                    WriteError(erec);
                }
                if (client.IsConnected)
                {
                    client.BufferSize = 1024;

                    // Print progess of upload.

                    if (!_noProgress)
                    {
                        client.Uploading += delegate(object sender, ScpUploadEventArgs e)
                        {
                            var progressRecord = new ProgressRecord(1, "Uploading " + e.Filename, String.Format("{0} Bytes Uploaded of {1}", e.Uploaded, e.Size))
                            {
                                PercentComplete = Convert.ToInt32((e.Uploaded * 100) / e.Size)
                            };

                            Host.UI.WriteProgress(1, progressRecord);
                        };
                    }

                    // Resolve the path even if a relative one is given.
                    ProviderInfo provider;
                    var pathinfo = GetResolvedProviderPathFromPSPath(_localfolder, out provider);
                    var localfullPath = pathinfo[0];

                    //var localfullPath = Path.GetFullPath(_localfolder);
                    if (Directory.Exists(localfullPath))
                    {
                        try
                        {
                            WriteVerbose("Uploading " + _remotefolder);
                            var dirinfo = new DirectoryInfo(@localfullPath);
                            client.Upload(dirinfo, _remotefolder);
                        }
                        catch (Exception e)
                        {
                            ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                            WriteError(erec);
                        }

                    }
                    else
                    {
                        var ex = new DirectoryNotFoundException("Directory " + localfullPath + " was not found.");
                        WriteError(new ErrorRecord(ex,
                                                   "Directory " + localfullPath + " was not found.",
                                                   ErrorCategory.InvalidArgument,
                                                   localfullPath));
                    }
                    client.Disconnect();
                }
            }
        }