internal static IntPtr FindWindowWithThreadProcessId(int processId)
    {
        var window = new IntPtr();

        Win32Helpers.EnumWindows(delegate(IntPtr wnd, IntPtr param)
        {
            var windowProcessId = 0;
            Win32Helpers.GetWindowThreadProcessId(wnd, out windowProcessId);
            if (windowProcessId == processId)
            {
                window = wnd;
                return false;
            }

            return true;
        },
        IntPtr.Zero);

        if (window.Equals(IntPtr.Zero))
        {
            UnityEngine.Debug.LogError("Could not find any window with process id " + processId);
        }

        return window;
    }
Beispiel #2
0
 public virtual bool runTest()
   {
   Console.Error.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
   int iCountErrors = 0;
   int iCountTestcases = 0;
   String strLoc = "Loc_000oo";
   IntPtr ip1;
   IntPtr ip2;
   Int32 iValue;
   try {
   strLoc = "Loc_743wg";
   iValue = 16;
   ip1 = new IntPtr(iValue);
   ip2 = new IntPtr(iValue);
   iCountTestcases++;
   if(!ip1.Equals(ip2)){
   iCountErrors++;
   Console.WriteLine("Err_865sg! Wrong value returned");
   }             
   strLoc = "Loc_9047tdsg";
   iValue = 16;
   ip1 = new IntPtr(iValue);
   ip2 = new IntPtr(iValue*2);
   iCountTestcases++;
   if(ip1.Equals(ip2)){
   iCountErrors++;
   Console.WriteLine("Err_9765sgf! Wrong value returned");
   }             
   strLoc = "Loc_98736zdg";
   iValue = 16;
   ip1 = new IntPtr(iValue);
   iCountTestcases++;
   if(ip1.Equals(iValue)){
   iCountErrors++;
   Console.WriteLine("Err_9756gf! Wrong value returned");
   }             
   strLoc = "Loc_98736zdg";
   iValue = 16;
   ip1 = new IntPtr(iValue);
   iCountTestcases++;
   if(ip1.Equals(null)){
   iCountErrors++;
   Console.WriteLine("Err_973sdg! Wrong value returned");
   }             
   } catch (Exception exc_general ) {
   ++iCountErrors;
   Console.WriteLine(s_strTFAbbrev +" Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general);
   }
   if ( iCountErrors == 0 )
     {
     Console.Error.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
     return true;
     }
   else
     {
     Console.Error.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
     return false;
     }
   }
Beispiel #3
0
 public bool PosTest1()
 {
     bool retVal = true;
     try
     {
         System.IntPtr ip = new IntPtr(0);
         if (ip.Equals(null))
         {
             TestLibrary.TestFramework.LogError("001", "expect new IntPtr(0).Equals(null)");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
Beispiel #4
0
 unsafe public bool PosTest2()
 {
     bool retVal = true;
     try
     {
         byte* mem = stackalloc byte[1024];
         System.IntPtr ip1 = new IntPtr((void*)mem);
         System.IntPtr ip2 = new IntPtr((void*)mem);
         if (!ip1.Equals(ip2))
         {
             TestLibrary.TestFramework.LogError("002", "expect two IntPtr equals");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
    public static bool LoadProcess(string applicationPath, bool ignoreCase = false)
    {
        string processName = Path.GetFileNameWithoutExtension(applicationPath);
        foreach (Process p in Process.GetProcessesByName(processName))
        {
            if (ignoreCase)
            {
                if (p.MainModule.FileName.ToLower().Equals(applicationPath.ToLower()))
                    proc = p;
            }
            else
            {
                if (p.MainModule.FileName.Equals(applicationPath))
                    proc = p;
            }
        }

        if (proc == null) return false;
        BaseAddress = (Int32)proc.MainModule.BaseAddress;
        procHwnd = OpenProcess(PROC_RW, false, proc.Id);
        if (procHwnd.Equals(IntPtr.Zero)) return false;
        return true;
    }
        public static Pango.Context LayoutGetContext(Pango.Layout layout)
        {
            IntPtr handle = pango_layout_get_context(layout.Handle);

            return(handle.Equals(IntPtr.Zero) ? null : GLib.Object.GetObject(handle) as Pango.Context);
        }
Beispiel #7
0
        /// <summary>
        /// 获取ntoskrnl的基址
        /// </summary>
        /// <returns></returns>
        internal static bool GetNtoskrnlBase()
        {
            uint   uiNeedSize, uiModuleCount, uiBufferSize = 0x5000;
            IntPtr pBuffer = IntPtr.Zero;

            NativeApiEx.NtStatus status;
            MODULE_LIST          _ModuleInfo = new MODULE_LIST();

            // 分配内存
            pBuffer = Marshal.AllocHGlobal((IntPtr)uiBufferSize);
            if (pBuffer.Equals(IntPtr.Zero))
            {
                return(false);
            }
            // 查询模块信息
            status = NativeApi.NtQuerySystemInformation(
                NativeApiEx.SYSTEM_INFORMATION_CLASS.SystemModuleInformation,
                pBuffer, uiBufferSize, out uiNeedSize);

            if (status.Equals(NativeApiEx.NtStatus.InfoLengthMismatch))
            {
                Marshal.FreeHGlobal(pBuffer);
                try
                {
                    pBuffer = Marshal.AllocHGlobal((int)uiNeedSize);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("[x_x]:" + ex.Message);
                    return(false);
                }

                status = NativeApi.NtQuerySystemInformation(
                    NativeApiEx.SYSTEM_INFORMATION_CLASS.SystemModuleInformation,
                    pBuffer, uiNeedSize, out uiNeedSize);

                if (!status.Equals(NativeApiEx.NtStatus.Success))
                {
                    Marshal.FreeHGlobal(pBuffer);
                    MessageBox.Show("[x_x]:" + Common.CommonFunction.GetLastError32());
                    return(false);
                }
            }

            try
            {
                _ModuleInfo = (MODULE_LIST)Marshal.PtrToStructure(pBuffer, _ModuleInfo.GetType());
            }
            catch (Exception ex)
            {
                Marshal.FreeHGlobal(pBuffer);
                MessageBox.Show("[x_x]:" + ex.Message);
                return(false);
            }

            // 获取模块总数量
            uiModuleCount = _ModuleInfo.ModuleCount;
            // 获取模块名
            if (strNtosExeFullPath.Equals(""))
            {
                strNtosExeFullPath = _ModuleInfo.Modules[0].ImageName;
                strNtosExeFullPath = Environment.GetEnvironmentVariable("SystemRoot") + "\\system32\\" + Path.GetFileName(strNtosExeFullPath);
            }
            // 获取模块基址
            NtosBase = _ModuleInfo.Modules[0].Base;
            // 释放内存空间
            Marshal.FreeHGlobal(pBuffer);

            return(true);
        }
Beispiel #8
0
        public static int GetCRLNumber(string fileName, bool throwExceptions = false)
        {
            Boolean bResult   = false;
            IntPtr  pvContext = IntPtr.Zero;

            CryptoApiWin32.CRL_CONTEXT CRLContext;
            CryptoApiWin32.CRL_INFO    CRLInfo;
            IntPtr rgExtension = IntPtr.Zero;

            CryptoApiWin32.CERT_EXTENSION CRLExtension;
            Int32         cbFormat = 0;
            StringBuilder pbFormat = null;

            try
            {
                // Get CRL context
                //
                bResult = CryptoApiWin32.CryptQueryObject(
                    CryptoApiWin32.CERT_QUERY_OBJECT_FILE,
                    fileName,
                    CryptoApiWin32.CERT_QUERY_CONTENT_FLAG_CRL,
                    CryptoApiWin32.CERT_QUERY_FORMAT_FLAG_BINARY,
                    0,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    ref pvContext
                    );
                if (!bResult)
                {
                    throw new Exception("CryptQueryObject error #" + Marshal.GetLastWin32Error());
                }

                CRLContext =
                    (CryptoApiWin32.CRL_CONTEXT)Marshal.PtrToStructure(pvContext, typeof(CryptoApiWin32.CRL_CONTEXT));

                // Get CRL info
                //
                CRLInfo =
                    (CryptoApiWin32.CRL_INFO)
                    Marshal.PtrToStructure(CRLContext.pCrlInfo, typeof(CryptoApiWin32.CRL_INFO));

                rgExtension = CryptoApiWin32.CertFindExtension(
                    CryptoApiWin32.szOID_CRL_NUMBER_CODE,
                    CRLInfo.cExtension,
                    CRLInfo.rgExtension
                    );
                if (rgExtension.Equals(IntPtr.Zero))
                {
                    throw new Exception("CertFindExtension found no CRL Number");
                }

                CRLExtension =
                    (CryptoApiWin32.CERT_EXTENSION)
                    Marshal.PtrToStructure(rgExtension, typeof(CryptoApiWin32.CERT_EXTENSION));

                var res = new byte[CRLExtension.Value.cbData];
                Marshal.Copy(CRLExtension.Value.pbData, res, 0, res.Length);

                /*if (res.Length == 4)
                 * {
                 *  var res2 = new byte[2];
                 *  res2[0] = res[2];
                 *  res2[1] = res[3];
                 *
                 *  return res2;
                 * }*/

                cbFormat = 0;
                pbFormat = null;
                bResult  = CryptoApiWin32.CryptFormatObject(
                    CryptoApiWin32.X509_ASN_ENCODING,
                    0,
                    0,
                    IntPtr.Zero,
                    CryptoApiWin32.szOID_CRL_NUMBER_CODE,
                    CRLExtension.Value.pbData,
                    CRLExtension.Value.cbData,
                    null,
                    ref cbFormat
                    );
                if (!bResult)
                {
                    throw new Exception("CryptFormatObject error #" + Marshal.GetLastWin32Error());
                }

                pbFormat = new StringBuilder(cbFormat);

                bResult = CryptoApiWin32.CryptFormatObject(
                    CryptoApiWin32.X509_ASN_ENCODING,
                    0,
                    0,
                    IntPtr.Zero,
                    CryptoApiWin32.szOID_CRL_NUMBER_CODE,
                    CRLExtension.Value.pbData,
                    CRLExtension.Value.cbData,
                    pbFormat,
                    ref cbFormat
                    );
                if (!bResult)
                {
                    throw new Exception("CryptFormatObject error #" + Marshal.GetLastWin32Error());
                }

                LogHelper.GetLogger().WriteEntry("Reading crl number from " + fileName + ": " + pbFormat + ", array length=" + res.Length, EventLogEntryType.Information, 9000);

                //return Convert.ToInt32(pbFormat.ToString().Replace(" ", ""));

                if (res.Length == 3)
                {
                    return(res[2]);
                }
                else if (res.Length >= 2)
                {
                    return(res[res.Length - 2] * 256 + res[res.Length - 1]);
                }

                return(BitConverter.ToInt32(res, 0));
            } catch (Exception ex)
            {
                if (throwExceptions)
                {
                    throw;
                }

                LogHelper.GetLogger().WriteEntry("Error reading crl number from " + fileName + ": " + ex.Message, EventLogEntryType.Error, 5);
                return(0);
            } finally {
                // Do some clean up
                //
                if (!pvContext.Equals(IntPtr.Zero))
                {
                    CryptoApiWin32.CertFreeCRLContext(pvContext);
                }
            }
        }
Beispiel #9
0
        private void HandleCompletionStatus(out CompletionStatus completionStatus, IntPtr overlappedAddress, IntPtr completionKey, int bytesTransferred)
        {
            if (completionKey.Equals(SignalPostCompletionKey))
            {
                object state;

                m_signalQueue.TryDequeue(out state);
                completionStatus = new CompletionStatus(null, state, OperationType.Signal, SocketError.Success, 0);
            }
            else
            {
                var overlapped = Overlapped.CompleteOperation(overlappedAddress);

                if (completionKey.Equals(SocketCompletionKey))
                {
                    // if the overlapped ntstatus is zero we assume success and don't call get overlapped result for optimization
                    if (overlapped.Success)
                    {
                        SocketError socketError = SocketError.Success;
                        try
                        {
                            if (overlapped.OperationType == OperationType.Accept)
                            {
                                overlapped.AsyncSocket.UpdateAccept();
                            }
                            else if (overlapped.OperationType == OperationType.Connect)
                            {
                                overlapped.AsyncSocket.UpdateConnect();
                            }
                        }
                        catch (SocketException ex)
                        {
                            socketError = ex.SocketErrorCode;
                        }

                        completionStatus = new CompletionStatus(overlapped.AsyncSocket, overlapped.State,
                                                                overlapped.OperationType, socketError,
                                                                bytesTransferred);
                    }
                    else
                    {
                        SocketError socketError = SocketError.Success;
                        SocketFlags socketFlags;

                        bool operationSucceed = UnsafeMethods.WSAGetOverlappedResult(overlapped.AsyncSocket.Handle,
                                                                                     overlappedAddress,
                                                                                     out bytesTransferred, false, out socketFlags);

                        if (!operationSucceed)
                        {
                            socketError = (SocketError)Marshal.GetLastWin32Error();
                        }

                        completionStatus = new CompletionStatus(overlapped.AsyncSocket, overlapped.State,
                                                                overlapped.OperationType, socketError,
                                                                bytesTransferred);
                    }
                }
                else
                {
                    completionStatus = new CompletionStatus(overlapped.AsyncSocket, overlapped.State,
                                                            overlapped.OperationType, SocketError.Success, 0);
                }
            }
        }
Beispiel #10
0
 /// <inheritdoc />
 public bool Equals(DisplayHandle other)
 {
     return(_MemoryAddress.Equals(other._MemoryAddress));
 }
        private static void OnRemoteCmdSignalCompleted(IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            tracer.WriteLine("Signal Completed callback received.");

            long cmdContextId = 0;
            WSManClientCommandTransportManager cmdTM = null;
            if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId))
            {
                // We dont have the command TM handle..just return.
                tracer.WriteLine("Unable to find a transport manager for the given command context {0}.", cmdContextId);
                return;
            }

            // log the callback received event.
            PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignalCallbackReceived,
                PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
                cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString());

            if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) ||
                (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle)))
            {
                // WSMan returned data from a wrong shell..notify the caller
                // about the same.
                tracer.WriteLine("Cmd Signal callback: ShellOperationHandles are not the same as the signal is initiated with");
                PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.CommandSendExFailed);
                TransportErrorOccuredEventArgs eventargs =
                    new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CommandInputEx);
                cmdTM.ProcessWSManTransportError(eventargs);

                return;
            }

            // release the resources related to signal
            if (IntPtr.Zero != cmdTM._cmdSignalOperationHandle)
            {
                WSManNativeApi.WSManCloseOperation(cmdTM._cmdSignalOperationHandle, 0);
                cmdTM._cmdSignalOperationHandle = IntPtr.Zero;
            }

            if (null != cmdTM._signalCmdCompleted)
            {
                cmdTM._signalCmdCompleted.Dispose();
                cmdTM._signalCmdCompleted = null;
            }

            // if the transport manager is already closed..ignore the errors and return            
            if (cmdTM.isClosed)
            {
                tracer.WriteLine("Client Command TM: Transport manager is closed. So returning");
                return;
            }

            if (IntPtr.Zero != error)
            {
                WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                if (errorStruct.errorCode != 0)
                {
                    tracer.WriteLine("Cmd Signal callback: WSMan reported an error: {0}", errorStruct.errorDetail);

                    TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(
                        cmdTM._sessnTm.WSManAPIData.WSManAPIHandle,
                        null,
                        errorStruct,
                        TransportMethodEnum.CommandInputEx,
                        RemotingErrorIdStrings.CommandSendExCallBackError,
                        new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) });
                    cmdTM.ProcessWSManTransportError(eventargs);
                    return;
                }
            }

            cmdTM.EnqueueAndStartProcessingThread(null, null, true);
        }
Beispiel #12
0
 public bool Equals(VideoMeta other)
 {
     return(true && Meta.Equals(other.Meta) && Buffer.Equals(other.Buffer) && Flags.Equals(other.Flags) && Format.Equals(other.Format) && Id.Equals(other.Id) && Width.Equals(other.Width) && Height.Equals(other.Height) && NPlanes.Equals(other.NPlanes) && Offset.Equals(other.Offset) && Stride.Equals(other.Stride) && _map.Equals(other._map) && _unmap.Equals(other._unmap));
 }
Beispiel #13
0
        private void timer2_Tick(object sender, EventArgs e)
        {
            //this.Hide();
            IntPtr ParenthWnd = new IntPtr(0);
            string Caption    = this.txtCaption.Text;

            if (!string.IsNullOrEmpty(Caption))
            {
                try
                {
                    ParenthWnd = FindWindow(null, "Miner");
                }catch (Exception ex)
                {
                    this.txtRecordInfo.Text += ex.Message + "\n\r";
                }
                if (!ParenthWnd.Equals(IntPtr.Zero))//判断指定的窗体是否运行
                {
                    //SetForegroundWindow(ParenthWnd);//将当前窗口锁定在最前
                    // timer1.Enabled = true;

                    #region 获取窗口位置
                    //RECT rect = new RECT();
                    //GetWindowRect(ParenthWnd, ref rect);
                    //this.lblMarginLeft.Text = rect.Left.ToString();
                    //this.lblMarginRight.Text = rect.Right.ToString();
                    //this.lblMarginTop.Text = rect.Top.ToString();
                    //this.lblMarginBottom.Text = rect.Bottom.ToString();
                    try
                    {
                        WINDOWPLACEMENT wpm = new WINDOWPLACEMENT();
                        GetWindowPlacement(ParenthWnd, ref wpm);
                        Left   = wpm.rcNormalPosition.Left;
                        Right  = wpm.rcNormalPosition.Right;
                        Top    = wpm.rcNormalPosition.Top;
                        Bottom = wpm.rcNormalPosition.Bottom;
                    }catch (Exception ex)
                    {
                        this.txtRecordInfo.Text += ex.Message + "\n\r";
                    }
                    this.lblMarginLeft.Text   = Left.ToString();
                    this.lblMarginRight.Text  = Right.ToString();
                    this.lblMarginTop.Text    = Top.ToString();
                    this.lblMarginBottom.Text = Bottom.ToString();
                    #endregion

                    #region 截取窗口
                    if ((!IsLeftChange.Equals(this.lblMarginLeft.Text)) || (!IsTopChange.Equals(this.lblMarginTop.Text)))
                    {
                        IsLeftChange = this.lblMarginLeft.Text;
                        IsTopChange  = this.lblMarginTop.Text;
                        int Width  = Math.Abs(Right - Left);
                        int Height = Math.Abs(Bottom - Top);
                        CutImage(Width, Height, Left, Top, 0, 0, new Size(Width, Height));
                    }
                    #endregion

                    ///运行键盘钩子
                    if (hKeyboardHook == 0)
                    {
                        try
                        {
                            hookp         = new HookProc(KeyboardHookProc);
                            hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, hookp, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
                            // hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, hookp, GetModuleHandle("Miner.exe"),0);
                            this.gpbKeyboard.Text = "键盘信息(" + hKeyboardHook.ToString() + ")";


                            this.timer2.Stop();
                        }catch (Exception ex)
                        {
                            if (hKeyboardHook != 0)
                            {
                                if (UnhookWindowsHookEx(hKeyboardHook))//卸载当前钩子
                                {
                                    timer1.Enabled = false;
                                }
                                hKeyboardHook = 0;
                            }
                            this.timer2.Start();
                        }
                    }
                    else
                    {
                        #region 卸载钩子
                        // this.txtRecordInfo.Text += "/n/r";
                        if (hKeyboardHook != 0)
                        {
                            if (UnhookWindowsHookEx(hKeyboardHook))//卸载当前钩子
                            {
                                timer1.Enabled = false;
                            }
                            hKeyboardHook = 0;
                        }

                        #endregion
                        this.timer2.Start();
                    }
                }
                else
                {
                    this.txtCaption.Text = "请输入标题!";
                }
            }
        }
        private static unsafe object[] GetCustomAttributes(RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType, bool mustBeInheritable, IList derivedAttributes, bool isDecoratedTargetSecurityTransparent)
        {
            if (decoratedModule.Assembly.ReflectionOnly)
            {
                throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyCA"));
            }
            MetadataImport metadataImport = decoratedModule.MetadataImport;

            CustomAttributeRecord[] customAttributeRecords = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
            Type elementType = (((attributeFilterType == null) || attributeFilterType.IsValueType) || attributeFilterType.ContainsGenericParameters) ? typeof(object) : attributeFilterType;

            if ((attributeFilterType == null) && (customAttributeRecords.Length == 0))
            {
                return(CreateAttributeArrayHelper(elementType, 0));
            }
            object[]             attributes = CreateAttributeArrayHelper(elementType, customAttributeRecords.Length);
            int                  length     = 0;
            SecurityContextFrame frame      = new SecurityContextFrame();

            frame.Push(decoratedModule.GetRuntimeAssembly());
            Assembly lastAptcaOkAssembly = null;

            for (int i = 0; i < customAttributeRecords.Length; i++)
            {
                bool   flag2;
                bool   flag3;
                object obj2 = null;
                CustomAttributeRecord caRecord      = customAttributeRecords[i];
                IRuntimeMethodInfo    ctor          = null;
                RuntimeType           attributeType = null;
                int    namedArgs = 0;
                IntPtr signature = caRecord.blob.Signature;
                IntPtr blobEnd   = (IntPtr)(((void *)signature) + caRecord.blob.Length);
                int    num4      = (int)((long)((((void *)blobEnd) - ((void *)signature)) / 1));
                if (FilterCustomAttributeRecord(caRecord, metadataImport, ref lastAptcaOkAssembly, decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable, attributes, derivedAttributes, out attributeType, out ctor, out flag2, out flag3))
                {
                    if (ctor != null)
                    {
                        RuntimeMethodHandle.CheckLinktimeDemands(ctor, decoratedModule, isDecoratedTargetSecurityTransparent);
                    }
                    RuntimeConstructorInfo.CheckCanCreateInstance(attributeType, flag3);
                    if (flag2)
                    {
                        obj2 = CreateCaObject(decoratedModule, ctor, ref signature, blobEnd, out namedArgs);
                    }
                    else
                    {
                        obj2 = RuntimeTypeHandle.CreateCaInstance(attributeType, ctor);
                        if (num4 == 0)
                        {
                            namedArgs = 0;
                        }
                        else
                        {
                            if (Marshal.ReadInt16(signature) != 1)
                            {
                                throw new CustomAttributeFormatException();
                            }
                            signature = (IntPtr)(((void *)signature) + 2);
                            namedArgs = Marshal.ReadInt16(signature);
                            signature = (IntPtr)(((void *)signature) + 2);
                        }
                    }
                    for (int j = 0; j < namedArgs; j++)
                    {
                        string      str;
                        bool        flag4;
                        RuntimeType type;
                        object      obj3;
                        IntPtr      ptr1 = caRecord.blob.Signature;
                        GetPropertyOrFieldData(decoratedModule, ref signature, blobEnd, out str, out flag4, out type, out obj3);
                        try
                        {
                            if (flag4)
                            {
                                if ((type == null) && (obj3 != null))
                                {
                                    type = (RuntimeType)obj3.GetType();
                                    if (type == Type_RuntimeType)
                                    {
                                        type = Type_Type;
                                    }
                                }
                                RuntimePropertyInfo property = null;
                                if (type == null)
                                {
                                    property = attributeType.GetProperty(str) as RuntimePropertyInfo;
                                }
                                else
                                {
                                    property = attributeType.GetProperty(str, type, Type.EmptyTypes) as RuntimePropertyInfo;
                                }
                                if (property == null)
                                {
                                    throw new CustomAttributeFormatException(string.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString(flag4 ? "RFLCT.InvalidPropFail" : "RFLCT.InvalidFieldFail"), new object[] { str }));
                                }
                                RuntimeMethodInfo setMethod = property.GetSetMethod(true) as RuntimeMethodInfo;
                                if (setMethod.IsPublic)
                                {
                                    RuntimeMethodHandle.CheckLinktimeDemands(setMethod, decoratedModule, isDecoratedTargetSecurityTransparent);
                                    setMethod.Invoke(obj2, BindingFlags.Default, null, new object[] { obj3 }, null, true);
                                }
                            }
                            else
                            {
                                RtFieldInfo field = attributeType.GetField(str) as RtFieldInfo;
                                if (isDecoratedTargetSecurityTransparent)
                                {
                                    RuntimeFieldHandle.CheckAttributeAccess(field.FieldHandle, decoratedModule.GetNativeHandle());
                                }
                                field.InternalSetValue(obj2, obj3, BindingFlags.Default, Type.DefaultBinder, null, false);
                            }
                        }
                        catch (Exception exception)
                        {
                            throw new CustomAttributeFormatException(string.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString(flag4 ? "RFLCT.InvalidPropFail" : "RFLCT.InvalidFieldFail"), new object[] { str }), exception);
                        }
                    }
                    if (!signature.Equals(blobEnd))
                    {
                        throw new CustomAttributeFormatException();
                    }
                    attributes[length++] = obj2;
                }
            }
            frame.Pop();
            if ((length == customAttributeRecords.Length) && (pcaCount == 0))
            {
                return(attributes);
            }
            object[] destinationArray = CreateAttributeArrayHelper(elementType, length + pcaCount);
            Array.Copy(attributes, 0, destinationArray, 0, length);
            return(destinationArray);
        }
Beispiel #15
0
 public unsafe bool Equals(CullingResults other)
 {
     return(ptr.Equals(other.ptr) && m_AllocationInfo == other.m_AllocationInfo);
 }
Beispiel #16
0
        // ---------------------------------------------------------------
        // Name:      OverlayDraw
        // Synopsis:  This function draws annotations in the display overlay.

        static void OverlayDraw(MIL_ID MilDisplay)
        {
            MIL_ID  DefaultGraphicContext = MIL.M_DEFAULT;
            MIL_ID  MilOverlayImage = MIL.M_NULL;
            MIL_INT ImageWidth, ImageHeight;
            IntPtr  hCustomDC = IntPtr.Zero;

            // Prepare overlay buffer.
            //***************************

            // Enable the display of overlay annotations.
            MIL.MdispControl(MilDisplay, MIL.M_OVERLAY, MIL.M_ENABLE);

            // Inquire the overlay buffer associated with the display.
            MIL.MdispInquire(MilDisplay, MIL.M_OVERLAY_ID, ref MilOverlayImage);

            // Clear the overlay to transparent.
            MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_CLEAR, MIL.M_DEFAULT);

            // Disable the overlay display update to accelerate annotations.
            MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_SHOW, MIL.M_DISABLE);

            // Inquire overlay size.
            ImageWidth  = MIL.MbufInquire(MilOverlayImage, MIL.M_SIZE_X, MIL.M_NULL);
            ImageHeight = MIL.MbufInquire(MilOverlayImage, MIL.M_SIZE_Y, MIL.M_NULL);

            // Draw MIL overlay annotations.
            //*********************************

            // Set the graphic text background to transparent.
            MIL.MgraControl(DefaultGraphicContext, MIL.M_BACKGROUND_MODE, MIL.M_TRANSPARENT);

            // Print a white string in the overlay image buffer.
            MIL.MgraColor(DefaultGraphicContext, MIL.M_COLOR_WHITE);
            MIL.MgraText(DefaultGraphicContext, MilOverlayImage, ImageWidth / 9, ImageHeight / 5, " -------------------- ");
            MIL.MgraText(DefaultGraphicContext, MilOverlayImage, ImageWidth / 9, ImageHeight / 5 + 25, " - MIL Overlay Text - ");
            MIL.MgraText(DefaultGraphicContext, MilOverlayImage, ImageWidth / 9, ImageHeight / 5 + 50, " -------------------- ");

            // Print a green string in the overlay image buffer.
            MIL.MgraColor(DefaultGraphicContext, MIL.M_COLOR_GREEN);
            MIL.MgraText(DefaultGraphicContext, MilOverlayImage, ImageWidth * 11 / 18, ImageHeight / 5, " ---------------------");
            MIL.MgraText(DefaultGraphicContext, MilOverlayImage, ImageWidth * 11 / 18, ImageHeight / 5 + 25, " - MIL Overlay Text - ");
            MIL.MgraText(DefaultGraphicContext, MilOverlayImage, ImageWidth * 11 / 18, ImageHeight / 5 + 50, " ---------------------");

            // Re-enable the overlay display after all annotations are done.
            MIL.MdispControl(MilDisplay, MIL.M_OVERLAY_SHOW, MIL.M_ENABLE);

            // Draw GDI color overlay annotation.
            //***********************************

            // The inquire might not be supported
            MIL.MappControl(MIL.M_DEFAULT, MIL.M_ERROR, MIL.M_PRINT_DISABLE);

            // Create a device context to draw in the overlay buffer with GDI.
            MIL.MbufControl(MilOverlayImage, MIL.M_DC_ALLOC, MIL.M_DEFAULT);

            // Inquire the device context.
            hCustomDC = (IntPtr)MIL.MbufInquire(MilOverlayImage, MIL.M_DC_HANDLE, MIL.M_NULL);

            MIL.MappControl(MIL.M_DEFAULT, MIL.M_ERROR, MIL.M_PRINT_ENABLE);

            // Perform operation if GDI drawing is supported.
            if (!hCustomDC.Equals(IntPtr.Zero))
            {
                // NOTE : The using blocks will automatically call the Dipose method on the GDI objects.
                //        This ensures that resources are freed even if an exception occurs.

                // Create a System.Drawing.Graphics object from the Device context
                using (Graphics DrawingGraphics = Graphics.FromHdc(hCustomDC))
                {
                    // Draw a blue cross.
                    using (Pen DrawingPen = new Pen(Color.Blue))
                    {
                        // Draw a blue cross in the overlay image
                        DrawingGraphics.DrawLine(DrawingPen, 0, (int)(ImageHeight / 2), ImageWidth, (int)(ImageHeight / 2));
                        DrawingGraphics.DrawLine(DrawingPen, (int)(ImageWidth / 2), 0, (int)(ImageWidth / 2), ImageHeight);

                        // Prepare transparent text annotations.
                        // Define the Brushes and fonts used to draw text
                        using (SolidBrush LeftBrush = new SolidBrush(Color.Red))
                        {
                            using (SolidBrush RightBrush = new SolidBrush(Color.Yellow))
                            {
                                using (Font OverlayFont = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold))
                                {
                                    // Write text in the overlay image
                                    SizeF GDITextSize = DrawingGraphics.MeasureString("GDI Overlay Text", OverlayFont);
                                    DrawingGraphics.DrawString("GDI Overlay Text", OverlayFont, LeftBrush, System.Convert.ToInt32(ImageWidth / 4 - GDITextSize.Width / 2), System.Convert.ToInt32(ImageHeight * 3 / 4 - GDITextSize.Height / 2));
                                    DrawingGraphics.DrawString("GDI Overlay Text", OverlayFont, RightBrush, System.Convert.ToInt32(ImageWidth * 3 / 4 - GDITextSize.Width / 2), System.Convert.ToInt32(ImageHeight * 3 / 4 - GDITextSize.Height / 2));
                                }
                            }
                        }
                    }
                }

                //   // Delete device context.
                MIL.MbufControl(MilOverlayImage, MIL.M_DC_FREE, MIL.M_DEFAULT);

                //   // Signal MIL that the overlay buffer was modified.
                MIL.MbufControl(MilOverlayImage, MIL.M_MODIFIED, MIL.M_DEFAULT);
            }
        }
Beispiel #17
0
        public byte[] GetRawOSBData()
        {
            if (_hPrimarySharedMemoryAreaFileMappingObject.Equals(IntPtr.Zero))
            {
                ConnectToFalcon();
            }
            if (_hPrimarySharedMemoryAreaFileMappingObject.Equals(IntPtr.Zero))
            {
                return(null);
            }
            var bytesRead = new List <byte>();

            if (!_hOsbSharedMemoryAreaFileMappingObject.Equals(IntPtr.Zero))
            {
                var fileSizeBytes = GetMaxMemFileSize(_lpOsbSharedMemoryAreaBaseAddress);
                if (fileSizeBytes > Marshal.SizeOf(typeof(OSBData)))
                {
                    fileSizeBytes = Marshal.SizeOf(typeof(OSBData));
                }
                for (var i = 0; i < fileSizeBytes; i++)
                {
                    try
                    {
                        bytesRead.Add(Marshal.ReadByte(_lpOsbSharedMemoryAreaBaseAddress, i));
                    }
                    catch
                    {
                        break;
                    }
                }
            }
            var toReturn = bytesRead.ToArray();

            return(toReturn.Length == 0 ? null : toReturn);
        }
Beispiel #18
0
 private bool EqualsByRef(ref DataBox other)
 {
     return(DataPointer.Equals(other.DataPointer) && RowPitch == other.RowPitch && SlicePitch == other.SlicePitch);
 }
    private bool LookForMalware(IntPtr map, ulong length)
    {
        if(!map.Equals(IntPtr.Zero) && length != 0)
            {
                int index = this._kmp.Search(map, (uint) length);

                if (index != -1)
                    return true;

                Debug.WriteLine(String.Format("length = {0} KMP returned = {1}", length, index));
            }

        return false;
    }
Beispiel #20
0
 /// <inheritdoc />
 public bool Equals(LogicalGPUHandle other)
 {
     return(_MemoryAddress.Equals(other._MemoryAddress));
 }
 public bool FoundProcess()
 {
     return(!_handler.Equals(IntPtr.Zero));
 }
Beispiel #22
0
 public bool PosTest3()
 {
     bool retVal = true;
     try
     {
         int anyAddr = TestLibrary.Generator.GetInt32(-55);
         System.IntPtr ip1 = new IntPtr(anyAddr);
         System.IntPtr ip2 = new IntPtr(anyAddr);
         if (!ip1.Equals(ip2))
         {
             TestLibrary.TestFramework.LogError("003", "expect two IntPtr equals");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
Beispiel #23
0
        private void NCPaint()
        {
            if (this.Parent == null)
            {
                return;
            }
            if (this.Width <= 0 || this.Height <= 0)
            {
                return;
            }

            IntPtr windowDC = NativeMethods.GetDCEx(this.Handle,
                                                    IntPtr.Zero, NativeMethods.DCX_CACHE |
                                                    NativeMethods.DCX_WINDOW |
                                                    NativeMethods.DCX_CLIPSIBLINGS |
                                                    NativeMethods.DCX_LOCKWINDOWUPDATE);

            if (windowDC.Equals(IntPtr.Zero))
            {
                return;
            }

            using (Bitmap bm = new Bitmap(this.Width, this.Height,
                                          System.Drawing.Imaging.PixelFormat.Format32bppPArgb))
            {
                using (Graphics g = Graphics.FromImage(bm))
                {
                    Rectangle borderRect = new Rectangle(0, 0,
                                                         Width - 1, Height - 1);

                    using (Pen borderPen = new Pen(this.borderColor, 1))
                    {
                        borderPen.Alignment = PenAlignment.Inset;
                        g.DrawRectangle(borderPen, borderRect);
                    }

                    // Create and Apply a Clip Region to the WindowDC
                    using (Region Rgn = new Region(new
                                                   Rectangle(0, 0, Width, Height)))
                    {
                        Rgn.Exclude(new Rectangle(1, 1, Width - 2, Height - 2));
                        IntPtr hRgn = Rgn.GetHrgn(g);
                        if (!hRgn.Equals(IntPtr.Zero))
                        {
                            NativeMethods.SelectClipRgn(windowDC, hRgn);
                        }

                        IntPtr bmDC  = g.GetHdc();
                        IntPtr hBmp  = bm.GetHbitmap();
                        IntPtr oldDC = NativeMethods.SelectObject(bmDC,
                                                                  hBmp);
                        NativeMethods.BitBlt(windowDC, 0, 0, bm.Width,
                                             bm.Height, bmDC, 0, 0, NativeMethods.SRCCOPY);

                        NativeMethods.SelectClipRgn(windowDC, IntPtr.Zero);
                        NativeMethods.DeleteObject(hRgn);

                        g.ReleaseHdc(bmDC);
                        NativeMethods.SelectObject(oldDC, hBmp);
                        NativeMethods.DeleteObject(hBmp);
                        bm.Dispose();
                    }
                }
            }

            NativeMethods.ReleaseDC(this.Handle, windowDC);
        }
Beispiel #24
0
 unsafe public bool NegTest1()
 {
     bool retVal = true;
     try
     {
         byte* mem1 = stackalloc byte[1];
         byte* mem2 = stackalloc byte[1];
         mem1[0] = mem1[0] = TestLibrary.Generator.GetByte(-55);
         System.IntPtr ip1 = new IntPtr((void*)mem1);
         System.IntPtr ip2 = new IntPtr((void*)mem2);
         if (ip1.Equals(ip2))
         {
             TestLibrary.TestFramework.LogError("001", "expect two IntPtrs NOT equals");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
Beispiel #25
0
        public static void RunOCRonBluebeamtool(string folderpath)
        {
            try
            {
                ProcessHandlers.killapp("Revu");
                var psi = new ProcessStartInfo(ExeSourceFile);
                psi.UseShellExecute = true;
                _application        = TestStack.White.Application.AttachOrLaunch(psi);
                Process p = Process.GetProcessesByName("Revu").FirstOrDefault();
                while (p.MainWindowHandle == IntPtr.Zero)
                {
                    p.Refresh();
                }
                p.WaitForInputIdle();
                if (p != null)
                {
                    IntPtr h = p.MainWindowHandle;
                    ProcessHandlers.SetForegroundWindow(h);
                    p.WaitForInputIdle();
                    IntPtr hPRAZChem = ProcessHandlers.FindWindow(null, "Bluebeam Revu x64");
                    if (!hPRAZChem.Equals(IntPtr.Zero))
                    {
                        ProcessHandlers.SetForegroundWindow(hPRAZChem);
                    }
                    p.WaitForInputIdle();

                    Thread.Sleep(3000);


                    sendkeyevent(1, "%");
                    //  sendkeyevent(1, "{RIGHT}");
                    sendkeyevent(1, "{DOWN}");
                    sendkeyevent(7, "{RIGHT}");
                    sendkeyevent(1, "{ENTER}");
                    sendkeyevent(1, "{DOWN}");
                    sendkeyevent(1, "{ENTER}");

                    IntPtr hPRAZChem1 = ProcessHandlers.FindWindow(null, "Add Files for Batch Processing");
                    p.WaitForInputIdle();
                    if (!hPRAZChem1.Equals(IntPtr.Zero))
                    {
                        ProcessHandlers.SetForegroundWindow(hPRAZChem1);
                    }
                    p.WaitForInputIdle();

                    SendKeys.SendWait(folderpath);
                    Thread.Sleep(10000);
                    if (folderpath.Contains(".pdf"))
                    {
                        sendkeyevent(4, "{ENTER}");
                    }
                    else
                    {
                        sendkeyevent(1, "{ENTER}");
                        Thread.Sleep(3000);
                        sendkeyevent(8, "{TAB}");
                        sendkeyevent(1, "^(a)");
                        // SendKeys.SendWait("{A}");
                        sendkeyevent(4, "{ENTER}");
                    }
                    checkprogress();
                    checkprogress();
                    p.WaitForInputIdle();
                    ProcessHandlers.killapp("Revu");
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #26
0
 /// <summary>
 ///     Determines whether the specified <see cref="EGLDisplay" />, is equal to this instance.
 /// </summary>
 /// <param name="other">The <see cref="EGLDisplay" /> to compare with this instance.</param>
 /// <returns>
 ///     <c>true</c> if the specified <see cref="EGLDisplay" /> is equal to this instance; otherwise, <c>false</c>.
 /// </returns>
 public bool Equals(EGLDisplay other)
 {
     return(handle.Equals(other.handle));
 }
Beispiel #27
0
        /// <summary>
        /// Adds an ACE (access control entry) for the Users group to the specified directory.
        /// </summary>
        /// <param name="Path">The path to add the ACE to.</param>
        /// <param name="AceFlags">The flags to set in the ACE.</param>
        /// <param name="AccessMask">The rights to allow in the ACE.</param>
        /// <returns><b>True</b> if the ACE was successfully set; otherwise, <b>False</b>.</returns>
        public bool SetAccess(string Path, int AceFlags, uint AccessMask)
        {
            bool   retValue = false;
            IntPtr pSid     = IntPtr.Zero;
            IntPtr fileSD   = IntPtr.Zero;
            IntPtr pNewAcl  = IntPtr.Zero;

            try
            {
                try
                {
                    // Create the SID for the Users group.
                    SID_IDENTIFIER_AUTHORITY ntAuthority;
                    ntAuthority.Value0 = ntAuthority.Value1 = ntAuthority.Value2 = ntAuthority.Value3 = ntAuthority.Value4 = 0;
                    ntAuthority.Value5 = 5;
                    if (!AllocateAndInitializeSid(
                            ref ntAuthority,
                            2,
                            SECURITY_BUILTIN_DOMAIN_RID,
                            DOMAIN_ALIAS_RID_USERS,
                            0, 0, 0, 0, 0, 0,
                            ref pSid))
                    {
                        return(false);
                    }

                    // Get the size of the security descriptor for the directory.
                    int sdLength = 0;
                    if (!GetFileSecurity(Path, DACL_SECURITY_INFORMATION, fileSD, 0, out sdLength))
                    {
                        if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)
                        {
                            return(false);
                        }

                        // Allocate the security descriptor
                        fileSD = Marshal.AllocHGlobal(sdLength);

                        // Get the security descriptor for the directory.
                        if (!GetFileSecurity(Path, DACL_SECURITY_INFORMATION, fileSD, sdLength, out sdLength))
                        {
                            return(false);
                        }

                        // Get DACL from the old SD.
                        bool   bDaclPresent;
                        bool   bDaclDefaulted;
                        IntPtr aclPtr = IntPtr.Zero;
                        if (!GetSecurityDescriptorDacl(fileSD, out bDaclPresent, ref aclPtr, out bDaclDefaulted))
                        {
                            return(false);
                        }

                        if (aclPtr.Equals(IntPtr.Zero))
                        {
                            return(false);
                        }

                        // Put the data in an ACL structure.
                        MemoryMarshaler mm  = new MemoryMarshaler(aclPtr);
                        ACL             acl = (ACL)mm.ParseStruct(typeof(ACL));

                        // Compute size needed for the new ACL.
                        ACCESS_ALLOWED_ACE accessAllowedAce = new ACCESS_ALLOWED_ACE();
                        int n1       = Marshal.SizeOf(accessAllowedAce);
                        int n2       = Marshal.SizeOf(n1);
                        int cbNewAcl = acl.AclSize + 12 /*sizeof(ACCESS_ALLOWED_ACE)*/ + GetLengthSid(pSid) - 4 /*sizeof(int)*/;

                        // Allocate memory for new ACL.
                        pNewAcl = Marshal.AllocHGlobal(cbNewAcl);

                        // Initialize the new ACL.
                        if (!InitializeAcl(pNewAcl, cbNewAcl, ACL_REVISION))
                        {
                            return(false);
                        }

                        // If DACL is present, copy all the ACEs from the old DACL
                        // to the new DACL.
                        uint   newAceIndex     = 0;
                        IntPtr acePtr          = IntPtr.Zero;
                        int    CurrentAceIndex = 0;
                        if (bDaclPresent && (acl.AceCount > 0))
                        {
                            for (CurrentAceIndex = 0; CurrentAceIndex < acl.AceCount; CurrentAceIndex++)
                            {
                                // Get the ACE.
                                if (!GetAce(aclPtr, CurrentAceIndex, ref acePtr))
                                {
                                    return(false);
                                }

                                // Put the data in an ACCESS_ALLOWED_ACE structure.
                                mm.Ptr           = acePtr;
                                accessAllowedAce = (ACCESS_ALLOWED_ACE)mm.ParseStruct(typeof(ACCESS_ALLOWED_ACE));

                                // Check if it is a non-inherited ACE.
                                if ((accessAllowedAce.Header.AceFlags & INHERITED_ACE) == INHERITED_ACE)
                                {
                                    break;
                                }

                                // Get the memory that holds the SID.
                                mm.Ptr = acePtr;
                                mm.Advance(8);

                                // If the SID matches, don't add the ACE.
                                if (EqualSid(pSid, mm.Ptr))
                                {
                                    continue;
                                }

                                // Add the ACE to the new ACL.
                                if (!AddAce(pNewAcl, ACL_REVISION, MAXDWORD, acePtr, accessAllowedAce.Header.AceSize))
                                {
                                    return(false);
                                }

                                newAceIndex++;
                            }
                        }

                        // Add the access-allowed ACE to the new DACL.
                        if (!AddAccessAllowedAceEx(pNewAcl, ACL_REVISION, AceFlags, AccessMask, pSid))
                        {
                            return(false);
                        }

                        // Copy the rest of inherited ACEs from the old DACL to the new DACL.
                        if (bDaclPresent && (acl.AceCount > 0))
                        {
                            for (; CurrentAceIndex < acl.AceCount; CurrentAceIndex++)
                            {
                                // Get the ACE.
                                if (!GetAce(aclPtr, CurrentAceIndex, ref acePtr))
                                {
                                    return(false);
                                }

                                // Put the data in an ACCESS_ALLOWED_ACE structure.
                                mm.Ptr           = acePtr;
                                accessAllowedAce = (ACCESS_ALLOWED_ACE)mm.ParseStruct(typeof(ACCESS_ALLOWED_ACE));

                                // Add the ACE to the new ACL.
                                if (!AddAce(pNewAcl, ACL_REVISION, MAXDWORD, acePtr, accessAllowedAce.Header.AceSize))
                                {
                                    return(false);
                                }
                            }
                        }

                        // Create a new security descriptor to set on the directory.
                        SECURITY_DESCRIPTOR newSD;
                        newSD.Revision = (byte)SECURITY_DESCRIPTOR_REVISION;
                        newSD.Sbz1     = 0;
                        newSD.Control  = 0;
                        newSD.Owner    = IntPtr.Zero;
                        newSD.Group    = IntPtr.Zero;
                        newSD.Sacl     = IntPtr.Zero;
                        newSD.Dacl     = IntPtr.Zero;

                        // Set the new DACL to the new SD.
                        if (!SetSecurityDescriptorDacl(ref newSD, true, pNewAcl, false))
                        {
                            return(false);
                        }

                        // Copy the old security descriptor control flags
                        short controlBitsOfInterest = 0;
                        short controlBitsToSet      = 0;
                        short oldControlBits        = 0;
                        int   revision = 0;

                        if (!GetSecurityDescriptorControl(fileSD, out oldControlBits, out revision))
                        {
                            return(false);
                        }

                        if ((oldControlBits & SE_DACL_AUTO_INHERITED) == SE_DACL_AUTO_INHERITED)
                        {
                            controlBitsOfInterest = (short)(SE_DACL_AUTO_INHERIT_REQ | SE_DACL_AUTO_INHERITED);
                            controlBitsToSet      = controlBitsOfInterest;
                        }
                        else if ((oldControlBits & SE_DACL_PROTECTED) == SE_DACL_PROTECTED)
                        {
                            controlBitsOfInterest = (short)SE_DACL_PROTECTED;
                            controlBitsToSet      = controlBitsOfInterest;
                        }

                        if (controlBitsOfInterest > 0)
                        {
                            if (!SetSecurityDescriptorControl(ref newSD, controlBitsOfInterest, controlBitsToSet))
                            {
                                return(false);
                            }
                        }

                        // Set the new SD to the File.
                        if (!SetFileSecurity(Path, DACL_SECURITY_INFORMATION, ref newSD))
                        {
                            return(false);
                        }

                        retValue = true;
                    }
                }
                catch {}
            }
            finally
            {
                if (pSid != IntPtr.Zero)
                {
                    FreeSid(pSid);
                }

                if (fileSD != IntPtr.Zero)
                {
                    //GlobalFree(fileSD);
                    Marshal.FreeHGlobal(fileSD);
                }

                if (pNewAcl != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pNewAcl);
                }
            }

            return(retValue);
        }
Beispiel #28
0
        public override void Read(uint offset, uint length, IntPtr dest, ref uint bytesRead)
        {
            //System.Diagnostics.Debug.WriteLine("Conditional {2} reading from OS {0} L {1}", offset, length, Name);

            bool header = (offset < 24);
            bool init   = (offset == 24);

            if ((!_lastHeader && header) || (init && !_lastInit))   //re-evaluate
            {
                _current = null;
                if (!_handle.Equals(IntPtr.Zero))
                {
                    Win32.CloseHandle(_handle);
                }
                _handle = IntPtr.Zero;

                foreach (var of in _files)
                {
                    if (of.CFolder == null || of.CFolder.IsActive(of.CName))
                    {
                        System.Diagnostics.Debug.WriteLine("Conditional {0} switching to {1}", Name, of.File);
                        _current = of;
                        Bytes.WriteInt(_header, 20, of.Size);
                        break;
                    }
                }
                if (_current == null)
                {
                    System.Diagnostics.Debug.WriteLine("Conditional {0} switching to fallback", Name, Name);
                }
                _lastInit = true; //we're ready to read file headers
            }
            else
            {
                _lastInit = init;
            }
            if (_current != null && _handle.Equals(IntPtr.Zero) && _current.Archive == null)
            {
                _handle = Wrap.CreateFileW(_current.File, System.IO.FileAccess.Read, System.IO.FileShare.Read, IntPtr.Zero, System.IO.FileMode.Open, System.IO.FileAttributes.Normal, IntPtr.Zero);
            }
            _lastHeader = header;
            _access     = DateTime.Now;

            if (_current == null)   //read from fallback
            //System.Diagnostics.Debug.WriteLine("Conditional reading from fallback handle {0} with extra offset {1}", _fallbackHandle, _fallbackOffset);
            {
                Win32.OVERLAPPED ov = new Win32.OVERLAPPED()
                {
                    EventHandle  = IntPtr.Zero,
                    Internal     = UIntPtr.Zero,
                    InternalHigh = UIntPtr.Zero,
                    Offset       = _fallbackOffset + offset,
                    OffsetHigh   = 0
                };
                Win32.ReadFile(_fallbackHandle, dest, length, ref bytesRead, ref ov);
                //System.Diagnostics.Debug.WriteLine("Conditional {1} reading from fallback - {0} bytes read", bytesRead, Name);
            }
            else
            {
                if (offset < 24)
                {
                    length = Math.Min(length, 24 - offset);
                    System.Runtime.InteropServices.Marshal.Copy(_header, (int)offset, dest, (int)length);
                    bytesRead = length;
                    //System.Diagnostics.Debug.WriteLine("Conditional {2} reading from cheader - {0} bytes read [current size is {1}]", bytesRead, BitConverter.ToInt32(_header, 20), Name);
                    return;
                }
                else
                {
                    offset -= 24;
                    if (_current.Archive == null)
                    {
                        Wrap.SetFilePointer(_handle, (int)offset, IntPtr.Zero, Wrap.EMoveMethod.Begin);
                        Win32.ReadFile(_handle, dest, length, ref bytesRead, IntPtr.Zero);
                        //System.Diagnostics.Debug.WriteLine("Conditional {1} reading from cfile - {0} bytes read", bytesRead, Name);
                    }
                    else
                    {
                        _current.Archive.RawRead(_current.File, offset, length, dest, ref bytesRead);
                        //System.Diagnostics.Debug.WriteLine("Conditional {1} reading from cfile archive offset {2} length {3} - {0} bytes read", bytesRead, Name, offset, length);
                    }
                }
            }
        }
Beispiel #29
0
        public static void fncAppTracker()
        {
            if (GlobalClass.CheckForInternetConnection())
            {
                try
                {
                    string title  = string.Empty;
                    string appexe = string.Empty;

                    IntPtr handle = GetForegroundWindow();
                    if (!handle.Equals(IntPtr.Zero))
                    {
                        int tLength = GetWindowTextLength(handle);
                        if (tLength > 0)
                        {
                            if (tLength > 255)
                            {
                                tLength = 255;
                            }
                            StringBuilder wTitle = new StringBuilder(string.Empty, tLength + 1);
                            if (GetWindowText(handle, wTitle, wTitle.Capacity) > 0)
                            {
                                title = wTitle.ToString();
                            }
                            if (title != OldTitle && !String.IsNullOrEmpty(title))
                            {
                                int wProcID = 0;
                                if (GetWindowThreadProcessId(handle, out wProcID) > 0)
                                {
                                    appexe = Process.GetProcessById(wProcID).ProcessName;
                                }
                                if (!string.IsNullOrEmpty(appexe))
                                {
                                    if (appexe.Equals("firefox"))
                                    {
                                        BrowserUrlTracker.ReadBrowserUrlforFirefox();
                                        //BrowserUrlTracker.ReadBrowserUrlforChrome();
                                    }
                                    else if (appexe.Equals("iexplore"))
                                    {
                                        BrowserUrlTracker.ReadBrowserUrlforIE();
                                    }
                                    else if (appexe.Equals("chrome"))
                                    {
                                        BrowserUrlTracker.ReadBrowserUrlforChrome();
                                    }
                                    else if (appexe.Equals("opera"))
                                    {
                                        BrowserUrlTracker.ReadBrowserUrlforOpera();
                                    }
                                    else
                                    {
                                        OldTitle = title;
                                        appexe   = appexe + ".exe";
                                        WriteData(title, appexe);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error on AppTracker.cs in fncAppTracker function :- " + ex.Message);
                    GlobalClass.WriteTolog("Error on AppTracker.cs in fncAppTracker function :- " + ex.Message);
                }
            }
            else
            {
                GlobalClass.WriteTolog("server not giving any response");
            }
        }
    public string Recognize(Texture2D texture)
    {
        if (_tessHandle.Equals(IntPtr.Zero))
        {
            return(null);
        }

        _highlightedTexture = texture;

        int width  = _highlightedTexture.width;
        int height = _highlightedTexture.height;

        Color32[] colors        = _highlightedTexture.GetPixels32();
        int       count         = width * height;
        int       bytesPerPixel = 4;

        byte[] dataBytes = new byte[count * bytesPerPixel];
        int    bytePtr   = 0;

        for (int y = height - 1; y >= 0; y--)
        {
            for (int x = 0; x < width; x++)
            {
                int colorIdx = y * width + x;
                dataBytes[bytePtr++] = colors[colorIdx].r;
                dataBytes[bytePtr++] = colors[colorIdx].g;
                dataBytes[bytePtr++] = colors[colorIdx].b;
                dataBytes[bytePtr++] = colors[colorIdx].a;
            }
        }

        IntPtr imagePtr = Marshal.AllocHGlobal(count * bytesPerPixel);

        Marshal.Copy(dataBytes, 0, imagePtr, count * bytesPerPixel);

        TessBaseAPISetImage(_tessHandle, imagePtr, width, height, bytesPerPixel, width * bytesPerPixel);

        if (TessBaseAPIRecognize(_tessHandle, IntPtr.Zero) != 0)
        {
            Marshal.FreeHGlobal(imagePtr);
            return(null);
        }

        IntPtr     confidencesPointer = TessBaseAPIAllWordConfidences(_tessHandle);
        int        i          = 0;
        List <int> confidence = new List <int>();

        while (true)
        {
            int tempConfidence = Marshal.ReadInt32(confidencesPointer, i * 4);

            if (tempConfidence == -1)
            {
                break;
            }

            i++;
            confidence.Add(tempConfidence);
        }

        int    pointerSize = Marshal.SizeOf(typeof(IntPtr));
        IntPtr intPtr      = TessBaseAPIGetWords(_tessHandle, IntPtr.Zero);
        Boxa   boxa        = Marshal.PtrToStructure <Boxa>(intPtr);

        Box[] boxes = new Box[boxa.n];

        for (int index = 0; index < boxes.Length; index++)
        {
            if (confidence[index] >= MinimumConfidence)
            {
                IntPtr boxPtr = Marshal.ReadIntPtr(boxa.box, index * pointerSize);
                boxes[index] = Marshal.PtrToStructure <Box>(boxPtr);
                Box box = boxes[index];
                DrawLines(_highlightedTexture,
                          new Rect(box.x, _highlightedTexture.height - box.y - box.h, box.w, box.h),
                          Color.green);
            }
        }

        IntPtr stringPtr = TessBaseAPIGetUTF8Text(_tessHandle);

        Marshal.FreeHGlobal(imagePtr);
        if (stringPtr.Equals(IntPtr.Zero))
        {
            return(null);
        }

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
        string recognizedText = Marshal.PtrToStringAnsi(stringPtr);
#else
        string recognizedText = Marshal.PtrToStringAuto(stringPtr);
#endif

        TessBaseAPIClear(_tessHandle);
        TessDeleteText(stringPtr);

        string[]      words  = recognizedText.Split(new[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        StringBuilder result = new StringBuilder();

        for (i = 0; i < boxes.Length; i++)
        {
            Debug.Log(words[i] + " -> " + confidence[i]);
            if (confidence[i] >= MinimumConfidence)
            {
                result.Append(words[i]);
                result.Append(" ");
            }
        }

        return(result.ToString());
    }
Beispiel #31
0
    public static unsafe void TestBasics()
    {
        if (sizeof(void*) == 4)
        {
            // Skip IntPtr tests on 32-bit platforms
            return;
        }

        IntPtr p;
        int i;
        long l;

        int size = IntPtr.Size;
        Assert.Equal(size, sizeof(void*));

        TestPointer(IntPtr.Zero, 0);

        i = 42;
        TestPointer(new IntPtr(i), i);
        TestPointer((IntPtr)i, i);

        i = 42;
        TestPointer(new IntPtr(i), i);

        i = -1;
        TestPointer(new IntPtr(i), i);

        l = 0x0fffffffffffffff;
        TestPointer(new IntPtr(l), l);
        TestPointer((IntPtr)l, l);

        void* pv = new IntPtr(42).ToPointer();
        TestPointer(new IntPtr(pv), 42);
        TestPointer((IntPtr)pv, 42);

        p = IntPtr.Add(new IntPtr(42), 5);
        TestPointer(p, 42 + 5);

        // Add is spected NOT to generate an OverflowException
        p = IntPtr.Add(new IntPtr(0x7fffffffffffffff), 5);
        unchecked
        {
            TestPointer(p, (long)0x8000000000000004);
        }

        p = IntPtr.Subtract(new IntPtr(42), 5);
        TestPointer(p, 42 - 5);

        bool b;
        p = new IntPtr(42);
        b = p.Equals(null);
        Assert.False(b);
        b = p.Equals((object)42);
        Assert.False(b);
        b = p.Equals((object)(new IntPtr(42)));
        Assert.True(b);

        int h = p.GetHashCode();
        int h2 = p.GetHashCode();
        Assert.Equal(h, h2);

        p = new IntPtr(42);
        i = (int)p;
        Assert.Equal(i, 42);
        l = (long)p;
        Assert.Equal(l, 42);
        IntPtr p2;
        p2 = (IntPtr)i;
        Assert.Equal(p, p2);
        p2 = (IntPtr)l;
        Assert.Equal(p, p2);
        p2 = (IntPtr)(p.ToPointer());
        Assert.Equal(p, p2);
        p2 = new IntPtr(40) + 2;
        Assert.Equal(p, p2);
        p2 = new IntPtr(44) - 2;
        Assert.Equal(p, p2);

        p = new IntPtr(0x7fffffffffffffff);
        Assert.Throws<OverflowException>(() => { i = (int)p; });
    }
 internal static bool IsNull(IntPtr pointer)
 {
     return(pointer.Equals(IntPtr.Zero));
 }
Beispiel #33
0
    public bool NegTest2()
    {
        bool retVal = true;
        try
        {
            int anyAddr = TestLibrary.Generator.GetInt32(-55);
            if (anyAddr == Int32.MaxValue)
                anyAddr -= 1;
            else if (anyAddr == Int32.MinValue)
                anyAddr += 1;

            System.IntPtr ip1 = new IntPtr(anyAddr);
            System.IntPtr ip2 = new IntPtr(anyAddr + 1);
            System.IntPtr ip3 = new IntPtr(anyAddr - 1);
            if (ip1.Equals(ip2))
            {
                TestLibrary.TestFramework.LogError("002", "expect two IntPtrs NOT equals");
                retVal = false;
            }

            if (ip1.Equals(ip3))
            {
                TestLibrary.TestFramework.LogError("002", "expect two IntPtrs NOT equals");
                retVal = false;
            }


        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }
        return retVal;
    }
Beispiel #34
0
 public bool Equals([AllowNull] ALContext other)
 {
     return(Handle.Equals(other.Handle));
 }
        // WSMan will make sure this callback is synchronously called ie., if 1 callback
        // is active, the callback will not be called from a different thread.
        private static void OnRemoteSessionDataReceived(IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            tracer.WriteLine("Client Session TM: OnRemoteDataReceived callback.");

            long sessionTMHandle = 0;
            WSManClientSessionTransportManager sessionTM = null;
            if (!TryGetSessionTransportManager(operationContext, out sessionTM, out sessionTMHandle))
            {
                // We dont have the session TM handle..just return.
                tracer.WriteLine("Unable to find a transport manager for context {0}.", sessionTMHandle);
                return;
            }

            sessionTM.ClearReceiveOrSendResources(flags, false);

            if (sessionTM.isClosed)
            {
                tracer.WriteLine("Client Session TM: Transport manager is closed. So returning");
                return;
            }

            if (!shellOperationHandle.Equals(sessionTM._wsManShellOperationHandle))
            {
                // WSMan returned data from a wrong shell..notify the caller
                // about the same.
                PSRemotingTransportException e = new PSRemotingTransportException(
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ReceiveExFailed, sessionTM.ConnectionInfo.ComputerName));
                TransportErrorOccuredEventArgs eventargs =
                    new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx);
                sessionTM.ProcessWSManTransportError(eventargs);

                return;
            }

            if (IntPtr.Zero != error)
            {
                WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);

                if (errorStruct.errorCode != 0)
                {
                    tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail);

                    TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(
                        sessionTM.WSManAPIData.WSManAPIHandle,
                        sessionTM,
                        errorStruct,
                        TransportMethodEnum.ReceiveShellOutputEx,
                        RemotingErrorIdStrings.ReceiveExCallBackError,
                        new object[] { sessionTM.ConnectionInfo.ComputerName, WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) });
                    sessionTM.ProcessWSManTransportError(eventargs);

                    return;
                }
            }

            WSManNativeApi.WSManReceiveDataResult dataReceived = WSManNativeApi.WSManReceiveDataResult.UnMarshal(data);
            if (null != dataReceived.data)
            {
                tracer.WriteLine("Session Received Data : {0}", dataReceived.data.Length);
                PSEtwLog.LogAnalyticInformational(
                    PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None,
                    PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
                    sessionTM.RunspacePoolInstanceId.ToString(),
                    Guid.Empty.ToString(),
                    dataReceived.data.Length.ToString(CultureInfo.InvariantCulture));
                sessionTM.ProcessRawData(dataReceived.data, dataReceived.stream);
            }
        }
Beispiel #36
0
        // Callback function for Keyboard hook.
        private static IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                IntPtr active = GetForegroundWindow();
                if (!(active.Equals(self.MainWindowHandle) || active.Equals(GUIManager.GUIHandle)))
                {
                    inputStatus = KEYBOARD_IDLE;
                    GUIManager.disappear();
                }

                #region KeyCheck
                else
                {
                    currDoc = ThisAddIn.getCurrDocument();
                    int vkCode = Marshal.ReadInt32(lParam);

                    if (active.Equals(GUIManager.GUIHandle))
                    {
                        hotkeyTimer.Start();

                        int maxCount = tempList.Count - wrappedPage * REFERENCE_PER_PAGE - 1;

                        if (vkCode == KeyboardMapping.Keys["1"])
                        {
                            selectedItem = Math.Min(0, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["2"])
                        {
                            selectedItem = Math.Min(1, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["3"])
                        {
                            selectedItem = Math.Min(2, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["4"])
                        {
                            selectedItem = Math.Min(3, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["5"])
                        {
                            selectedItem = Math.Min(4, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["VK_LEFT"])
                        {
                            if (wrappedPage > 0)
                            {
                                wrappedPage -= 1;
                            }
                            selectedItem = 0;
                        }
                        else if (vkCode == KeyboardMapping.Keys["VK_RIGHT"])
                        {
                            if (wrappedPage < maxPage)
                            {
                                wrappedPage += 1;
                                selectedItem = 0;
                            }
                            else
                            {
                                selectedItem = maxCount;
                            }
                        }

                        GUIManager.chooseItem(selectedItem, wrappedPage);
                    }


                    if (inputStatus == KEYBOARD_IDLE)
                    {
                        // Register place for starting typing.
                        inputStatus = KEYBOARD_TYPING;
                        Messenger.message("User is Typing!");
                        selStart = currDoc.Application.Selection.End;

                        //start Timer
                        resetTimer();
                    }
                    else if (inputStatus == KEYBOARD_TYPING)
                    {
                        resetTimer();
                    }
                    else if (inputStatus == KEYBOARD_PREFLISTSHOWED)
                    {
                        if (checkHotKey(vkCode, extendSentenceHotKey, 1))
                        {
                            string extending = tempList[wrappedPage * REFERENCE_PER_PAGE + selectedItem].getContent();

                            sentenceLength.Add(extending.Length);
                            int tempPos = selEnd;

                            // Print string
                            currDoc.Application.Selection.Start = selEnd;
                            currDoc.Application.Selection.End   = selEnd;
                            currDoc.Application.Selection.TypeText(extending);

                            // Move cursor
                            selEnd   = tempPos + extending.Length;
                            selStart = tempPos;
                            rng      = currDoc.Range(selStart, selEnd);
                            rng.Select();

                            Messenger.message("Sentence Extended!");
                        }
                        else if (checkHotKey(vkCode, deleteSentenceHotKey, 4))
                        {
                            if (sentenceLength.Any())
                            {
                                int lastAdded = sentenceLength.Count - 1;
                                selStart = selEnd - sentenceLength[lastAdded];
                                rng      = currDoc.Range(selStart, selEnd);
                                rng.Delete();
                                sentenceLength.RemoveAt(lastAdded);

                                if (sentenceLength.Any())
                                {
                                    lastAdded = sentenceLength.Count - 1;
                                    selEnd    = selStart;
                                    selStart  = selEnd - sentenceLength[lastAdded];
                                    rng       = currDoc.Range(selStart, selEnd);
                                    rng.Select();
                                }
                                else
                                {
                                    selEnd = selStart;
                                    rng    = currDoc.Range(selStart, selEnd);
                                    rng.Select();
                                }

                                Messenger.message("Sentence Reverted!");
                            }
                            else
                            {
                                Messenger.message("Nothing extended yet!");
                            }
                        }
                        else if (vkCode == KeyboardMapping.Keys["SPACE"])
                        {
                            Messenger.message("KeyboardStatRestored!\n");

                            selStart = selEnd;
                            rng      = currDoc.Range(selStart, selEnd);
                            rng.Select();

                            GUIManager.disappear();
                            inputStatus    = KEYBOARD_TYPING;
                            sentenceLength = new List <int>();
                        }
                    }
                }
                #endregion
            }
            return(CallNextHookEx(_hookID, nCode, wParam, lParam));
        }
        private static void OnRemoteCmdDataReceived(IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            tracer.WriteLine("Remote Command DataReceived callback.");

            long cmdContextId = 0;
            WSManClientCommandTransportManager cmdTM = null;
            if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId))
            {
                // We dont have the command TM handle..just return.
                tracer.WriteLine("Unable to find a transport manager for the given command context {0}.", cmdContextId);
                return;
            }

            if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) ||
                (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle)))
            {
                // WSMan returned data from a wrong shell..notify the caller
                // about the same.
                tracer.WriteLine("CmdReceive callback: ShellOperationHandles are not the same as the Receive is initiated with");
                PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.CommandReceiveExFailed);
                TransportErrorOccuredEventArgs eventargs =
                    new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveCommandOutputEx);
                cmdTM.ProcessWSManTransportError(eventargs);

                return;
            }

            // release the resources related to receive
            cmdTM.ClearReceiveOrSendResources(flags, false);

            // if the transport manager is already closed..ignore the errors and return            
            if (cmdTM.isClosed)
            {
                tracer.WriteLine("Client Command TM: Transport manager is closed. So returning");
                return;
            }

            if (IntPtr.Zero != error)
            {
                WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                if (errorStruct.errorCode != 0)
                {
                    tracer.WriteLine("CmdReceive callback: WSMan reported an error: {0}", errorStruct.errorDetail);

                    TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(
                        cmdTM._sessnTm.WSManAPIData.WSManAPIHandle,
                        null,
                        errorStruct,
                        TransportMethodEnum.ReceiveCommandOutputEx,
                        RemotingErrorIdStrings.CommandReceiveExCallBackError,
                        new object[] { errorStruct.errorDetail });
                    cmdTM.ProcessWSManTransportError(eventargs);

                    return;
                }
            }

            if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_RECEIVE_DELAY_STREAM_REQUEST_PROCESSED)
            {
                cmdTM._isDisconnectedOnInvoke = true;
                cmdTM.RaiseDelayStreamProcessedEvent();
                return;
            }

            WSManNativeApi.WSManReceiveDataResult dataReceived = WSManNativeApi.WSManReceiveDataResult.UnMarshal(data);
            if (null != dataReceived.data)
            {
                tracer.WriteLine("Cmd Received Data : {0}", dataReceived.data.Length);
                PSEtwLog.LogAnalyticInformational(
                    PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None,
                    PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
                    cmdTM.RunspacePoolInstanceId.ToString(),
                    cmdTM.powershellInstanceId.ToString(),
                    dataReceived.data.Length.ToString(CultureInfo.InvariantCulture));
                cmdTM.ProcessRawData(dataReceived.data, dataReceived.stream);
            }
        }
Beispiel #38
0
 public bool Equals(WindowCompositionAttributeData other)
 {
     return(Attribute == other.Attribute &&
            Data.Equals(other.Data) &&
            SizeOfData == other.SizeOfData);
 }
Beispiel #39
0
 unsafe public bool NegTest3()
 {
     bool retVal = true;
     try
     {
         object o = new Object();
         System.IntPtr ip = new IntPtr(TestLibrary.Generator.GetInt32(-55));
         if (ip.Equals(o))
         {
             TestLibrary.TestFramework.LogError("003", "expect IntPtr NOT equals an object referece");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
Beispiel #40
0
 public static void TestEquals(IntPtr ptr1, object obj, bool expected)
 {
     if (obj is IntPtr)
     {
         IntPtr ptr2 = (IntPtr)obj;
         Assert.Equal(expected, ptr1 == ptr2);
         Assert.Equal(!expected, ptr1 != ptr2);
         Assert.Equal(expected, ptr1.GetHashCode().Equals(ptr2.GetHashCode()));
     }
     Assert.Equal(expected, ptr1.Equals(obj));
     Assert.Equal(ptr1.GetHashCode(), ptr1.GetHashCode());
 }
Beispiel #41
0
 /// <summary>
 ///     Determines whether the specified <see cref="EGLDisplay" />, is equal to this instance.
 /// </summary>
 /// <param name="other">The <see cref="EGLDisplay" /> to compare with this instance.</param>
 /// <returns>
 ///     <c>true</c> if the specified <see cref="EGLDisplay" /> is equal to this instance; otherwise, <c>false</c>.
 /// </returns>
 public bool Equals(EGLDisplay other) => handle.Equals(other.handle);
        private static void OnRemoteSessionSendCompleted(IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            tracer.WriteLine("Client Session TM: SendComplete callback received");

            long sessionTMHandle = 0;
            WSManClientSessionTransportManager sessionTM = null;
            if (!TryGetSessionTransportManager(operationContext, out sessionTM, out sessionTMHandle))
            {
                // We dont have the session TM handle..just return.
                tracer.WriteLine("Unable to find a transport manager for context {0}.", sessionTMHandle);
                return;
            }

            // do the logging for this send
            PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived,
                PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
                sessionTM.RunspacePoolInstanceId.ToString(), Guid.Empty.ToString());

            if (!shellOperationHandle.Equals(sessionTM._wsManShellOperationHandle))
            {
                // WSMan returned data from a wrong shell..notify the caller
                // about the same.
                PSRemotingTransportException e = new PSRemotingTransportException(
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.SendExFailed, sessionTM.ConnectionInfo.ComputerName));
                TransportErrorOccuredEventArgs eventargs =
                    new TransportErrorOccuredEventArgs(e, TransportMethodEnum.SendShellInputEx);
                sessionTM.ProcessWSManTransportError(eventargs);

                return;
            }

            sessionTM.ClearReceiveOrSendResources(flags, true);

            // if the session is already closed ignore the errors and return.
            if (sessionTM.isClosed)
            {
                tracer.WriteLine("Client Session TM: Transport manager is closed. So returning");
                return;
            }

            if (IntPtr.Zero != error)
            {
                WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);

                // Ignore operation aborted error. operation aborted is raised by WSMan to 
                // notify operation complete. PowerShell protocol has its own
                // way of notifying the same using state change events.
                if ((errorStruct.errorCode != 0) && (errorStruct.errorCode != 995))
                {
                    tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail);

                    TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(
                        sessionTM.WSManAPIData.WSManAPIHandle,
                        sessionTM,
                        errorStruct,
                        TransportMethodEnum.SendShellInputEx,
                        RemotingErrorIdStrings.SendExCallBackError,
                        new object[] { sessionTM.ConnectionInfo.ComputerName, WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) });
                    sessionTM.ProcessWSManTransportError(eventargs);

                    return;
                }
            }

            // Send the next item, if available
            sessionTM.SendOneItem();
        }
Beispiel #43
0
        /// <summary>
        /// Gets the page.
        /// </summary>
        /// <param name="getNextPage">if set to <c>true</c> [get next page].</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns></returns>
        List <DataSourceShell> GetPage(ShellAPI.IEnumIDList pEnum)
        {
            IntPtr pIDLChild           = IntPtr.Zero;
            Int32  iGotChild           = 0;
            List <DataSourceShell> lst = new List <DataSourceShell>();

            pEnum.Next(1, out pIDLChild, out iGotChild);
            while (!pIDLChild.Equals(IntPtr.Zero) && iGotChild == 1)
            {
                SpecialFolderType specialFolderType = CheckSpecialFolderType(shellFolder, ptrIDL, pIDLChild);
                if (specialFolderType != SpecialFolderType.Internet &&
                    specialFolderType != SpecialFolderType.RecycleBin &&
                    specialFolderType != SpecialFolderType.MyComputerControlPanel &&
                    specialFolderType != SpecialFolderType.DesktopControlPanel &&
                    (SpecialFolderType != SpecialFolderType.MyComputer ||
                     (specialFolderType != SpecialFolderType.MyDocuments &&
                      specialFolderType != SpecialFolderType.SharedDocuments))
                    )
                {
                    // Create the new ShellItem object.
                    DataSourceShell shItem = new DataSourceShell(shellRoot, pIDLChild, this, false, specialFolderType);
                    if (shItem.IsFolder && !shItem.IsStream)
                    {
                        lst.Add(shItem);
                    }
                }

                // Free the PIDL and reset counters.
                Marshal.FreeCoTaskMem(pIDLChild);
                pIDLChild = IntPtr.Zero;
                iGotChild = 0;

                // Grab the next item.
                pEnum.Next(1, out pIDLChild, out iGotChild);
            }

            if (this.SpecialFolderType != SpecialFolderType.MyComputer)
            {
                List <DataSourceShell>      tempLst  = new List <DataSourceShell>();
                IComparer <DataSourceShell> comparer = new SortAscending();
                for (int i = 0; isRoot && i < lst.Count; i++)
                {
                    if (lst[i].SpecialFolderType == SpecialFolderType.MyComputer ||
                        lst[i].SpecialFolderType == SpecialFolderType.DesktopControlPanel ||
                        lst[i].SpecialFolderType == SpecialFolderType.Network ||
                        lst[i].SpecialFolderType == SpecialFolderType.MyDocuments ||
                        lst[i].SpecialFolderType == SpecialFolderType.SharedDocuments ||
                        lst[i].SpecialFolderType == SpecialFolderType.CurrentUserProfile
                        )
                    {
                        tempLst.Add(lst[i]);
                        lst.RemoveAt(i);
                        i--;
                    }
                }
                lst.Sort(comparer);
                for (int i = 0; isRoot && i < tempLst.Count; i++)
                {
                    lst.Insert(i, tempLst[i]);
                }
            }
            return(lst);
        }
        private static void OnRemoteCmdSendCompleted(IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            tracer.WriteLine("SendComplete callback received");

            long cmdContextId = 0;
            WSManClientCommandTransportManager cmdTM = null;
            if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId))
            {
                // We dont have the command TM handle..just return.
                tracer.WriteLine("Unable to find a transport manager for the command context {0}.", cmdContextId);
                return;
            }

            cmdTM._isSendingInput = false;

            // do the logging for this send
            PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived,
                PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
                cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString());

            if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) ||
                (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle)))
            {
                tracer.WriteLine("SendShellInputEx callback: ShellOperationHandles are not the same as the Send is initiated with");
                // WSMan returned data from a wrong shell..notify the caller
                // about the same.
                PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.CommandSendExFailed);
                TransportErrorOccuredEventArgs eventargs =
                    new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CommandInputEx);
                cmdTM.ProcessWSManTransportError(eventargs);

                return;
            }

            // release the resources related to send
            cmdTM.ClearReceiveOrSendResources(flags, true);

            // if the transport manager is already closed..ignore the errors and return           
            if (cmdTM.isClosed)
            {
                tracer.WriteLine("Client Command TM: Transport manager is closed. So returning");

                if (cmdTM._isDisconnectPending)
                {
                    cmdTM.RaiseReadyForDisconnect();
                }

                return;
            }

            if (IntPtr.Zero != error)
            {
                WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                // Ignore Command aborted error. Command aborted is raised by WSMan to 
                // notify command operation complete. PowerShell protocol has its own
                // way of notifying the same using state change events.
                if ((errorStruct.errorCode != 0) && (errorStruct.errorCode != 995))
                {
                    tracer.WriteLine("CmdSend callback: WSMan reported an error: {0}", errorStruct.errorDetail);

                    TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(
                        cmdTM._sessnTm.WSManAPIData.WSManAPIHandle,
                        null,
                        errorStruct,
                        TransportMethodEnum.CommandInputEx,
                        RemotingErrorIdStrings.CommandSendExCallBackError,
                        new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) });
                    cmdTM.ProcessWSManTransportError(eventargs);

                    return;
                }
            }

            // Send the next item, if available
            cmdTM.SendOneItem();
        }
Beispiel #45
0
        public List <DataSourceShell> GetFolderByPage(int pageSize, int pageindex, out bool isEndPage)
        {
            ShellAPI.IEnumIDList shllEnum = null;
            IntPtr ptrIDLChild            = IntPtr.Zero;
            Int32  isGotChild             = 0;


            List <DataSourceShell> lst = new List <DataSourceShell>();

            LogHelper.DebugFormat("shell GetFolderByPage ==>{0}", this.ParsingName);

            if (this._blibrary) //support for windows 7 library
            {
                #region For library
                ShellAPI.IShellItem psi;
                if (ShellAPI.SHCreateShellItem(IntPtr.Zero, null, PIDL, out psi) == 0)
                {
                    Int32 length = 0;
                    if (ShellAPI.SHLoadLibraryFromItem(psi, ref length) == 0)
                    {
                        for (int i = 0; i <= length; i++)
                        {
                            ShellAPI.IShellItem psiarry;
                            if (ShellAPI.SHGetShellItemsAt(psi, i, out psiarry) == 0)
                            {
                                DataSourceShell shItem = new DataSourceShell(psiarry);
                                lst.Add(shItem);
                            }
                        }
                        isEndPage = true;
                        return(lst);
                    }
                }
                #endregion
            }


            #region init
            isEndPage = false;
            // Get the IEnumIDList interface pointer.
            ShellAPI.SHCONTF flags = ShellAPI.SHCONTF.SHCONTF_FOLDERS;
            if (shllEnum != null)
            {
                Marshal.ReleaseComObject(shllEnum);
            }

            uint result = ShellFolder.EnumObjects(IntPtr.Zero,
                                                  flags
                                                  , out shllEnum);

            if (result != 0)
            {
                isEndPage = true;
                LogHelper.Debug("result != 0   ==> true");
                return(null);
            }
            #endregion

            #region reset enum
            ptrIDLChild = IntPtr.Zero;
            isGotChild  = 0;
            shllEnum.Reset();
            #endregion

            #region skip pageIndex*pageSize
            // Grab the first enumeration.
            for (int i = 0; i <= ((pageindex - 1) * pageSize); i++)
            {
                // Free the PIDL and reset counters.
                Marshal.FreeCoTaskMem(ptrIDLChild);
                ptrIDLChild = IntPtr.Zero;
                isGotChild  = 0;

                // Grab the next item.
                shllEnum.Next(1, out ptrIDLChild, out isGotChild);
            }
            #endregion

            LogHelper.Debug("enum .....");

            #region enum item

            int itemIndex = 0;
            while (itemIndex < pageSize)
            {
                SpecialFolderType specialFolderType = CheckSpecialFolderType(shellFolder, ptrIDL, ptrIDLChild);
                if (specialFolderType != SpecialFolderType.Internet &&
                    specialFolderType != SpecialFolderType.RecycleBin &&
                    specialFolderType != SpecialFolderType.MyComputerControlPanel &&
                    specialFolderType != SpecialFolderType.DesktopControlPanel &&
                    (SpecialFolderType != SpecialFolderType.MyComputer ||
                     (specialFolderType != SpecialFolderType.MyDocuments &&
                      specialFolderType != SpecialFolderType.SharedDocuments))
                    )
                {
                    LogHelper.DebugFormat("enum-1   : {0}", ptrIDLChild);
                    // Create the new ShellItem object.
                    DataSourceShell shItem = new DataSourceShell(shellRoot, ptrIDLChild, this, false, specialFolderType);
                    if (shItem.IsFolder && !shItem.IsStream)
                    {
                        lst.Add(shItem);
                    }

                    LogHelper.DebugFormat("enum  : {0}", shItem.ParsingName);
                }
                // Free the PIDL and reset counters.
                Marshal.FreeCoTaskMem(ptrIDLChild);
                ptrIDLChild = IntPtr.Zero;
                isGotChild  = 0;

                // Grab the next item.
                shllEnum.Next(1, out ptrIDLChild, out isGotChild);
                if (ptrIDLChild.Equals(IntPtr.Zero) && isGotChild == 0)
                {
                    LogHelper.Debug("ptrIDLChild.Equals(IntPtr.Zero) && iGotChild == 0   ==> true");
                    isEndPage = true;
                    break;
                }
                itemIndex++;
            }
            #endregion

            LogHelper.Debug("enum <==");
            #region sort item
            // AH: If _getfolders flag is true, sort treeview items.
            if (this.SpecialFolderType != SpecialFolderType.MyComputer)
            {
                List <DataSourceShell>      tempLst  = new List <DataSourceShell>();
                IComparer <DataSourceShell> comparer = new SortAscending();
                for (int i = 0; isRoot && i < lst.Count; i++)
                {
                    if (lst[i].SpecialFolderType == SpecialFolderType.MyComputer ||
                        lst[i].SpecialFolderType == SpecialFolderType.DesktopControlPanel ||
                        lst[i].SpecialFolderType == SpecialFolderType.Network ||
                        lst[i].SpecialFolderType == SpecialFolderType.MyDocuments ||
                        lst[i].SpecialFolderType == SpecialFolderType.SharedDocuments ||
                        lst[i].SpecialFolderType == SpecialFolderType.CurrentUserProfile
                        )
                    {
                        tempLst.Add(lst[i]);
                        lst.RemoveAt(i);
                        i--;
                    }
                }
                lst.Sort(comparer);
                for (int i = 0; isRoot && i < tempLst.Count; i++)
                {
                    lst.Insert(i, tempLst[i]);
                }
            }
            #endregion
            LogHelper.Debug("enum end==");
            return(lst);
        }
        private static void OnReconnectCmdCompleted(IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            long cmdContextId = 0;
            WSManClientCommandTransportManager cmdTM = null;
            if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId))
            {
                // We dont have the command TM handle..just return.
                tracer.WriteLine("Unable to find a transport manager for the given command context {0}.", cmdContextId);
                return;
            }

            if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) ||
               (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle)))
            {
                // WSMan returned data from a wrong shell..notify the caller
                // about the same.
                tracer.WriteLine("Cmd Signal callback: ShellOperationHandles are not the same as the signal is initiated with");
                PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ReconnectShellCommandExCallBackError);
                TransportErrorOccuredEventArgs eventargs =
                    new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReconnectShellCommandEx);
                cmdTM.ProcessWSManTransportError(eventargs);

                return;
            }

            if (IntPtr.Zero != error)
            {
                WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                if (errorStruct.errorCode != 0)
                {
                    tracer.WriteLine("OnReconnectCmdCompleted callback: WSMan reported an error: {0}", errorStruct.errorDetail);

                    TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(
                        cmdTM._sessnTm.WSManAPIData.WSManAPIHandle,
                        null,
                        errorStruct,
                        TransportMethodEnum.ReconnectShellCommandEx,
                        RemotingErrorIdStrings.ReconnectShellCommandExCallBackError,
                         new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) });
                    cmdTM.ProcessWSManTransportError(eventargs);

                    return;
                }
            }

            // The command may have been disconnected before all input was read or 
            // the returned command data started to be received.
            cmdTM._shouldStartReceivingData = true;
            cmdTM.SendOneItem();

            cmdTM.RaiseReconnectCompleted();
        }
Beispiel #47
0
        private Packet _getPacket()
        {
            Packet thePacket     = new Packet();
            uint   theBufferSize = 0;

            byte[] theBuffer = new byte[0];

            for (; ;)
            {
                IntPtr theTempBuffer = Marshal.AllocHGlobal(ASYNC_DATA_SIZE);
                byte[] theNewBuffer;
                UInt32 theBytesReturned = 0;
                DeviceIoControl(gHandle, IOCTL_ASYNC_IN, IntPtr.Zero, 0, theTempBuffer, (uint)ASYNC_DATA_SIZE, ref theBytesReturned, IntPtr.Zero);
                theBufferSize += ASYNC_DATA_SIZE;
                theNewBuffer   = new byte[theBufferSize];
                theBuffer.CopyTo(theNewBuffer, 0);
                Marshal.Copy(theTempBuffer, theNewBuffer, (Int32)theBufferSize - ASYNC_DATA_SIZE, ASYNC_DATA_SIZE);
                theBuffer = theNewBuffer;

                if (!theTempBuffer.Equals(IntPtr.Zero))
                {
                    Marshal.FreeHGlobal(theTempBuffer);
                }

                if (theBytesReturned != ASYNC_DATA_SIZE)
                {
                    IntPtr packetPtr = Marshal.AllocHGlobal(theBuffer.Length);
                    Marshal.Copy(theBuffer, 0, packetPtr, theBuffer.Length);

                    thePacket = _marshalPacket(packetPtr, theBytesReturned, 0);

                    if (!packetPtr.Equals(IntPtr.Zero))
                    {
                        Marshal.FreeHGlobal(packetPtr);
                    }
                    break;
                }
            }

            if ((thePacket.mPacketType == Pid_USB_Protocol_Layer) && (thePacket.mPacketId == Pid_Data_Available))
            {
                IntPtr packetBuffer     = Marshal.AllocHGlobal(MAX_BUFFER_SIZE);
                UInt32 packetBufferSize = 0;

                IntPtr tmpBuffer        = Marshal.AllocHGlobal(MAX_BUFFER_SIZE);
                UInt32 theBytesReturned = 1;

                int offset = 0;

                while (theBytesReturned > 0)
                {
                    ReadFile(gHandle, tmpBuffer, MAX_BUFFER_SIZE, ref theBytesReturned, IntPtr.Zero);
                    packetBufferSize += theBytesReturned;
                    for (int i = 0; i < theBytesReturned; i++)
                    {
                        Marshal.WriteByte(packetBuffer, (Int32)packetBufferSize, Marshal.ReadByte(tmpBuffer, i));
                    }

                    thePacket = _marshalPacket(packetBuffer, packetBufferSize, offset);
                    offset   += thePacket.mDataSize;
                    _pqueue.Enqueue(thePacket);
                }

                if (!packetBuffer.Equals(IntPtr.Zero))
                {
                    Marshal.FreeHGlobal(packetBuffer);
                }
            }
            else
            {
                _pqueue.Enqueue(thePacket);
            }

            return(_pqueue.Dequeue());
        }
Beispiel #48
0
        private bool _obtainDeviceHandle()
        {
            try
            {
                // Used to capture how many bytes are returned by system calls
                UInt32 theBytesReturned = 0;

                // SetupAPI32.DLL Data Structures
                SP_DEVICE_INTERFACE_DETAIL_DATA theDevDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                SP_DEVINFO_DATA theDevInfoData = new SP_DEVINFO_DATA();
                theDevInfoData.cbSize = Marshal.SizeOf(theDevInfoData);
                IntPtr theDevInfo = SetupDiGetClassDevs(ref DeviceGuid, IntPtr.Zero, IntPtr.Zero, (int)(DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE));
                SP_DEVICE_INTERFACE_DATA theInterfaceData = new SP_DEVICE_INTERFACE_DATA();
                theInterfaceData.cbSize = Marshal.SizeOf(theInterfaceData);

                // Check for a Garmin Device
                if (!SetupDiEnumDeviceInterfaces(theDevInfo, IntPtr.Zero, ref DeviceGuid, 0, ref theInterfaceData) && GetLastError() == ERROR_NO_MORE_ITEMS)
                {
                    gHandle = null;
                    return(false);
                }

                // Get the device's file path
                SetupDiGetDeviceInterfaceDetail(theDevInfo, ref theInterfaceData, IntPtr.Zero, 0, ref theBytesReturned, IntPtr.Zero);

                if (theBytesReturned <= 0)
                {
                    gHandle = null;
                    return(false);
                }

                IntPtr tmpBuffer = Marshal.AllocHGlobal((int)theBytesReturned);
                if (IntPtr.Size == 4)
                {
                    Marshal.WriteInt32(tmpBuffer, 4 + Marshal.SystemDefaultCharSize);
                }
                else
                {
                    Marshal.WriteInt32(tmpBuffer, 8);
                }

                theDevDetailData.cbSize = Marshal.SizeOf(theDevDetailData);
                SetupDiGetDeviceInterfaceDetail(theDevInfo, ref theInterfaceData, tmpBuffer, theBytesReturned, IntPtr.Zero, ref theDevInfoData);

                IntPtr pDevicePathName = new IntPtr(tmpBuffer.ToInt64() + 4);
                String devicePathName  = Marshal.PtrToStringAuto(pDevicePathName);

                // Create a handle to the device
                gHandle = CreateFile(devicePathName, ((UInt32)(GenericAccessRights.GenericRead | GenericAccessRights.GenericWrite)), 0, IntPtr.Zero, (UInt32)FileCreationDisposition.OpenExisting, (UInt32)FileAttributes.Normal, IntPtr.Zero);

                // Get the driver's asynchronous packet size
                if (tmpBuffer.Equals(IntPtr.Zero))
                {
                    Marshal.FreeHGlobal(tmpBuffer);
                }
                tmpBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(gUSBPacketSize));

                DeviceIoControl(gHandle, IOCTL_USB_PACKET_SIZE, IntPtr.Zero, 0, tmpBuffer, (UInt32)Marshal.SizeOf(gUSBPacketSize), ref theBytesReturned, IntPtr.Zero);

                switch (theBytesReturned)
                {
                case 2:
                    gUSBPacketSize = Marshal.ReadInt16(tmpBuffer);
                    break;

                case 4:
                    gUSBPacketSize = Marshal.ReadInt32(tmpBuffer);
                    break;

                case 8:
                    gUSBPacketSize = Marshal.ReadInt64(tmpBuffer);
                    break;
                }
                if (!tmpBuffer.Equals(IntPtr.Zero))
                {
                    Marshal.FreeHGlobal(tmpBuffer);
                }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
    //*
    //* Returns the actual path from a pointer
    //*
    private string GetFSPath( IntPtr pidl)
    {
        StringBuilder  strPath = new StringBuilder(MAX_PATH);

        //*
        //* Checks if the pointer is invalid
        //*
        if ( pidl.Equals(IntPtr.Zero) )
        {
            return "";
        }
        else
        {
            //*
            //* get { the actual path from the list
            //*
            if ( SHGetPathFromIDList(pidl, strPath) == 1 )
            {
                return strPath.ToString();
            }
            return "";
        }
    }