示例#1
0
 /// <summary>
 /// Throws an exception when an error occurs.
 /// </summary>
 /// <param name="errorCode">The result of the P/Invoke call.</param>
 /// <exception cref="Win32Exception">If <paramref name="errorCode"/> is not <see cref="Win32ErrorCode.ERROR_SUCCESS"/>.</exception>
 public static void ThrowOnError(this Win32ErrorCode errorCode)
 {
     if (errorCode != Win32ErrorCode.ERROR_SUCCESS)
     {
         throw new Win32Exception(errorCode);
     }
 }
示例#2
0
        public static void AssertSuccess(Win32ErrorCode code)
        {
            switch (code)
            {
            case Win32ErrorCode.Success:
            case Win32ErrorCode.MORE_DATA:
                // No error occured, so exit gracefully.
                return;
            }

            var       genericException = new Win32Exception((int)code);
            Exception exceptionToThrow;

            // We will try to translate the generic Win32 exception to a more specific built-in exception.
            switch (code)
            {
            case Win32ErrorCode.DS_INVALID_DN_SYNTAX:
            case Win32ErrorCode.INVALID_PARAMETER:
                exceptionToThrow = new ArgumentException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.FILE_NOT_FOUND:
                exceptionToThrow = new FileNotFoundException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.ACCESS_DENIED:
            case Win32ErrorCode.DS_DRA_ACCESS_DENIED:
            case Win32ErrorCode.WRONG_PASSWORD:
            case Win32ErrorCode.PASSWORD_EXPIRED:
                exceptionToThrow = new UnauthorizedAccessException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.NOT_ENOUGH_MEMORY:
            case Win32ErrorCode.OUTOFMEMORY:
            case Win32ErrorCode.DS_DRA_OUT_OF_MEM:
            case Win32ErrorCode.RPC_S_OUT_OF_RESOURCES:
                exceptionToThrow = new OutOfMemoryException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.NO_LOGON_SERVERS:
            case Win32ErrorCode.NO_SUCH_DOMAIN:
            case Win32ErrorCode.RPC_S_SERVER_UNAVAILABLE:
            case Win32ErrorCode.RPC_S_CALL_FAILED:
                exceptionToThrow = new ActiveDirectoryServerDownException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.DS_OBJ_NOT_FOUND:
            // This error code means either a non-existing DN or Access Denied.
            case Win32ErrorCode.DS_DRA_BAD_DN:
                exceptionToThrow = new DirectoryObjectNotFoundException(null, genericException);
                break;

            // TODO: Add translation for ActiveDirectoryOperationException and for other exception types.
            default:
                // We were not able to translate the Win32Exception to a more specific type.
                exceptionToThrow = genericException;
                break;
            }
            throw exceptionToThrow;
        }
示例#3
0
    public void Win32Exception_NativeErrorCode()
    {
        Win32ErrorCode error = Win32ErrorCode.ERROR_ALREADY_FIBER;
        var            ex    = new Win32Exception(error);

        Assert.Equal(error, ex.NativeErrorCode);
    }
示例#4
0
文件: IO.cs 项目: gtrant/eraser
        public static IList <StreamInfo> GetADSes(this FileInfo info)
        {
            List <StreamInfo> result = new List <StreamInfo>();

            using (SafeFileHandle streamHandle = NativeMethods.CreateFile(info.FullName,
                                                                          NativeMethods.GENERIC_READ, (uint)FileShare.ReadWrite, IntPtr.Zero,
                                                                          (uint)FileMode.Open, (uint)FileOptions.None, IntPtr.Zero))
            {
                if (streamHandle.IsInvalid)
                {
                    throw Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
                }

                //Allocate the structures
                NativeMethods.FILE_STREAM_INFORMATION[] streams = GetADSes(streamHandle);

                foreach (NativeMethods.FILE_STREAM_INFORMATION streamInfo in streams)
                {
                    //Get the name of the stream. The raw value is :NAME:$DATA
                    string streamName = streamInfo.StreamName.Substring(1,
                                                                        streamInfo.StreamName.LastIndexOf(':') - 1);

                    if (streamName.Length != 0)
                    {
                        result.Add(new StreamInfo(info.FullName, streamName));
                    }
                }
            }

            return(result.AsReadOnly());
        }
示例#5
0
 public static void AssertSuccess(Win32ErrorCode code)
 {
     if (code != Win32ErrorCode.Success)
     {
         throw new Win32Exception((int) code);
     }
 }
示例#6
0
 public static void AssertSuccess(Win32ErrorCode code)
 {
     if (code != Win32ErrorCode.Success)
     {
         throw new Win32Exception((int)code);
     }
 }
示例#7
0
    public void Win32Exception_Message()
    {
        Win32ErrorCode error = Win32ErrorCode.ERROR_INVALID_LABEL;
        var            ex    = new Win32Exception(error);

        Assert.Equal("Indicates a particular Security ID may not be assigned as the label of an object", ex.Message);
    }
示例#8
0
    public void Win32Exception_MessageNotFound()
    {
        Win32ErrorCode error = (Win32ErrorCode)0x11111111;
        var            ex    = new Win32Exception(error);

        Assert.Equal("Unknown error (0x11111111)", ex.Message);
    }
示例#9
0
    public void IsProductElevated_BadArgs()
    {
        Guid           productCode = Guid.Empty;
        bool           elevated;
        Win32ErrorCode result = MsiIsProductElevated(productCode, out elevated);

        Assert.Equal(Win32ErrorCode.ERROR_UNKNOWN_PRODUCT, result);
    }
示例#10
0
        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="context">异常信息</param>
        public Win32ErrorCodeException(string context, Win32ErrorCode win32ErrorCode = Win32ErrorCode.Win32Error)
        {
            var error          = Marshal.GetLastWin32Error();
            var innerException = new Win32Exception(error);

            Win32ErrorCode = win32ErrorCode;
            Message        = Win32ErrorCode <= 0 ? $"{context}: (Error Code {error}) {innerException.Message}" : context;
        }
示例#11
0
 public static void AssertSuccess(NtStatus status)
 {
     if (status != NtStatus.Success)
     {
         Win32ErrorCode code = NativeMethods.RtlNtStatusToDosError(status);
         throw new Win32Exception((int)code);
     }
 }
示例#12
0
 /// <summary>
 /// Converts a <see cref="Win32ErrorCode"/> to an <see cref="HResult"/>.
 /// </summary>
 /// <param name="error">The <see cref="Win32ErrorCode"/> to convert.</param>
 /// <returns>The <see cref="HResult"/></returns>
 public static HResult ToHResult(this Win32ErrorCode error)
 {
     // From winerror.h
     //  (HRESULT)(x) <= 0 ? (HRESULT)(x) : (HRESULT) (((x) & 0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000)
     return(error <= 0
         ? (HResult)(int)error
         : (HResult)(int)(((int)error & 0x0000ffff) | ((int)FACILITY_WIN32 /*<< 16*/) | 0x80000000));
 }
示例#13
0
    public void Win32Exception_CodeAndMessage()
    {
        Win32ErrorCode error = Win32ErrorCode.ERROR_ALREADY_FIBER;
        var            ex    = new Win32Exception(error, "msg");

        Assert.Equal(error, ex.NativeErrorCode);
        Assert.Equal("msg", ex.Message);
    }
示例#14
0
        public static byte[] SddlToBinary(this string securityDescriptor)
        {
            Validator.AssertNotNullOrWhiteSpace(securityDescriptor, "securityDescriptor");
            byte[]         binarySecurityDescriptor;
            Win32ErrorCode result = NativeMethods.ConvertStringSecurityDescriptorToSecurityDescriptor(securityDescriptor, GenericSecurityDescriptor.Revision, out binarySecurityDescriptor);

            Validator.AssertSuccess(result);
            return(binarySecurityDescriptor);
        }
示例#15
0
        public static string GetClass(this RegistryKey key)
        {
            string         keyClass;
            DateTime       lastWrite;
            Win32ErrorCode result = NativeMethods.RegQueryInfoKey(key.Handle, out keyClass, out lastWrite);

            Validator.AssertSuccess(result);
            return(keyClass);
        }
示例#16
0
 /// <summary>
 /// Gets the text associated with a <see cref="Win32ErrorCode"/>.
 /// </summary>
 /// <param name="error">The error code.</param>
 /// <returns>The error message. Or <c>null</c> if no message could be found.</returns>
 public static unsafe string GetMessage(this Win32ErrorCode error)
 {
     return(FormatMessage(
                FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM,
                null,
                (int)error,
                0,
                null,
                MaxAllowedBufferSize));
 }
        public RegistryHiveFileMapping(string hiveFilePath)
        {
            Validator.AssertNotNullOrWhiteSpace(hiveFilePath, "hiveFilePath");
            SetProcessPrivilege(BackupPrivilege, true);
            SetProcessPrivilege(RestorePrivilege, true);
            this.UsersSubKey = string.Format(SubKeyFormat, Guid.NewGuid());
            Win32ErrorCode result = NativeMethods.RegLoadKey((IntPtr)RegistryHive.Users, this.UsersSubKey, hiveFilePath);

            Validator.AssertSuccess(result);
        }
示例#18
0
    public void Win32Exception_MessageNotFound()
    {
        Win32ErrorCode error = (Win32ErrorCode)0x11111111;
        var            ex    = new Win32Exception(error);

#if DESKTOP
        Assert.Equal("Unknown error (0x11111111)", ex.Message);
#else
        Assert.Equal("Unknown Win32 error (0x11111111)", ex.Message);
#endif
    }
示例#19
0
        internal static Win32ErrorCode RegQueryInfoKey(SafeRegistryHandle hKey, out string keyClass, out DateTime lastWriteTime)
        {
            StringBuilder  buffer     = new StringBuilder(MaxRegistryKeyClassSize);
            int            bufferSize = buffer.Capacity;
            long           fileTime;
            Win32ErrorCode result = NativeMethods.RegQueryInfoKey(hKey, buffer, ref bufferSize, IntPtr.Zero, null, null, null, null, null, null, null, out fileTime);

            keyClass      = buffer.ToString();
            lastWriteTime = DateTime.FromFileTimeUtc(fileTime);
            return(result);
        }
 protected virtual void Dispose(bool disposing)
 {
     if (this.UsersSubKey != null)
     {
         // Ignore any errors
         Win32ErrorCode result = NativeMethods.RegUnLoadKey((IntPtr)RegistryHive.Users, this.UsersSubKey);
         SetProcessPrivilege(RestorePrivilege, false);
         SetProcessPrivilege(BackupPrivilege, false);
         this.UsersSubKey = null;
     }
 }
示例#21
0
        /// <summary>
        /// The MsiEnumProductsEx function enumerates through one or all the instances of products that are currently advertised or installed in the specified contexts.
        /// This function supersedes MsiEnumProducts.
        /// </summary>
        /// <param name="szProductCode">
        /// ProductCode GUID of the product to be enumerated. Only instances of products within the scope of the context specified by the szUserSid and dwContext parameters are enumerated. This parameter can be set to NULL to enumerate all products in the specified context.
        /// </param>
        /// <param name="szUserSid">
        /// Null-terminated string that specifies a security identifier (SID) that restricts the context of enumeration. The special SID string s-1-1-0 (Everyone) specifies enumeration across all users in the system. A SID value other than s-1-1-0 is considered a user-SID and restricts enumeration to the current user or any user in the system. This parameter can be set to NULL to restrict the enumeration scope to the current user.
        /// See MSDN documentation for more information.
        /// </param>
        /// <param name="dwContext">Restricts the enumeration to a context. </param>
        /// <param name="dwIndex">Specifies the index of the product to retrieve. This parameter must be zero for the first call to the MsiEnumProductsEx function and then incremented for subsequent calls. The index should be incremented, only if the previous call has returned ERROR_SUCCESS. Because products are not ordered, any new product has an arbitrary index. This means that the function can return products in any order.</param>
        /// <param name="szInstalledProductCode">Gives the ProductCode GUID of the product instance being enumerated. This parameter can be NULL.</param>
        /// <param name="pdwInstalledContext">Returns the context of the product instance being enumerated. The output value can be <see cref="MSIINSTALLCONTEXT.MSIINSTALLCONTEXT_USERMANAGED"/>, <see cref="MSIINSTALLCONTEXT.MSIINSTALLCONTEXT_USERUNMANAGED"/>, or <see cref="MSIINSTALLCONTEXT.MSIINSTALLCONTEXT_MACHINE"/>. This parameter can be NULL.</param>
        /// <param name="szSid">
        /// An output buffer that receives the string SID of the account under which this product instance exists. This buffer returns an empty string for an instance installed in a per-machine context.
        /// </param>
        /// <returns>An error code.</returns>
        public static unsafe Win32ErrorCode MsiEnumProductsEx(
            string szProductCode,
            string szUserSid,
            MSIINSTALLCONTEXT dwContext,
            int dwIndex,
            out Guid szInstalledProductCode,
            out MSIINSTALLCONTEXT pdwInstalledContext,
            out string szSid)
        {
            szInstalledProductCode = Guid.Empty;
            pdwInstalledContext    = MSIINSTALLCONTEXT.MSIINSTALLCONTEXT_NONE;
            szSid = null;

            var installedProductCode = new char[39];
            MSIINSTALLCONTEXT?pdwInstalledContextLocal = MSIINSTALLCONTEXT.MSIINSTALLCONTEXT_NONE;
            int?           pcchSid = 0;
            Win32ErrorCode error   = MsiEnumProductsEx(
                szProductCode,
                szUserSid,
                dwContext,
                dwIndex,
                installedProductCode,
                ref pdwInstalledContextLocal,
                null,
                ref pcchSid);

            if (error != Win32ErrorCode.ERROR_SUCCESS)
            {
                return(error);
            }

            char[] pszSid = new char[pcchSid.Value];
            error = MsiEnumProductsEx(
                szProductCode,
                szUserSid,
                dwContext,
                dwIndex,
                installedProductCode,
                ref pdwInstalledContextLocal,
                pszSid,
                ref pcchSid);
            if (error != Win32ErrorCode.ERROR_SUCCESS)
            {
                return(error);
            }

            szInstalledProductCode = new Guid(new string(installedProductCode, 0, 38));
            pdwInstalledContext    = pdwInstalledContextLocal.Value;
            szSid = new string(pszSid, 0, pcchSid.Value);
            return(error);
        }
示例#22
0
        public NamedPipeConnection(string server, NetworkCredential credential)
        {
            // Argument validation:
            Validator.AssertNotNullOrWhiteSpace(server, "server");
            Validator.AssertNotNull(credential, "credential");

            this.Server = server;
            // Disconnect from the IPC share first in case of a preexisting connection. Ignore any errors.
            this.DoDisconnect();
            // Connect
            NetResource    resource = new NetResource(this.ShareName);
            Win32ErrorCode result   = NativeMethods.WNetAddConnection2(ref resource, credential.SecurePassword, credential.GetLogonName(), NetConnectOptions.Temporary);

            Validator.AssertSuccess(result);
        }
示例#23
0
    public unsafe void EnumProductsEx()
    {
        Guid              installedProductCode;
        string            sid;
        MSIINSTALLCONTEXT installedContext;
        Win32ErrorCode    result = MsiEnumProductsEx(
            null,
            null,
            MSIINSTALLCONTEXT.MSIINSTALLCONTEXT_ALL,
            0,
            out installedProductCode,
            out installedContext,
            out sid);

        Assert.Equal(Win32ErrorCode.ERROR_SUCCESS, result);
    }
示例#24
0
        /// <summary>
        /// Gets the text associated with a <see cref="Win32ErrorCode"/>.
        /// </summary>
        /// <param name="error">The error code.</param>
        /// <returns>The error message. Or <c>null</c> if no message could be found.</returns>
        public static unsafe string GetMessage(this Win32ErrorCode error)
        {
            int dwLanguageId = 0;

#if NETFRAMEWORK || NETSTANDARD2_0_ORLATER
            dwLanguageId = CultureInfo.CurrentCulture.LCID;
#endif

            return(FormatMessage(
                       FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM,
                       null,
                       (int)error,
                       dwLanguageId,
                       null,
                       MaxAllowedBufferSize));
        }
示例#25
0
文件: IO.cs 项目: gtrant/eraser
        /// <summary>
        /// Uses SHGetFileInfo to retrieve the icon for the given file, folder or
        /// drive.
        /// </summary>
        /// <param name="info">The file system object to query the description of.</param>
        /// <returns>An Icon object containing the bitmap</returns>
        public static Icon GetIcon(this FileSystemInfo info)
        {
            NativeMethods.SHFILEINFO shfi = new NativeMethods.SHFILEINFO();
            NativeMethods.SHGetFileInfo(info.FullName, 0, ref shfi, Marshal.SizeOf(shfi),
                                        NativeMethods.SHGetFileInfoFlags.SHGFI_SMALLICON |
                                        NativeMethods.SHGetFileInfoFlags.SHGFI_ICON);

            if (shfi.hIcon != IntPtr.Zero)
            {
                return(Icon.FromHandle(shfi.hIcon));
            }
            else
            {
                throw new IOException(string.Format(CultureInfo.CurrentCulture,
                                                    "Could not load file icon from {0}", info.FullName),
                                      Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error()));
            }
        }
    public void ThrowOnError_Win32ErrorCode()
    {
        Win32ErrorCode success = Win32ErrorCode.ERROR_SUCCESS;

        success.ThrowOnError();
        Win32ErrorCode failure = Win32ErrorCode.ERROR_FAIL_NOACTION_REBOOT;

        Assert.Throws <Win32Exception>(() => failure.ThrowOnError());

        try
        {
            failure.ThrowOnError();
            Assert.False(true, "Expected exception not thrown.");
        }
        catch (Win32Exception ex)
        {
            Assert.Equal("No action was taken as a system reboot is required", ex.Message);
        }
    }
        static internal ErrorCategory ToPSCategory(this Win32ErrorCode code)
        {
            ErrorCategory category;

            switch (code)
            {
            case Win32ErrorCode.ACCESS_DENIED:
                category = ErrorCategory.PermissionDenied;
                break;

            case Win32ErrorCode.LOGON_FAILURE:
                category = ErrorCategory.AuthenticationError;
                break;

            case Win32ErrorCode.BAD_NETPATH:
            case Win32ErrorCode.RPC_S_SERVER_UNAVAILABLE:
                category = ErrorCategory.ConnectionError;
                break;

            case Win32ErrorCode.NOT_FOUND:
            case Win32ErrorCode.NO_SUCH_USER:
            case Win32ErrorCode.NO_SUCH_DOMAIN:
            case Win32ErrorCode.NONE_MAPPED:
                category = ErrorCategory.ObjectNotFound;
                break;

            case Win32ErrorCode.PASSWORD_RESTRICTION:
                category = ErrorCategory.SecurityError;
                break;

            case Win32ErrorCode.MORE_DATA:
                category = ErrorCategory.LimitsExceeded;
                break;

            default:
                category = ErrorCategory.NotSpecified;
                break;
            }
            return(category);
        }
示例#28
0
文件: IO.cs 项目: gtrant/eraser
        /// <summary>
        /// Copies an existing file to a new file, allowing the monitoring of the progress
        /// of the copy operation.
        /// </summary>
        /// <param name="info">The <see cref="System.IO.FileSystemInfo"/> object
        /// to copy.</param>
        /// <param name="destFileName">The name of the new file to copy to.</param>
        /// <param name="progress">The progress callback function to execute</param>
        /// <returns>A new file, or an overwrite of an existing file if the file exists.</returns>
        public static FileInfo CopyTo(this FileInfo info, string destFileName,
                                      CopyProgressFunction progress)
        {
            bool cancel = false;

            NativeMethods.CopyProgressFunction callback = delegate(
                long TotalFileSize, long TotalBytesTransferred, long StreamSize,
                long StreamBytesTransferred, uint dwStreamNumber,
                NativeMethods.CopyProgressFunctionCallbackReasons dwCallbackReason,
                IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)
            {
                return(progress(TotalFileSize, TotalBytesTransferred));
            };

            if (!NativeMethods.CopyFileEx(info.FullName, destFileName, callback, IntPtr.Zero,
                                          ref cancel, 0))
            {
                throw Win32ErrorCode.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
            }

            return(new FileInfo(destFileName));
        }
 public static bool IsFor(this Win32Exception exception, Win32ErrorCode code)
 {
     return exception.NativeErrorCode == (int)code;
 }
示例#30
0
 /// <summary>
 /// Constructor. This sets the message for the exception and specifies the
 /// file whcih triggered this exception as well as the exception which
 /// is the cause of this exception.
 /// </summary>
 /// <param name="message">A <see cref="string"/> that describes the error.</param>
 /// <param name="filePath">The file which triggered this exception.</param>
 /// <param name="innerException">The exception that is the cause of the
 /// current exception. If the innerException parameter is not null, the
 /// current exception is raised in a catch block that handles the inner exception.</param>
 public SharingViolationException(string message, string filePath, Exception innerException)
     : base(message == null ?
            Win32ErrorCode.GetSystemErrorMessage(Win32ErrorCode.SharingViolation) : message,
            innerException)
 {
 }
 internal static int HResultFromWin32(Win32ErrorCode error)
 {
     return HResultFromWin32((int)error);
 }
示例#32
0
    public void InstallProduct_BadArgs()
    {
        Win32ErrorCode result = MsiInstallProduct(null, null);

        Assert.Equal(Win32ErrorCode.ERROR_INVALID_PARAMETER, result);
    }
 internal static bool Matches(int hresult, Win32ErrorCode win32ErrorCode)
 {
     return (hresult == HResultFromWin32(win32ErrorCode));
 }
示例#34
0
 internal static bool Matches(int hresult, Win32ErrorCode win32ErrorCode)
 {
     return(hresult == HResultFromWin32(win32ErrorCode));
 }