Example #1
0
        public static void connectToRemote(string remoteUNC, string username, string password, bool promptUser)
        {
            NETRESOURCE nr = new NETRESOURCE();

            nr.dwType       = RESOURCETYPE_DISK;
            nr.lpRemoteName = remoteUNC;

            int ret;

            if (promptUser)
            {
                ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
            }
            else
            {
                ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
            }

            var successfullyConnected = (ret == 0);

            if (!successfullyConnected)
            {
                // 1219 is the code for "Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed.
                var alreadyConnected = (ret == 1219);
                if (!alreadyConnected)
                {
                    var win32Exception = new System.ComponentModel.Win32Exception(ret);
                    throw new WinNetConnectionException(win32Exception.Message);
                }
            }
        }
        public static string GetLastError(bool s = false)
        {
            GetLastError();
            string errorMessage = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message;

            return(errorMessage);
        }
Example #3
0
        /// <summary>
        /// 为被管理的 Window 注册新的快捷键。
        /// </summary>
        /// <param name="fsModifiers">指定快捷键的修饰键部分。</param>
        /// <param name="key">指定快捷键的非修饰键部分。</param>
        /// <param name="handler">指定此快捷键按下时应当在 UI 线程上被调用的委托。</param>
        /// <exception cref="ArgumentNullException">当指定的委托为 null 时抛出。</exception>
        /// <exception cref="InvalidOperationException">当指定的快捷键已被注册时抛出。</exception>
        /// <exception cref="System.ComponentModel.Win32Exception">当注册快捷键遇到 Windows API 返回错误时抛出。</exception>
        public void Register(HotKeyModifiers fsModifiers, Key key, Action handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            int vk = KeyInterop.VirtualKeyFromKey(key);
            int id = GetIDFromKeyCombination(fsModifiers, vk);

            try
            {
                handlers.Add(id, handler);
            }
            catch (ArgumentException) // ID already registered
            {
                throw new InvalidOperationException("This hot key has already been registered.");
            }

            if (!WinApi.RegisterHotKey(hwnd, id, fsModifiers, unchecked ((uint)vk)))
            {
                var e = new System.ComponentModel.Win32Exception();
                handlers.Remove(id);
                throw e;
            }
        }
Example #4
0
        public async Task Start(Connection connection, ElevationRequest elevationRequest)
        {
            var exitCode = 0;

            if (Settings.SecurityEnforceUacIsolation)
            {
                throw new Exception("Attached mode not supported when SecurityEnforceUacIsolation is set.");
            }

            try
            {
                Native.ConsoleApi.SetConsoleCtrlHandler(ConsoleHelper.IgnoreConsoleCancelKeyPress, true);
                Native.ConsoleApi.FreeConsole();
                int pid = elevationRequest.ConsoleProcessId;
                if (Native.ConsoleApi.AttachConsole(pid))
                {
                    System.Environment.CurrentDirectory = elevationRequest.StartFolder;

                    try
                    {
                        var process = Helpers.ProcessFactory.StartAttached(elevationRequest.FileName, elevationRequest.Arguments);

                        WaitHandle.WaitAny(new WaitHandle[] { process.GetProcessWaitHandle(), connection.DisconnectedWaitHandle });
                        if (process.HasExited)
                        {
                            exitCode = process.ExitCode;
                        }

                        await Task.Delay(1).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await connection.ControlStream.WriteAsync($"{Constants.TOKEN_ERROR}Server Error:{ex.ToString()}\r\n{Constants.TOKEN_ERROR}").ConfigureAwait(false);

                        exitCode = Constants.GSUDO_ERROR_EXITCODE;
                    }
                }
                else
                {
                    var ex = new System.ComponentModel.Win32Exception();
                    await connection.ControlStream.WriteAsync($"{Constants.TOKEN_ERROR}Server Error: Attach Console Failed.\r\n{ex.Message}\r\n{Constants.TOKEN_ERROR}").ConfigureAwait(false);

                    Logger.Instance.Log("Attach Console Failed.", LogLevel.Error);
                    exitCode = Constants.GSUDO_ERROR_EXITCODE;
                }

                if (connection.IsAlive)
                {
                    await connection.ControlStream.WriteAsync($"{Constants.TOKEN_EXITCODE}{exitCode}{Constants.TOKEN_EXITCODE}").ConfigureAwait(false);
                }

                await connection.FlushAndCloseAll().ConfigureAwait(false);
            }
            finally
            {
                Native.ConsoleApi.SetConsoleCtrlHandler(ConsoleHelper.IgnoreConsoleCancelKeyPress, false);
                Native.ConsoleApi.FreeConsole();
                await connection.FlushAndCloseAll().ConfigureAwait(false);
            }
        }
Example #5
0
        private static void DbgHelpError(string message)
        {
            var    err          = Marshal.GetLastWin32Error();
            string errorMessage = new System.ComponentModel.Win32Exception(err).Message;

            throw new InvalidOperationException($"{message} (win32 error={err}. {errorMessage})");
        }
Example #6
0
        public override void SendResponseFromFile(IntPtr handle, long offset, long length)
        {
            if (secure || no_libc)
            {
                base.SendResponseFromFile(handle, offset, length);
                return;
            }

            try {
                Cork(true);
                SendHeaders();
                while (length > 0)
                {
                    int result = sendfile((int)socket, (int)handle, ref offset, (IntPtr)length);
                    if (result == -1)
                    {
                        var ex = new System.ComponentModel.Win32Exception();
                        if (ex.NativeErrorCode == (int)Errno.EINTR || ex.NativeErrorCode == (int)Errno.EAGAIN)
                        {
                            // If socket was not ready for sending, let's keep retrying..
                            continue;
                        }

                        throw ex;
                    }

                    // sendfile() will set 'offset' for us
                    length -= result;
                }
            } finally {
                Cork(false);
            }
        }
Example #7
0
        public void CaptureWindow(IntPtr handle)
        {
            // Get the size of the window to capture
            Rectangle rect = new Rectangle();

            GetWindowRect(handle, ref rect);

            // GetWindowRect returns Top/Left and Bottom/Right, so fix it
            rect.Width  = rect.Width - rect.X;
            rect.Height = rect.Height - rect.Y;

            // Create a bitmap to draw the capture into
            using (Bitmap bitmap = new Bitmap(rect.Width, rect.Height))
            {
                // Use PrintWindow to draw the window into our bitmap
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    IntPtr hdc = g.GetHdc();
                    if (!PrintWindow(handle, hdc, 0))
                    {
                        int error     = Marshal.GetLastWin32Error();
                        var exception = new System.ComponentModel.Win32Exception(error);
                        Debug.WriteLine("ERROR: " + error + ": " + exception.Message);
                        // TODO: Throw the exception?
                    }
                    g.ReleaseHdc(hdc);
                }

                // Save it as a .jpg just to demo this
                bitmap.Save("C:\\linscreen.jpg", ImageFormat.Jpeg);
            }
        }
Example #8
0
        Boolean EnablePrivilege(IntPtr HANDLE, string lpszPrivilege)
        {
            if (!Win32Native.LookupPrivilegeValue(null, lpszPrivilege, out luid))
            {
                return(false);
            }

            tp.PrivilegeCount = 1;
            tp.Luid           = luid;
            tp.Attributes     = Win32Native.SE_PRIVILEGE_ENABLED;

            uint retlen;
            uint buflen = (uint)System.Runtime.InteropServices.Marshal.SizeOf(tp2);

            //if (!Win32Native.AdjustTokenPrivileges(HANDLE, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero))
            if (!Win32Native.AdjustTokenPrivileges(HANDLE, false, ref tp, buflen, ref tp2, out retlen))
            {
                return(false);
            }

            if (System.Runtime.InteropServices.Marshal.GetLastWin32Error() != ERROR_NOT_ALL_ASSIGNED)
            {
                var win32Exception = new System.ComponentModel.Win32Exception();
                //throw new InvalidOperationException("AdjustTokenPrivileges failed.", win32Exception);
                return(false);
            }

            return(true);
        }
Example #9
0
        public static Exception GetWin32Exception(string reason)
        {
            string msg = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message;
            string err = String.Format("{0} failed: {1}: {2}", reason, Marshal.GetLastWin32Error(), msg);

            return(new Exception(err));
        }
Example #10
0
        public static RegistryKey OpenSubKey(RegistryKey pParentKey, string pSubKeyName,
                                             bool pWriteable,
                                             eRegWow64Options pOptions)
        {
            if (pParentKey == null || GetRegistryKeyHandle(pParentKey).Equals(System.IntPtr.Zero))
            {
                throw new System.Exception("OpenSubKey: Parent key is not open");
            }

            eRegistryRights Rights = eRegistryRights.ReadKey;

            if (pWriteable)
            {
                Rights = eRegistryRights.WriteKey;
            }

            System.IntPtr SubKeyHandle;
            System.Int32  Result = RegOpenKeyEx(GetRegistryKeyHandle(pParentKey), pSubKeyName, 0,
                                                (int)Rights | (int)pOptions, out SubKeyHandle);
            if (Result != 0)
            {
                System.ComponentModel.Win32Exception W32ex =
                    new System.ComponentModel.Win32Exception();
                throw new System.Exception("OpenSubKey: Exception encountered opening key",
                                           W32ex);
            }

            return(PointerToRegistryKey(SubKeyHandle, pWriteable, false));
        }
Example #11
0
        public static bool MMLoad(ref MM_LOAD load, string baseDirectory)
        {
            string mmLibPath = GetMultiMediaPath(baseDirectory);

            if (!string.IsNullOrEmpty(mmLibPath))
            {
                try
                {
                    if (!MMInterop.SetDllDirectory(mmLibPath))
                    {
                        Exception e = new System.ComponentModel.Win32Exception();
                        throw new DllNotFoundException("Error, Unable to load library: " + mmLibPath, e);
                    }
                    else
                    {
                        load.Size = (uint)Marshal.SizeOf(typeof(MM_LOAD));
                        mmStatus sts = mmMethods.mmLoad(ref load);
                        if (sts == mmStatus.MM_STS_NONE)
                        {
                            return(true);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
            Console.WriteLine($"Error, failed to Load mmAPI from {baseDirectory}");
            return(false);
        }
Example #12
0
        /// <summary>
        /// Try to load a native library by providing the full path including the file name of the library.
        /// </summary>
        /// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
        public static bool TryLoadFile(FileInfo file)
        {
            lock (StaticLock)
            {
                IntPtr libraryHandle;
                if (NativeHandles.Value.TryGetValue(file.Name, out libraryHandle))
                {
                    return(true);
                }

                if (!file.Exists)
                {
                    // If the library isn't found within an architecture specific folder then return false
                    // to allow normal P/Invoke searching behavior when the library is called
                    return(false);
                }

                // If successful this will return a handle to the library
                libraryHandle = IsUnix ? UnixLoader.LoadLibrary(file.FullName) : WindowsLoader.LoadLibrary(file.FullName);
                if (libraryHandle == IntPtr.Zero)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(lastError);
                    LastException = exception;
                }
                else
                {
                    LastException = null;
                    NativeHandles.Value[file.Name] = libraryHandle;
                }

                return(libraryHandle != IntPtr.Zero);
            }
        }
        /// <summary>
        /// Try to load a native library by providing the full path including the file name of the library.
        /// </summary>
        /// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
        static bool TryLoadFile(string directory, string relativePath, string fileName)
        {
            lock (StaticLock)
            {
                if (NativeHandles.Value.TryGetValue(fileName, out IntPtr libraryHandle))
                {
                    return(true);
                }

                var fullPath = Path.GetFullPath(Path.Combine(Path.Combine(directory, relativePath), fileName));
                if (!File.Exists(fullPath))
                {
                    // If the library isn't found within an architecture specific folder then return false
                    // to allow normal P/Invoke searching behavior when the library is called
                    return(false);
                }

                // If successful this will return a handle to the library
                libraryHandle = IsUnix ? UnixLoader.LoadLibrary(fullPath) : WindowsLoader.LoadLibrary(fullPath);
                if (libraryHandle == IntPtr.Zero)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(lastError);
                    LastException = exception;
                }
                else
                {
                    LastException = null;
                    NativeHandles.Value[fileName] = libraryHandle;
                }

                return(libraryHandle != IntPtr.Zero);
            }
        }
Example #14
0
        internal static string GetCurrentPackageFullName()
        {
            if (isWindows7OrLower())
            {
                System.Diagnostics.Debug.WriteLine("Appmodel packaging is not available on this version of Windows.");
                return(null);
            }
            else
            {
                StringBuilder sb     = new StringBuilder(1024);
                int           length = 0;
                int           result = GetCurrentPackageFullName(ref length, sb);

                if (result != 15700)
                {
                    sb.EnsureCapacity(length);
                    result = GetCurrentPackageFullName(ref length, sb);
                    if (result == 0)
                    {
                        return(sb.ToString());
                    }
                    else
                    {
                        System.ComponentModel.Win32Exception win32Exception = new System.ComponentModel.Win32Exception(result);
                        System.Diagnostics.Debug.WriteLine(win32Exception.Message);
                    }
                }
                else
                {
                    System.ComponentModel.Win32Exception win32Exception = new System.ComponentModel.Win32Exception(result);
                    System.Diagnostics.Debug.WriteLine(win32Exception.Message);
                }
                return(null);
            }
        }
Example #15
0
        static private IntPtr OpenVolume(string DeviceName)
        {
            uint access_rights = /* SYNCHRONIZE | */ FILE_READ_ATTRIBUTES;

            access_rights = GENERIC_READ;



            IntPtr hDevice;

            hDevice = CreateFile(
                @"\\.\" + DeviceName,
                // READ_ATTRIBUTES | GENERIC_READ | GENERIC_WRITE
                access_rights,
                FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                IntPtr.Zero,
                OPEN_EXISTING,
                0,
                IntPtr.Zero);
            if ((int)hDevice == -1)
            {
                System.ComponentModel.Win32Exception ex = new System.ComponentModel.Win32Exception();
                string errMsg = ex.Message;
                throw new Exception(ex.Message);
                throw new Exception(Marshal.GetLastWin32Error().ToString());
            }
            return(hDevice);
        }
Example #16
0
        private static IntPtr LoadLibraryExWindows(String dllname, int flags)
        {
            IntPtr handler = LoadLibraryEx(dllname, IntPtr.Zero, flags);

            if (handler == IntPtr.Zero)
            {
                int error = Marshal.GetLastWin32Error();

                System.ComponentModel.Win32Exception ex = new System.ComponentModel.Win32Exception(error);
                System.Diagnostics.Trace.WriteLine(String.Format(
                                                       "LoadLibraryEx(\"{0}\", 0, {3}) failed with error code {1}: {2}",
                                                       dllname,
                                                       (uint)error,
                                                       ex.Message,
                                                       flags));
                if (error == 5)
                {
                    System.Diagnostics.Trace.WriteLine(String.Format(
                                                           "Please check if the current user has execute permission for file: {0} ", dllname));
                }
            }
            else
            {
                System.Diagnostics.Trace.WriteLine(String.Format("LoadLibraryEx(\"{0}\", 0, {1}) successfully loaded library.", dllname, flags));
            }

            return(handler);
        }
Example #17
0
        private unsafe void readBytes(byte *buf, Int32 bytesRemaining)
        {
            int error = 0;

            Log.Write(String.Format("readBytes(): begins for {0} bytes\n", bytesRemaining));

            while (bytesRemaining > 0)
            {
                Int32 bytesThisRead = Math.Min(bytesRemaining, MaxIoSize);
                Int32 bytesRead;

                if (FileIO.ReadFile(deviceHandle, buf, bytesThisRead, &bytesRead, 0))
                {
                    buf            += bytesRead;
                    bytesRemaining -= bytesRead;
                    Log.Write(String.Format("readBytes(): ReadFile() read {0} bytes - bytesRemaining={1}\n", bytesRead, bytesRemaining));
                }
                else
                {
                    error = Marshal.GetLastWin32Error();
                    System.ComponentModel.Win32Exception ex = new System.ComponentModel.Win32Exception(error);
                    string errMsg = ex.Message;

                    Log.Write(String.Format("ReadFile: error={0} ({1}) bytesThisRead={2} bytesRemaining={3}", error, errMsg, bytesThisRead, bytesRemaining));

                    throw new System.IO.IOException(String.Format("ReadFile: error={0} ({1}) bytesThisRead={2} bytesRemaining={3}", error, errMsg, bytesThisRead, bytesRemaining));
                }
            }

            Log.Write("Read bytes(): ends\n");
        }
Example #18
0
        /// <summary>
        /// 打印输出到打印机
        /// </summary>
        /// <param name="PortName">打印机端口名称</param>
        /// <param name="Content">要打印的内容,这里输入字符串,含打印机的控制码</param>
        /// <param name="ErrorDescription"></param>
        /// <returns></returns>
        public static bool Print(string PortName, string Content, ref string ErrorDescription)
        {
            ErrorDescription = "";
            System.ComponentModel.Win32Exception we = null;

            int iHandle = CreateFile(PortName, 0x40000000, 0, 0, 3, 0, 0);

            if (iHandle == -1)
            {
                we = new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
                ErrorDescription = we.Message;
                return(false);
            }

            int        i;
            OVERLAPPED x;

            byte[] bData  = System.Text.Encoding.Default.GetBytes(Content);
            bool   Result = WriteFile(iHandle, bData, bData.Length, out i, out x);

            CloseHandle(iHandle);

            if (Result)
            {
                return(true);
            }

            we = new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
            ErrorDescription = we.Message;
            return(false);
        }
Example #19
0
        internal static void LoadRCFProtoNativeDll()
        {
            if (g_nativeDll == IntPtr.Zero)
            {
                string dllPath = "RCFProto_NET_impl.dll";
                if (g_nativeDllPath != null && g_nativeDllPath != "")
                {
                    dllPath = g_nativeDllPath;
                }

                g_nativeDll = LoadLibraryEx(dllPath, IntPtr.Zero, 8);
                if (g_nativeDll == IntPtr.Zero)
                {
                    int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    System.ComponentModel.Win32Exception win32Err = new System.ComponentModel.Win32Exception(error);
                    string errorMsg = "Unable to load RCFProto native bindings for .NET. Attempted to load: " + dllPath + ".\n";
                    errorMsg += "LoadLibraryEx() error: " + win32Err.Message + "\n";

                    // Elaborate on Windows error 193 "%1 is not a valid Win32 application" .
                    if (error == 193)
                    {
                        errorMsg += "Note: This error most likely indicates an x86/x64 architecture mismatch.\n";
                    }

                    throw new System.Exception(errorMsg);
                }
            }
        }
Example #20
0
        public static Image CaptureWindow(IntPtr handle)
        {
            // Get the size of the window to capture
            Rectangle rect = new Rectangle();

            GetWindowRect(handle, ref rect);

            // GetWindowRect returns Top/Left and Bottom/Right, so fix it
            rect.Width  = rect.Width - rect.X;
            rect.Height = rect.Height - rect.Y;

            var bitmap = new Bitmap(rect.Width, rect.Height);

            // Use PrintWindow to draw the window into our bitmap
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                IntPtr hdc = g.GetHdc();
                if (!PrintWindow(handle, hdc, 0))
                {
                    int error     = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(error);
                    Debug.WriteLine("ERROR: " + error + ": " + exception.Message);
                }
                g.ReleaseHdc(hdc);
            }
            return(bitmap);
        }
Example #21
0
        /// <summary>
        /// Connect to a network path using the given authentication parameters
        /// This function is thread safe
        /// </summary>
        /// <param name="path">Network UNC Path</param>
        /// <param name="domain">(optional) Domain</param>
        /// <param name="userName">Username</param>
        /// <param name="password">Password</param>
        private void ConnectNet(string path, string domain, string userName, string password)
        {
            string invalidParam   = "";
            int    ret            = 0;
            string noConnectError = ("Unable to connect to network location") + " " + path + "\r\n" + "Domain name:" + domain + "\r\nUsername:"******"\r\nPassword:"******"\r\n";

            Log.AppLog.WriteEntry(this, ("Attempting to connect to network share") + " " + path, Log.LogEntryType.Debug);
            try
            {
                ret = Util.Net.ConnectShare(path, domain, userName, password, out invalidParam);
            }
            catch (Exception ex)
            {
                Log.AppLog.WriteEntry(noConnectError + ex.Message, Log.LogEntryType.Error);
            }
            if (ret == 87) // Invalid Param
            {
                System.ComponentModel.Win32Exception wex = new System.ComponentModel.Win32Exception(ret);
                Log.AppLog.WriteEntry(noConnectError + wex.Message + "\r\n" + ("The invalid parameter according to Windows is ->" + invalidParam), Log.LogEntryType.Error);
            }
            else if (ret == 86)
            {
                System.ComponentModel.Win32Exception wex = new System.ComponentModel.Win32Exception(ret);
                Log.AppLog.WriteEntry(noConnectError + wex.Message + "\r\n" + ("This is most likely caused by the currently logged on user being having a drive connected to the network location.  Please disconnect all network drives to the specified network locations for MCEBuddy."), Log.LogEntryType.Error);
            }
            else if (ret != 0)
            {
                System.ComponentModel.Win32Exception wex = new System.ComponentModel.Win32Exception(ret);
                Log.AppLog.WriteEntry(noConnectError + "Return code is " + ret.ToString(System.Globalization.CultureInfo.InvariantCulture) + "\r\n" + wex.Message, Log.LogEntryType.Error);
            }
        }
        Boolean EnablePrivilege(IntPtr HANDLE,string lpszPrivilege)
        {
            if (!Win32Native.LookupPrivilegeValue(null,lpszPrivilege,out luid))
            {
                return false;
            }

            tp.PrivilegeCount = 1;
            tp.Luid = luid;
            tp.Attributes = Win32Native.SE_PRIVILEGE_ENABLED;

            uint retlen;
            uint buflen = (uint)System.Runtime.InteropServices.Marshal.SizeOf(tp2);
            //if (!Win32Native.AdjustTokenPrivileges(HANDLE, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero))
            if (!Win32Native.AdjustTokenPrivileges(HANDLE, false, ref tp, buflen, ref tp2, out retlen))
            {
                return false;
            }

            if (System.Runtime.InteropServices.Marshal.GetLastWin32Error() != ERROR_NOT_ALL_ASSIGNED)
            {
                var win32Exception = new System.ComponentModel.Win32Exception();
                //throw new InvalidOperationException("AdjustTokenPrivileges failed.", win32Exception);
                return false;
            }

            return true;
        }
Example #23
0
        /// <summary>
        /// static helper method that is used to convert Win32 DWORD error codes into strings.  
        /// Does this by creating a Win32Exception from the given win32EC error code value and then returns the Message that the exception created.
        /// </summary>
        /// <param name="win32EC">Gives the value of the Win32 Error Code that is to be converted to a string.</param>
        /// <param name="noErrorReturnStr">Gives the value to return when win32EC is zero</param>
        /// <param name="unknownErrorReturnStr">Unused - ignored.</param>
        /// <returns>noErrorReturnStr if win32EC is zero or Message from constructed Win32Exception if win32EC is not zero.</returns>
        public static string CvtWin32ECToString(int win32EC, string noErrorReturnStr, string unknownErrorReturnStr)
        {
            if (win32EC == 0)
                return noErrorReturnStr;

            System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(win32EC);
            return e.Message;
        }
Example #24
0
 public static void ConvertWin32ErrorCodes()
 {
     foreach (int errorCode in errorCodes.Keys)
     {
         System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(errorCode, string.Format("{0}", errorCodes[errorCode]));
         Console.WriteLine("Exception: {0}, Native Error Code: {1}", e, e.NativeErrorCode);
     }
 }
 internal static void ASSERT(bool result, int error)
 {
     if (!result)
     {
         var ex = new System.ComponentModel.Win32Exception(error);
         throw new OverlappedStreamException(ex.Message, ex);
     }
 }
Example #26
0
        /// <summary>
        /// Try to load a native library by providing the full path including the file name of the library.
        /// </summary>
        /// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
        static bool TryLoadFile(string directory, string relativePath, string fileName)
        {
            lock (StaticLock)
            {
                if (NativeHandles.Value.TryGetValue(fileName, out IntPtr libraryHandle))
                {
                    return(true);
                }

                var fullPath = Path.GetFullPath(Path.Combine(Path.Combine(directory, relativePath), fileName));
                if (!File.Exists(fullPath))
                {
                    // If the library isn't found within an architecture specific folder then return false
                    // to allow normal P/Invoke searching behavior when the library is called
                    return(false);
                }

#if NET5_0_OR_GREATER
                try
                {
                    if (!NativeLibrary.TryLoad(fullPath, out libraryHandle) || libraryHandle == IntPtr.Zero)
                    {
                        return(false);
                    }
                }
                catch
                {
                    return(false);
                }

                NativeHandles.Value[fileName] = libraryHandle;
                return(true);
#else
                try
                {
                    // If successful this will return a handle to the library
                    libraryHandle = IsWindows ? WindowsLoader.LoadLibrary(fullPath) : IsMac?MacLoader.LoadLibrary(fullPath) : LinuxLoader.LoadLibrary(fullPath);
                }
                catch (Exception e)
                {
                    LastException = e;
                    return(false);
                }

                if (libraryHandle == IntPtr.Zero)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(lastError);
                    LastException = exception;
                    return(false);
                }

                LastException = null;
                NativeHandles.Value[fileName] = libraryHandle;
                return(true);
#endif
            }
        }
Example #27
0
        /// <summary>Creates or deletes a route in the local computer's IPv4 routing table.</summary>
        /// <param name="add"></param>
        /// <param name="destination"></param>
        /// <param name="mask"></param>
        /// <param name="gateway"></param>
        /// <param name="index"></param>
        /// <param name="metric"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static bool ModifyIpForwardEntry(bool add, string destination, string mask, string gateway, uint index, uint metric, out string message)
        {
            var route = new MIB_IPFORWARDROW();

            if (index == 0)
            {
                message = "Network interface index not found.";
                return(false);
            }
            if (metric == 1)
            {
                message = "Metric value not found.";
                return(false);
            }

            route.dwForwardDest    = GetIPFromString(destination);
            route.dwForwardMask    = GetIPFromString(mask);
            route.dwForwardNextHop = GetIPFromString(gateway);
            route.dwForwardIfIndex = index;
            route.dwForwardMetric1 = metric;
            route.dwForwardProto   = ForwardProtocol.NetMGMT;

            int result = add ? CreateIpForwardEntry(ref route) : DeleteIpForwardEntry(ref route);

            message = string.Empty;

            if (result == ERROR_SUCCESS)
            {
                return(true);
            }

            if (result == ERROR_INVALID_PARAMETER)
            {
                route.dwForwardNextHop = 0;
                result = add ? CreateIpForwardEntry(ref route) : DeleteIpForwardEntry(ref route);
            }

            if (result == ERROR_SUCCESS)
            {
                return(true);
            }

            if (result == ERROR_OBJECT_ALREADY_EXISTS)
            {
                message = "Route already exist.";
                return(true);
            }
            if (result == ERROR_NOT_FOUND)
            {
                message = "Cannot delete or modify a route that does not exist.";
                return(true);
            }

            message = new System.ComponentModel.Win32Exception(result).Message;

            return(false);
        }
Example #28
0
        private void ReadVersionsInfo()
        {
            if (_remoteVersionsInfo != null)
                return;
#if WinXP
            bool success;
            BTH_RADIO_INFO buf;
            IntPtr radioHandle = BluetoothRadio.PrimaryRadio.Handle;
            /*
             * http://msdn.microsoft.com/en-us/library/ff536685(v=VS.85).aspx
             * The IOCTL_BTH_GET_RADIO_INFO request obtains information about the specified remote radio.
             * struct _BTH_RADIO_INFO {  ULONGLONG lmpSupportedFeatures;  USHORT    mfg;  USHORT    lmpSubversion;  UCHAR     lmpVersion;
             */
            /*
             * e.g. BTH_RADIO_INFO v1_2, 777, Broadcom, 00000808380DFEFF.
             * When no connection: INFO: IOCTL_BTH_GET_RADIO_INFO failure: 1167 = 0x48F.
             * 1167 = ERROR_DEVICE_NOT_CONNECTED
             */
            //var h = this.
            // Windows 7 IOCTL
            long bthaddr = this.DeviceAddress.ToInt64();//endian?
            buf = new BTH_RADIO_INFO();
            var len = Marshal.SizeOf(buf);
            int bytesReturned;
            success = NativeMethods.DeviceIoControl(radioHandle,
                NativeMethods.MsftWin32BthIOCTL.IOCTL_BTH_GET_RADIO_INFO,
                ref bthaddr, Marshal.SizeOf(bthaddr),
                ref buf, len, out bytesReturned, IntPtr.Zero);
            if (!success) {
                var gle = Marshal.GetLastWin32Error();
                var ex = new System.ComponentModel.Win32Exception();
                Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                    "INFO: IOCTL_BTH_GET_RADIO_INFO failure: {0} = 0x{1:X}.",
                    (InTheHand.Win32.Win32Error)gle, gle));
                Debug.Assert(gle == ex.NativeErrorCode);
                throw ex;
            } else {
                _remoteVersionsInfo = buf.ConvertToRadioVersions();
            }
#else
            LmpVersion lmpVersion; UInt16 lmpSubversion; Manufacturer mfg; LmpFeatures lmpSupportedFeatures;
            int ret = NativeMethods.BthReadRemoteVersion(
              this.DeviceAddress.ToByteArrayLittleEndian(),
              out lmpVersion, out lmpSubversion, out mfg, out lmpSupportedFeatures);
            const int ERROR_SUCCESS = 0;
            if (ret == ERROR_SUCCESS) {
                _remoteVersionsInfo = new RadioVersions(lmpVersion, lmpSubversion, lmpSupportedFeatures, mfg);
            } else {
                var gle = Marshal.GetLastWin32Error();
                var ex = new System.ComponentModel.Win32Exception(ret);
                Debug.WriteLine("BthReadRemoteVersion fail: " + ret + ", gle: " + gle);
                Debug.Assert(ret == gle, "WAS using gle but docs say use ret. Check that are the same."); 
                throw ex;
            }
#endif
        }
Example #29
0
        private void CheckError(string methodName)
        {
            Int32 err = Marshal.GetLastWin32Error();

            if (err != 0)
            {
                var tempToGetMessage = new System.ComponentModel.Win32Exception(err);
                throw new System.ComponentModel.Win32Exception(err, methodName + ": " + tempToGetMessage.ToString());
            }
        }
 public static void ThrowWin32Exception(string info, int error)
 {
     if ((error != 0) && (error != 18))
     {
         var exception = new System.ComponentModel.Win32Exception(error);
         //System.Windows.Forms.MessageBox.Show("Error: " + error.ToString() + "\n" + info);
         MessageDisplay.RaiseError(new ErrorEventArgs(exception));
         throw exception;
     }
 }
Example #31
0
        /// <summary>
        /// static helper method that is used to convert Win32 DWORD error codes into strings.
        /// Does this by creating a Win32Exception from the given win32EC error code value and then returns the Message that the exception created.
        /// </summary>
        /// <param name="win32EC">Gives the value of the Win32 Error Code that is to be converted to a string.</param>
        /// <param name="noErrorReturnStr">Gives the value to return when win32EC is zero</param>
        /// <param name="unknownErrorReturnStr">Unused - ignored.</param>
        /// <returns>noErrorReturnStr if win32EC is zero or Message from constructed Win32Exception if win32EC is not zero.</returns>
        public static string CvtWin32ECToString(int win32EC, string noErrorReturnStr, string unknownErrorReturnStr)
        {
            if (win32EC == 0)
            {
                return(noErrorReturnStr);
            }

            System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(win32EC);
            return(e.Message);
        }
        /// <summary>
        /// Gets the info block.
        /// </summary>
        /// <returns><c>true</c>, if info block was received, <c>false</c> otherwise.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="data">Data.</param>
        public Boolean GetInfoBlock(byte id, out byte[] data)
        {
            if (id == 2 || id == 3)
            {
                data    = new byte[33];
                data[0] = id;

                if (connectedToDriver)
                {
                    int attempt = 0;
                    while (attempt < 5)
                    {
                        attempt++;
                        try
                        {
                            stream.GetFeature(data, 0, data.Length);
                            break;
                        }
                        catch (System.IO.IOException e)
                        {
                            if (e.InnerException is System.ComponentModel.Win32Exception)
                            {
                                System.ComponentModel.Win32Exception win32Exception = e.InnerException as System.ComponentModel.Win32Exception;

                                if (win32Exception != null && win32Exception.NativeErrorCode == 0)
                                {
                                    return(true);
                                }
                            }

                            if (attempt == 5)
                            {
                                throw;
                            }

                            if (!WaitThread(20))
                            {
                                return(false);
                            }
                        }
                    }

                    return(true);
                }
                else
                {
                    data = new byte[0];
                    return(false);
                }
            }
            else
            {
                throw new Exception("Invalid info block id");
            }
        }
Example #33
0
        public Impersonator(string userName, string password)
        {
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_INTERACTIVE = 2;

            this._tokenHandle = IntPtr.Zero;

            // Use LogonUser to get a handle to an access token
            bool returnValue = LogonUser(userName, _DOMAIN, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref this._tokenHandle);

            if (!returnValue)
            {
                // OH NOES!!
                int ret = Marshal.GetLastWin32Error();
                System.ComponentModel.Win32Exception up = new System.ComponentModel.Win32Exception(ret);
                throw up; // he he
            }
        }
        public static RegistryKey OpenSubKey(RegistryKey pParentKey, string pSubKeyName,
                                             bool pWriteable,
                                             eRegWow64Options pOptions)
        {
            if (pParentKey == null || GetRegistryKeyHandle(pParentKey).Equals(System.IntPtr.Zero))
                throw new System.Exception("OpenSubKey: Parent key is not open");

            eRegistryRights Rights = eRegistryRights.ReadKey;
            if (pWriteable)
                Rights = eRegistryRights.WriteKey;

            System.IntPtr SubKeyHandle;
            System.Int32 Result = RegOpenKeyEx(GetRegistryKeyHandle(pParentKey), pSubKeyName, 0,
                                              (int)Rights | (int)pOptions, out SubKeyHandle);
            if (Result != 0)
            {
                System.ComponentModel.Win32Exception W32ex =
                    new System.ComponentModel.Win32Exception();
                throw new System.Exception("OpenSubKey: Exception encountered opening key",
                    W32ex);
            }

            return PointerToRegistryKey(SubKeyHandle, pWriteable, false);
        }
Example #35
0
        /// <summary>
        /// Connect to a network path using the given authentication parameters
        /// This function is thread safe
        /// </summary>
        /// <param name="path">Network UNC Path</param>
        /// <param name="domain">(optional) Domain</param>
        /// <param name="userName">Username</param>
        /// <param name="password">Password</param>
        private void ConnectNet(string path, string domain, string userName, string password)
        {
            string invalidParam = "";
            int ret = 0;
            string noConnectError = ("Unable to connect to network location") + " " + path + "\r\n" + "Domain name:" + domain + "\r\nUsername:"******"\r\nPassword:"******"\r\n";

            Log.AppLog.WriteEntry(this, ("Attempting to connect to network share")+ " " + path, Log.LogEntryType.Debug);
            try
            {
                ret = Util.Net.ConnectShare(path, domain, userName, password, out invalidParam);
            }
            catch (Exception ex)
            {
                Log.AppLog.WriteEntry(noConnectError + ex.Message, Log.LogEntryType.Error);
            }
            if (ret == 87) // Invalid Param
            {
                System.ComponentModel.Win32Exception wex = new System.ComponentModel.Win32Exception(ret);
                Log.AppLog.WriteEntry(noConnectError + wex.Message + "\r\n" + ("The invalid parameter according to Windows is ->" + invalidParam), Log.LogEntryType.Error);
            }
            else if (ret == 86)
            {
                System.ComponentModel.Win32Exception wex = new System.ComponentModel.Win32Exception(ret);
                Log.AppLog.WriteEntry(noConnectError + wex.Message + "\r\n" + ("This is most likely caused by the currently logged on user being having a drive connected to the network location.  Please disconnect all network drives to the specified network locations for MCEBuddy."), Log.LogEntryType.Error);
            }
            else if (ret != 0)
            {
                System.ComponentModel.Win32Exception wex = new System.ComponentModel.Win32Exception(ret);
                Log.AppLog.WriteEntry(noConnectError + "Return code is " + ret.ToString(System.Globalization.CultureInfo.InvariantCulture) + "\r\n" + wex.Message, Log.LogEntryType.Error);
            }
        }
        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;
                }
            }
        }
        /// <summary>
        /// Try to load a native library by providing the full path including the file name of the library.
        /// </summary>
        /// <returns>True if the library was successfully loaded or if it has already been loaded.</returns>
        public static bool TryLoadFile(FileInfo file)
        {
            lock (StaticLock)
            {
                IntPtr libraryHandle;
                if (NativeHandles.Value.TryGetValue(file.Name, out libraryHandle))
                {
                    return true;
                }

                if (!file.Exists)
                {
                    // If the library isn't found within an architecture specific folder then return false
                    // to allow normal P/Invoke searching behavior when the library is called
                    return false;
                }

                // If successful this will return a handle to the library
                libraryHandle = IsUnix ? UnixLoader.LoadLibrary(file.FullName) : WindowsLoader.LoadLibrary(file.FullName);
                if (libraryHandle == IntPtr.Zero)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    var exception = new System.ComponentModel.Win32Exception(lastError);
                    LastException = exception;
                }
                else
                {
                    LastException = null;
                    NativeHandles.Value[file.Name] = libraryHandle;
                }

                return libraryHandle != IntPtr.Zero;
            }
        }
Example #38
0
        private void ThrowErrorRemoting(int stat)
        {
            if (this.Host.Name.Equals("ServerRemoteHost", StringComparison.OrdinalIgnoreCase))
            {
                Exception e = new System.ComponentModel.Win32Exception(stat);
                String error = e.Message;
                string message = CertificateProviderStrings.RemoteErrorMessage;
                error += message;

                Exception e2 = new Exception(error);
                ThrowTerminatingError(
                        new ErrorRecord(
                            e2,
                            "RemotingFailure",
                            ErrorCategory.NotSpecified,
                            null));
            }
            else
            {
                throw new System.ComponentModel.Win32Exception(stat);
            }
        }
Example #39
0
        /// Intro to DCs:  
        /// If you are familiar, skip ahead. If not, read on.
        /// Device contexts are just generic ways to represent devices,
        /// or things you can draw on or interact with graphically. 
        /// This is hugely over simplified, and I'm going to get flamed, but for the sake of brevity,
        /// let's just go with that for now. You can get device context's, or dc's as 
        /// they are commonly referred to, from images, windows, monitors, and even printers. 
        /// Every window has them, and you can use them to draw with. Everything you see on your screen is being 
        /// drawn upon a device context. The desktop, every window, your taskbar, and anything you see. 
        /// You can draw upon them, or copy what they have drawn upon them. If you can get a hold of them, 
        /// you can pretty much draw or steal whatever you want graphically speaking. 
        /// Working with device contexts is fast, and both GDI and GDI+ are based on them.
        /// in the case of capturing the screen, we know that somewhere Windows is drawing upon a device context, so that we can see it. 
        /// In fact, there's one for each monitor you have attached to your system, and that desktop that you are seeing on it, 
        /// is being drawn on that monitor's device context. 
        /// All we have to do is grab a hold of that device context, create another one of our own, 
        /// and copy the screen's device context image data to our own, and we've got a screen capture
        /// 
        public static Bitmap GetDesktopWindowCaptureAsBitmap()
        {
            //SEE HOW THIS FUNCTION WORKS AT THE END OF THIS FUNCTION.
            Rectangle rcScreen = Rectangle.Empty;
            Screen[] screens = Screen.AllScreens;

            // Create a rectangle encompassing all screens...
            foreach (Screen screen in Screen.AllScreens)
            rcScreen = Rectangle.Union(rcScreen, screen.Bounds);

            // Create a composite bitmap of the size of all screens...
            Bitmap finalBitmap = new Bitmap(rcScreen.Width, rcScreen.Height);

            // Get a graphics object for the composite bitmap and initialize it...
            Graphics g = Graphics.FromImage(finalBitmap);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
            g.FillRectangle(
               SystemBrushes.Desktop,
               0,
               0,
               rcScreen.Width - rcScreen.X,
               rcScreen.Height - rcScreen.Y);

            // Get an HDC for the composite area...
            IntPtr hdcDestination = g.GetHdc();

            // Now, loop through screens,
            // Blting each to the composite HDC created above...
            foreach (Screen screen in Screen.AllScreens)
            {
            // Create DC for each source monitor...
            IntPtr hdcSource = Win32.CreateDC(
              IntPtr.Zero,
              screen.DeviceName,
              IntPtr.Zero,
              IntPtr.Zero);

            // Blt the source directly to the composite destination...
            int xDest = screen.Bounds.X - rcScreen.X;
            int yDest = screen.Bounds.Y - rcScreen.Y;

            bool success = Win32.StretchBlt(
              hdcDestination,
              xDest,
              yDest,
              screen.Bounds.Width,
              screen.Bounds.Height,
              hdcSource,
              0,
              0,
              screen.Bounds.Width,
              screen.Bounds.Height,
              (int)Win32.TernaryRasterOperations.SRCCOPY);

            //  System.Diagnostics.Trace.WriteLine(screen.Bounds);

            if (!success)
            {
                System.ComponentModel.Win32Exception win32Exception =
                    new System.ComponentModel.Win32Exception();
                System.Diagnostics.Trace.WriteLine(win32Exception);
            }

            // Cleanup source HDC...
            Win32.DeleteDC(hdcSource);
            }

            // Cleanup destination HDC and Graphics...
            g.ReleaseHdc(hdcDestination);
            g.Dispose();

            // Return composite bitmap which will become our Form's PictureBox's image...
            return finalBitmap;

            ///Looking at the code, the first thing you'll see is that I'm using a mixture of GDI and GDI+.
            ///This is due largely to the fact that there is a bug present in GDI+ and the BtBlt API.
            ///This issue only manifests itself on systems with multiple monitors, and if I remember correctly,
            ///the system had to have a NVida display adapter on the non-primary monitor, and of course, our old friend Windows 98 running as the OS.
            ///What happens is the primary monitor captures fine, the secondary (or any non-primary) monitor stands a chance of returning garbage for an image.
            ///It looks like cable channel with no signal.

            ///Instead of relying on purely managed code, do copy the images,
            ///or backing up to the BtBlt API, we instead fall back to it's somewhat slower cousin, StretchBlt.

            ///first up we just grab all of the monitors using the Screen class' AllScreens property.
            ///This does two things for us. First it allows us to figure out how big the entire desktop is,
            ///and create an image just big enough to hold all of the screens inside.
            ///And secondly, it allows us to figure out just where each monitor is positioned in relation to the other.
            ///Remember, with multiple monitor support you can "arrange" your monitors in different ways,
            ///and with different resolutions, so don't think in terms of a pure rectangle when you think of
            ///how your monitors are positioned.

            ///Once we have those screens, it's a trivial matter to calculate the size of the entire bitmap
            ///by using the Rectangle.Union method to build up the size of the overall image.
            ///After we've figured out the size of the final image, we'll grab a Graphics object from the image.
            ///The GDI+ Graphics object is just the .NET wrapper around a device context.
            ///Using that graphics context, we can draw on the bitmap with the graphics object.

            ///Next, we'll enumerate through each monitor, and draw what that monitor has on it's device context,
            ///upon the image we just created that will hold the final screen shot.
            ///Well draw it using it's coordinates so that in case the monitors have different resolutions or positioning
            ///we'll be able to see them as the Display Control Panel applet sees them.
            ///Go check it out if you have multiple monitors, and you didn't know you could move them.
            ///Chances are there if you have multiple monitors, you know this already, but if not so harm no foul.
            ///Open the settings tab and drag one of the monitors around and
            ///you'll see you can reposition it in relation to the other monitors.

            ///For each monitor, we'll simply use the StretchBlt API to copy that monitor's device context contents,
            ///to the bitmap that will serve as the screen capture of the desktop.
            ///Notice that I'm creating a device context each time, this gives us access to that monitor's device context so
            ///that we can copy from it. Keep in mind that if we create it, we must destroy it,
            ///so we delete the device context when we are finished with it. If you don't, you'll have a memory leak,
            ///so keep a watchful eye on your dc's and make sure to release or destroy them.
            ///A simple rule is, if you "acquire" it, you're required to "release" it.
            ///And if you "create" it, then you must "destroy" it.
            ///I quote those because if you look at the GDI APIs, with that in mind you'll find the necessary APIs to do exactly what you want.

            ///Finally, after copying the contents of each device context to that bitmap we created,
            ///we'll release the Graphics object we acquired from the bitmap, and dispose it.
            ///That's the proper way to clean up a graphics object, if you've acquired a device context from it.
        }
        internal static void VerifySuccess(bool success, string format, params object[] args)
        {
            if (success)
                return;

            string msg = args == null || args.Length == 0 ? format : string.Format(format, args);

            int errorCode = Marshal.GetLastWin32Error();
            Exception inner = new System.ComponentModel.Win32Exception(errorCode);
            string errMessage = string.Format("{2} while {0}: LastError = {1} (0x{1:X})",
                                                msg, errorCode, inner.Message);

            throw new ApplicationException(errMessage, inner);
        }
        /// <summary>
        /// Only called from GetRouterPhysicalAddress()
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private PhysicalAddress GetHardwareAddressForIPv4Address(IPAddress ip, out Exception e)
        {
            if (ip == null)
            {
                e = new ArgumentNullException();
                return null;
            }

            if (ip.AddressFamily != AddressFamily.InterNetwork)
            {
                e = new ArgumentException("Only supports IPv4 addresses");
                return null;
            }

            UInt32 dstAddrInt = BitConverter.ToUInt32(ip.GetAddressBytes(), 0);
            UInt32 srcAddrInt = 0;

            byte[] mac = new byte[6]; // 48 bit
            int length = mac.Length;
            int reply = Win32.SendARP(dstAddrInt, srcAddrInt, mac, ref length);

            if (reply != 0)
            {
                e = new System.ComponentModel.Win32Exception(reply);
                return null;
            }

            e = null;
            return new PhysicalAddress(mac);
        }
Example #42
0
 protected override IntPtr HookProcess(int nCode, IntPtr wParam, IntPtr lParam)
 {
     if (EnableEvents)
     {
         // If ok and someone listens to our events
         if (nCode >= 0)
         {
             var info = new CURSORINFO();
             info.Size = Marshal.SizeOf(info.GetType());
             if (!GetCursorInfo(out info))
             {
                 var ex = new System.ComponentModel.Win32Exception();
                 throw new Exception(ex.Message);
             }
             var button = MouseButtons.None;
             var param = wParam.ToInt32();
             // Marshall the data from callback.
             var mStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
             var delta = 0;
             var tu = new TestUnion { Number = mStruct.mouseData };
             MouseKey mk = 0;
             int lastX = 0;
             int lastY = 0;
             bool handled;
             switch (param)
             {
                 case WM_MOUSEMOVE:
                     var x = mStruct.pt.x;
                     var y = mStruct.pt.y;
                     if (prevX == -1 || prevY == -1)
                     {
                         scrnX = SystemInformation.VirtualScreen.Width - 1;
                         scrnY = SystemInformation.VirtualScreen.Height - 1;
                         prevX = x;
                         prevY = y;
                     }
                     lastX = x - prevX;
                     lastY = y - prevY;
                     var fX = (int)Math.Max(Math.Min(scrnX, x), 0);
                     var fY = (int)Math.Max(Math.Min(scrnY, y), 0);
                     if (fX != x || fY != y) SetCursorPos(fX, fY);
                     prevX = fX;
                     prevY = fY;
                     break;
                 case WM_LBUTTONDOWN:
                 case WM_LBUTTONUP:
                 case WM_LBUTTONDBLCLK:
                     button = MouseButtons.Left;
                     break;
                 case WM_MBUTTONDOWN:
                 case WM_MBUTTONUP:
                 case WM_MBUTTONDBLCLK:
                     button = MouseButtons.Middle;
                     break;
                 case WM_RBUTTONDOWN:
                 case WM_RBUTTONUP:
                 case WM_RBUTTONDBLCLK:
                     button = MouseButtons.Right;
                     break;
                 case WM_XBUTTONDOWN:
                 case WM_XBUTTONUP:
                 case WM_XBUTTONDBLCLK:
                     button = MouseButtons.XButton1;
                     if (tu.High == 1) mk = MouseKey.MK_XBUTTON1;
                     if (tu.High == 2) mk = MouseKey.MK_XBUTTON2;
                     break;
                 case WM_NCXBUTTONDOWN:
                 case WM_NCXBUTTONUP:
                 case WM_NCXBUTTONDBLCLK:
                     button = MouseButtons.XButton2;
                     if (tu.High == 1) mk = MouseKey.MK_XBUTTON1;
                     if (tu.High == 2) mk = MouseKey.MK_XBUTTON2;
                     break;
                 case WM_MOUSEWHEEL:
                 case WM_MOUSEHWHEEL:
                     delta = (int)tu.High;
                     mk = (MouseKey)tu.ULow;
                     break;
                 case WM_TOUCH:
                     try
                     {
                         handled = DecodeTouch(wParam, lParam);
                     }
                     catch (Exception ex)
                     {
                         if (OnError != null) OnError(this, new UnhandledExceptionEventArgs(ex, false));
                     }
                     break;
             }
             var ea = new MouseHookEventArgs(mStruct, info, mk, param, lastX, lastY);
             if (OnMouseHook != null) OnMouseHook(this, ea);
             int clickCount = 0;
             if (button != MouseButtons.None) clickCount = (param == WM_LBUTTONDBLCLK || param == WM_RBUTTONDBLCLK) ? 2 : 1;
             var e = new MouseEventArgs(button, clickCount, mStruct.pt.x, mStruct.pt.y, delta);
             // Raise Events.
             if (OnMouseUp != null && (param == WM_LBUTTONUP || param == WM_MBUTTONUP || param == WM_RBUTTONUP || param == WM_XBUTTONUP || param == WM_NCXBUTTONUP)) OnMouseUp(this, e);
             else if (OnMouseDown != null && (param == WM_LBUTTONDOWN || param == WM_MBUTTONDOWN || param == WM_RBUTTONDOWN || param == WM_XBUTTONDOWN || param == WM_NCXBUTTONDOWN)) OnMouseDown(this, e);
             else if (OnMouseMove != null && (param == WM_MOUSEMOVE)) OnMouseMove(this, e);
             else if (OnMouseWheel != null) OnMouseWheel(this, e);
             else if (OnMouseActivity != null) OnMouseActivity(this, e);
         }
     }
     return CallNextHookEx(hHook, nCode, wParam, lParam);
 }
        internal static string SafeGetFullPathName(string path)
        {
            Debug.Assert(path != null, "path is null?");
            // make sure to test for Int16.MaxValue limit before calling this method
            // see the below comment re GetLastWin32Error for the reason
            Debug.Assert(path.Length < Int16.MaxValue);

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

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

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

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

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

            return buffer.ToString();
        }
Example #44
0
        /// <summary>
        /// Creates a new MSBuild process
        /// </summary>
        private int LaunchNode(string msbuildLocation, string commandLineArgs)
        {
            // Should always have been set already. 
            ErrorUtilities.VerifyThrowInternalLength(msbuildLocation, "msbuildLocation");

            if (!File.Exists(msbuildLocation))
            {
                throw new BuildAbortedException(ResourceUtilities.FormatResourceString("CouldNotFindMSBuildExe", msbuildLocation));
            }

            // Repeat the executable name as the first token of the command line because the command line
            // parser logic expects it and will otherwise skip the first argument
            commandLineArgs = msbuildLocation + " " + commandLineArgs;

            BackendNativeMethods.STARTUP_INFO startInfo = new BackendNativeMethods.STARTUP_INFO();
            startInfo.cb = Marshal.SizeOf<BackendNativeMethods.STARTUP_INFO>();

            // Null out the process handles so that the parent process does not wait for the child process
            // to exit before it can exit.
            uint creationFlags = BackendNativeMethods.NORMALPRIORITYCLASS;
            startInfo.dwFlags = BackendNativeMethods.STARTFUSESTDHANDLES;

            if (String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MSBUILDNODEWINDOW")))
            {
                startInfo.hStdError = BackendNativeMethods.InvalidHandle;
                startInfo.hStdInput = BackendNativeMethods.InvalidHandle;
                startInfo.hStdOutput = BackendNativeMethods.InvalidHandle;
                creationFlags = creationFlags | BackendNativeMethods.CREATENOWINDOW;
            }
            else
            {
                creationFlags = creationFlags | BackendNativeMethods.CREATE_NEW_CONSOLE;
            }

            BackendNativeMethods.SECURITY_ATTRIBUTES processSecurityAttributes = new BackendNativeMethods.SECURITY_ATTRIBUTES();
            BackendNativeMethods.SECURITY_ATTRIBUTES threadSecurityAttributes = new BackendNativeMethods.SECURITY_ATTRIBUTES();
            processSecurityAttributes.nLength = Marshal.SizeOf< BackendNativeMethods.SECURITY_ATTRIBUTES>();
            threadSecurityAttributes.nLength = Marshal.SizeOf<BackendNativeMethods.SECURITY_ATTRIBUTES>();

            BackendNativeMethods.PROCESS_INFORMATION processInfo = new BackendNativeMethods.PROCESS_INFORMATION();

            string appName = msbuildLocation;

            CommunicationsUtilities.Trace("Launching node from {0}", msbuildLocation);
            bool result = BackendNativeMethods.CreateProcess
                (
                    msbuildLocation,
                    commandLineArgs,
                    ref processSecurityAttributes,
                    ref threadSecurityAttributes,
                    false,
                    creationFlags,
                    BackendNativeMethods.NullPtr,
                    null,
                    ref startInfo,
                    out processInfo
                );

            if (!result)
            {
                // Creating an instance of this exception calls GetLastWin32Error and also converts it to a user-friendly string.
                System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception();

                CommunicationsUtilities.Trace
                    (
                        "Failed to launch node from {0}. System32 Error code {1}. Description {2}. CommandLine: {2}",
                        msbuildLocation,
                        e.NativeErrorCode.ToString(CultureInfo.InvariantCulture),
                        e.Message,
                        commandLineArgs
                    );

                throw new NodeFailedToLaunchException(e.NativeErrorCode.ToString(CultureInfo.InvariantCulture), e.Message);
            }

            CommunicationsUtilities.Trace("Successfully launched msbuild.exe node with PID {0}", processInfo.dwProcessId);
            return processInfo.dwProcessId;
        }
Example #45
0
		/// <summary>
		/// Gets the platform exception relative to the last operation performed.
		/// </summary>
		/// <param name="deviceContext">
		/// A <see cref="IDeviceContext"/> that specifies the device context on which an error occurred.
		/// </param>
		/// <returns>
		/// The platform exception relative to the last operation performed.
		/// </returns>
		/// <exception cref="NotSupportedException">
		/// Exception thrown if the current platform is not supported.
		/// </exception>
		public static Exception GetPlatformException(IDeviceContext deviceContext)
		{
			Exception platformException = null;

			switch (Environment.OSVersion.Platform) {
#if OPENGL_NET_SUPPORT_WGL
				case PlatformID.Win32Windows:
				case PlatformID.Win32NT: {
						int win32Error = Marshal.GetLastWin32Error();
						if (win32Error != 0)
							platformException = new System.ComponentModel.Win32Exception(win32Error);
					}
					break;
#endif

#if OPENGL_NET_SUPPORT_GLX
				case PlatformID.Unix: {
						XServerDeviceContext x11DeviceContext = (XServerDeviceContext)deviceContext;

						lock (mDisplayErrorsLock) {
							platformException = mDisplayErrors[x11DeviceContext.Display];
							mDisplayErrors[x11DeviceContext.Display] = null;
						}
					}
					break;
#endif
				default:
					throw new NotSupportedException(String.Format("{0} not supported", Environment.OSVersion.Platform));
			}

			return (platformException);
		}
Example #46
0
 public static string GetLastWin32Error()
 {
     string errmsg = new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()).Message;
     return string.IsNullOrWhiteSpace(errmsg) ? string.Empty : errmsg;
 }
Example #47
0
        public Task<long> ExtractDiskAsync(SystemDevice device, string outputFile, IProgress<double> progress, CancellationToken token)
        {
            if (deviceBuilder.IfUserAdmin() == false)
            {
                throw new System.Security.SecurityException("User must be administrator to access the hardware. Please re-login");
            }

            //
            // If bufferSize will be tooo small (like: 512 bytes) the iteration of ReadFile will fail with E_FAIL or some SEH exception :(
            int sectorsReadAtOnce = Convert.ToInt32(device.SectorsCount / 100) + 1; // in 'sectors' not bytes !
            int bufferSize = sectorsReadAtOnce * device.BytesPerSector;
            //

            // Align to 512 exactly
            //while (bufferSize % device.BytesPerSector != 0)
            //    bufferSize--;

            byte[] buffer = new byte[bufferSize];
            long bytesRead = 0;
            uint lpNumberOfBytesRead = 0;
            bool functionResult = false;
            int win32err = 0;
            NativeOverlapped nativeOverlapped = new NativeOverlapped();

            SystemDevice device2 = new SystemDevice("\\\\.\\PhysicalDrive" + device.DeviceNumber);
            GCHandle gcHandle = new GCHandle();

            return Task.Factory.StartNew<long>(() => {
                try
                {
                    IntPtr deviceHandle = device2.OpenDeviceHandle();
                    gcHandle = GCHandle.Alloc(deviceHandle);        // So it won't be collected by GC while I'm doing PInvoke

                    BinaryWriter writer = GetOutputStream(outputFile);

                    while(true)
                    {
                        functionResult = UnsafeNativeMethods.ReadFile(deviceHandle, buffer, Convert.ToUInt32(buffer.Length), ref lpNumberOfBytesRead, ref nativeOverlapped);
                        win32err = Marshal.GetLastWin32Error();

                        if (functionResult)
                        {
                            bytesRead += lpNumberOfBytesRead;

                            writer.Write(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            if (win32err == UnsafeNativeMethods.ERROR_SECTOR_NOT_FOUND)
                            {
                                // This is a device black-hole
                                // try to squeeze as much as I can
                                if (bufferSize == device.BytesPerSector)
                                {
                                    // That's the last one
                                    break;
                                }
                                else
                                {
                                    bufferSize = device.BytesPerSector;
                                    buffer = new byte[bufferSize];
                                }
                            }
                            else
                            {
                                throw new System.ComponentModel.Win32Exception(win32err);
                            }
                        }

                        if (progress != null)
                        {
                            progress.Report(Math.Round((double)((bytesRead * 100) / device.DiskSize.Value)));
                        }

                        // Must not (!) increase position - everything will be read to NULL
                        //deviceStream.Position = iCounter;

                        if (bytesRead + bufferSize > device.DiskSize.Value)
                        {
                            if (device.DiskSize.Value == bytesRead)
                            {
                                // all done
                                break;
                            }
                            else
                            {
                                // Collect leftovers
                                buffer = new byte[(bytesRead + bufferSize) - device.DiskSize.Value];
                            }
                        }

                        GC.KeepAlive(deviceHandle);
                    }

                    writer.Flush();

                    gcHandle.Free();

                    device.CloseDeviceHandle();

                    return bytesRead;
                }
                catch (SEHException seh)
                {
                    gcHandle.Free();
                    System.Diagnostics.Trace.WriteLine("[]--- SEHException in ExtractDiskAsync(): " + seh.ToString());
                    return 0;
                }
                catch (Exception exp_gen)
                {
                    gcHandle.Free();

                    if (win32err == 0)
                    {
                        win32err = Marshal.GetLastWin32Error();
                    }

                    var zz = new System.ComponentModel.Win32Exception(win32err);
                    System.Diagnostics.Trace.WriteLine("[]--- Exception in ExtractDiskAsync(): " + exp_gen.ToString());
                    System.Diagnostics.Trace.WriteLine("[]--- Exception in ExtractDiskAsync() (native) : " + zz.ToString());
                    return 0;
                }
            }
            , token);
        }
Example #48
0
 internal static void ThrowWin32Exception()
 {
     System.ComponentModel.Win32Exception ex = new System.ComponentModel.Win32Exception();
     if (ex.NativeErrorCode != 0) throw ex;
 }
Example #49
0
 protected void InstallHook(HookType hookType)
 {
     lock (HookLock)
     {
         // If hook is installed already then return.
         _hookType = hookType;
         if (hHook.Handle != IntPtr.Zero) return;
         string lpModuleName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
         var hMod = GetModuleHandle(lpModuleName);
         var hRef = new HandleRef(this, hMod);
         HookProcedure = new HookProc(HookProcess);
         var kh = SetWindowsHookEx((int)hookType, HookProcedure, hRef, 0);
         if (kh == IntPtr.Zero)
         {
             var ex = new System.ComponentModel.Win32Exception();
             throw new Exception(ex.Message);
         }
         hHook = new HandleRef(null, kh);
     }
 }
Example #50
0
        private bool OnDeviceDataReceived(byte[] bytes)
        {
            int length = bytes.Length;
            if (length > 0) 
            {
                HCI_TYPE hciType = (HCI_TYPE)bytes[0];

                // send command/data to bluetooth device...
                int lastError = 0;
                int ret = BthRuntime.SendHCICommand(devId, bytes, (uint)bytes.Length);

                string result = GlobalData.OK;
                if (ret == 0)
                {
                    lastError = Marshal.GetLastWin32Error();
                    string errMsg = new System.ComponentModel.Win32Exception(lastError).Message;
                    result = string.Format("Fail: {0} ({1})", lastError, errMsg);
                }

                // send error code to device...
                CommandPacket cmd = new CommandPacket();
                cmd.CommandId = (uint)PACKET_TYPE.HCI_DATA_ERROR_PACKET;
                cmd.AddParameterDWORD((uint)lastError);
                SendCommand(cmd);

                // add log entry.
                AddCommLog(hciType.ToString(), bytes, bytes.Length, result);
            }

            return false;            
        }
Example #51
0
 protected static string CreateMessage(int errorcode)
 {
     System.ComponentModel.Win32Exception temp = new System.ComponentModel.Win32Exception(errorcode);
     return temp.Message;
 }
Example #52
0
		/// <summary>
		/// The XServer error handler, invoked each time a X/GLX routine raise an error.
		/// </summary>
		/// <param name="DisplayHandle">
		/// A <see cref="IntPtr"/> that specifies the handle of the display on which the error occurred.
		/// </param>
		/// <param name="error_event">
		/// A <see cref="Glx.XErrorEvent"/> that describe the error.
		/// </param>
		/// <returns>
		/// It returns always 0.
		/// </returns>
		internal static int XServerErrorHandler(IntPtr DisplayHandle, ref Glx.XErrorEvent error_event)
		{
			lock (mDisplayErrorsLock) {
				StringBuilder sb = new StringBuilder(1024);
				Glx.XGetErrorText(DisplayHandle, error_event.error_code, sb, 1024);

				string eventName = Enum.GetName(typeof(Glx.XEventName), error_event.type);
				string requestName = Enum.GetName(typeof(Glx.XRequest), error_event.request_code);

				if (String.IsNullOrEmpty(eventName))
					eventName = "Unknown";
				if (String.IsNullOrEmpty(requestName))
					requestName = "Unknown";

				// Additional details
				sb.AppendLine("\nX error details:");
				sb.AppendFormat("	X event name: '{0}' ({1})\n", eventName, error_event.type);
				sb.AppendFormat("	Display: 0x{0}\n", error_event.display.ToInt64().ToString("x"));
				sb.AppendFormat("	Resource ID: {0}\n", error_event.resourceid.ToInt64().ToString("x"));
				sb.AppendFormat("	Error code: {0}\n", error_event.error_code);
				sb.AppendFormat("	Major code: '{0}' ({1})\n", requestName, error_event.request_code);
				sb.AppendFormat("	Minor code: {0}", error_event.minor_code);

				mDisplayErrors[DisplayHandle] = new System.ComponentModel.Win32Exception(error_event.error_code, sb.ToString());
			}

			return (0);
		}
Example #53
0
        public static void connectToRemote(string remoteUNC, string username, string password, bool promptUser)
        {
            NETRESOURCE nr = new NETRESOURCE();
            nr.dwType = RESOURCETYPE_DISK;
            nr.lpRemoteName = remoteUNC;

            int ret;
            if (promptUser)
                ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
            else
                ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

            var successfullyConnected = (ret == 0);
            if (!successfullyConnected)
            {
                // 1219 is the code for "Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed.
                var alreadyConnected = (ret == 1219);
                if (!alreadyConnected)
                {
                    var win32Exception = new System.ComponentModel.Win32Exception(ret);
                    throw new WinNetConnectionException(win32Exception.Message);
                }
            }
        }
Example #54
0
        private ISample _next(ISample sample, out bool err)
        {
            try
            {
                //            if (_gain == 0) Gain = 1;
                _sampleCount++;

                if (!_ignoreclipping && (_sampleCount % _sr == 0))
                {
                    // Every second, check for clipping and wind back the gain by 0.5dB if so
                    bool clipped = false;
                    for (int n = 0; n < _nc; n++)
                    {
                        if (_ditherProcessors[n].clipping)
                        {
                            clipped = true;
                        }
                    }
                    if (clipped)
                    {
                        // Reduce gain by 0.5dB to back off from clipping
                        Gain = _gain * 0.94406087628592338036438049660227;
                        //                            Trace.WriteLine("Gain {0} dB", MathUtil.dB(_gain));
                        for (int n = 0; n < _nc; n++)
                        {
                            _ditherProcessors[n].clipping = false;
                        }
                    }
                }

                for (int n = 0; n < _nc; n++)
                {
                    // dither processor does the float-to-PCM conversion
                    // (dither is not applied to 32-f output, only to PCM)
                    double val = sample[n];

                    if (_gain != 0 && !double.IsNaN(_gain))
                    {
                        val *= _gain;
                    }
                    if (_gains != null && !double.IsNaN(_gains[n]))
                    {
                        val *= _gains[n];
                    }

                    switch (_bitsPerSample)
                    {
                        case 8:
                            _w.Write((byte)(_ditherProcessors[n].process(val) + 127));
                            break;
                        case 16:
                            _w.Write((short)_ditherProcessors[n].process(val));
                            break;
                        case 24:
                            // Little-endian, signed 24-bit
                            int c = _ditherProcessors[n].process(val);
                            _w.Write((ushort)(c & 0xFFFF));
                            _w.Write((sbyte)(c >> 16 & 0xFF));
                            break;
                        case 32:
                            if (_audioFormat == WaveFormat.PCM || _audioFormat == WaveFormat.EXTENSIBLE)
                            {
                                _w.Write((int)_ditherProcessors[n].process(val));
                            }
                            else if (_audioFormat == WaveFormat.IEEE_FLOAT)
                            {
                                // Internals are double; just cast to float and discard any extra resolution
                                // (really we should dither here too, to approx 24 bits?)
                                _w.Write((float)val);
                            }
                            break;
                        case 64:
                            // we only do float, not PCM, 64-bits
                            _w.Write((double)val);
                            break;
                        default:
                            throw new Exception(String.Format("Bits per sample cannot be {0}", BitsPerSample));
                    }
                }

                err = false;
                if (_isConsole)
                {
                    // Check the stdout stream is still alive
                    int Err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    if (Err != 0)
                    {
                        // Err 997: "Overlapped I/O is in progress" (don't know cause)
                        // Err 183: cannot create a file... caused in Trace
                        // Err 2:   cannot find a file... caused in Trace
                        if (Err != 997 && Err != 183 && Err != 2)
                        {
                            System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Err);
                            Trace.WriteLine("Write fault " + Err + ": " + e.Message);
                            err = true;// yield break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (DSPUtil.IsMono() && e.Message.Contains("Write fault on path"))
                {
                    // This is the usual end-of-stream error on Mono
                    Trace.WriteLine("Write finished; " + e.Message);
                    err = true; // yield break
                }
                else if (e.GetHashCode() == 33574638)
                {
                    // "The specified network name is no longer available", from softsqueeze
                    Trace.WriteLine("Write finished; " + e.Message);
                    err = true; // yield break
                }
                else
                {
                    // Trace.WriteLine("Interrupted: " + e.Message);
                    throw e;
                }
            }
            return sample;
        }
Example #55
0
        public int OpenDevice()
        {
            BthRuntime.SetLogFileName("BthEmulManager.txt");

            int level = DesktopLogging ? 255 : 0;
            BthRuntime.SetLogLevel(level);

            devId = BthRuntime.OpenDevice();
            if (BthRuntime.INVALID_DEVICE_ID == devId)
            {
                HardwareState = HARDWARE_STATE.UNAVAILABLE;

                int lastError = Marshal.GetLastWin32Error();
                HardwareErrorCode = lastError;
                HardwareErrorMessage = new System.ComponentModel.Win32Exception(lastError).Message;
                RenderViews(null);
            }
            else
            {
                HardwareState = HARDWARE_STATE.ATTACHED;

                // get device info.
                DEVICE_INFO deviceInfo = new DEVICE_INFO();
                if (1 == BthRuntime.GetDeviceInfo(devId, ref deviceInfo))
                {
                    DeviceInfo = deviceInfo;
                    Manufacturer = BthRuntime.GetManufacturerName(deviceInfo.manufacturer);
                }

                // start connection monitor timer.
                connectionMonitorTimer = new System.Timers.Timer();
                connectionMonitorTimer.Elapsed += new ElapsedEventHandler(ConnectionMonitorTimerEvent);
                connectionMonitorTimer.Interval = 3000;
                connectionMonitorTimer.Start();
            }

            return devId;
        }
Example #56
0
 private void CheckError(string methodName)
 {
     Int32 err = Marshal.GetLastWin32Error();
     if (err != 0)
     {
         var tempToGetMessage = new System.ComponentModel.Win32Exception(err);
         throw new System.ComponentModel.Win32Exception(err, methodName + ": " + tempToGetMessage.ToString());
     }
 }
Example #57
0
        /// <summary>
        /// Creates the unsigned certificate
        /// </summary>
        /// <param name="keycontainer">The key-container name</param>
        /// <param name="DN">The x509 name of certificate</param>
        /// <param name="provider">The cryptography provider (MS_DEF_PROV/MS_STRONG_PROV/MS_ENHANCED_PROV)</param>
        /// <param name="KEYSPEC">The key specification (AT_KEYEXCHANGE/AT_SIGNATURE) </param>
        /// <param name="cspflags">The CSP flags (only 0 = 'Current User' is used)</param>
        /// <returns>Pointer to created certificate context</returns>
        /// <exception cref="System.ApplicationException">Error occurred while trying to create certificate. Error is:  +  e.Message</exception>
        internal static IntPtr CreateUnsignedCertCntxt(String keycontainer, String DN, String provider = MS_DEF_PROV, uint KEYSPEC = AT_KEYEXCHANGE, uint cspflags = 0)
        {
            IntPtr hCertCntxt = IntPtr.Zero;
            byte[] encodedName = null;
            uint cbName = 0;

            if (provider != MS_DEF_PROV && provider != MS_STRONG_PROV && provider != MS_ENHANCED_PROV)
            {
                return IntPtr.Zero;
            }

            if (keycontainer == "")
            {
                return IntPtr.Zero;
            }

            if (KEYSPEC != AT_SIGNATURE && KEYSPEC != AT_KEYEXCHANGE)
            {
                return IntPtr.Zero;
            }

            if (cspflags != 0 && cspflags != CRYPT_MACHINE_KEYSET)   //only 0 (Current User) keyset is currently used.
            {
                return IntPtr.Zero;
            }

            if (DN == "")
            {
                return IntPtr.Zero;
            }

            if (UnsafeNativeMethods.CertStrToName(X509_ASN_ENCODING, DN, CERT_X500_NAME_STR, IntPtr.Zero, null, ref cbName, IntPtr.Zero))
            {
                encodedName = new byte[cbName];
                UnsafeNativeMethods.CertStrToName(X509_ASN_ENCODING, DN, CERT_X500_NAME_STR, IntPtr.Zero, encodedName, ref cbName, IntPtr.Zero);
            }

            UnsafeNativeMethods.CERT_NAME_BLOB subjectblob = new UnsafeNativeMethods.CERT_NAME_BLOB();
            subjectblob.pbData = Marshal.AllocHGlobal(encodedName.Length);
            Marshal.Copy(encodedName, 0, subjectblob.pbData, encodedName.Length);
            subjectblob.cbData = encodedName.Length;

            UnsafeNativeMethods.CRYPT_KEY_PROV_INFO pInfo = new UnsafeNativeMethods.CRYPT_KEY_PROV_INFO();
            pInfo.pwszContainerName = keycontainer;
            pInfo.pwszProvName = provider;
            pInfo.dwProvType = PROV_RSA_FULL;
            pInfo.dwFlags = cspflags;
            pInfo.cProvParam = 0;
            pInfo.rgProvParam = IntPtr.Zero;
            pInfo.dwKeySpec = KEYSPEC;

            try
            {
                hCertCntxt = UnsafeNativeMethods.CertCreateSelfSignCertificate(IntPtr.Zero, ref subjectblob, CERT_CREATE_SELFSIGN_NO_SIGN, ref pInfo, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                if (hCertCntxt == IntPtr.Zero)
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                    throw new ApplicationException("Error occurred while trying to create certificate. Error is: " +  e.Message, e);
                }

                return hCertCntxt;
            }
            finally
            {
                Marshal.FreeHGlobal(subjectblob.pbData);
            }
        }