示例#1
0
        private static void Compare(Face2 faceTarget, Face2 faceCompare, IModelDoc2 modDoc)
        {
            //比较面
            Measure      measure;
            SelectionMgr selMgr;
            SelectData   selData;

            DispatchWrapper[] arrObjIn = new DispatchWrapper[2];
            int ret;

            measure     = modDoc.Extension.CreateMeasure();
            selMgr      = modDoc.SelectionManager;
            selData     = (SelectData)selMgr.CreateSelectData();
            arrObjIn[0] = new DispatchWrapper(faceTarget);
            arrObjIn[1] = new DispatchWrapper(faceCompare);
            ret         = selMgr.SuspendSelectionList();

            selMgr.AddSelectionListObjects((arrObjIn), selData);
            //如果两面贴合,且不为同一面
            if (measure.IsParallel & !faceTarget.IsSame(faceCompare) & measure.Distance <= 0.01)
            {
                //查找所有圆形
                //孔是否贯通
                //若否且孔到比较面的距离小于0.01则认为是漏打孔
                //
                //查找所有圆柱面
                //查找圆柱面的接合面
                //接合面是否有贴合面
                //贴合面是否至少存在一个对应孔
            }
        }
示例#2
0
        public void Ctor_Default()
        {
            var             attribute = new IDispatchConstantAttribute();
            DispatchWrapper wrapper   = Assert.IsType <DispatchWrapper>(attribute.Value);

            Assert.Null(wrapper.WrappedObject);
        }
        protected override void Command()
        {
            try
            {
                View Vue = MdlBase.eSelect_RecupererObjet <View>(1, -1);

                if (Vue.GetBodiesCount() == 0)
                {
                    WindowLog.Ecrire("Aucun corps");
                    return;
                }

                Object[] TabCorps = (Object[])Vue.Bodies;

                DispatchWrapper[] arrBodiesIn = new DispatchWrapper[Vue.GetBodiesCount()];

                for (int i = 0; i < TabCorps.Length; i++)
                {
                    arrBodiesIn[i] = new DispatchWrapper(TabCorps[i]);
                    WindowLog.Ecrire(((Body2)TabCorps[i]).Name);
                }

                Vue.Bodies = (arrBodiesIn);

                WindowLog.Ecrire(Vue.Name);
            }
            catch (Exception e)
            {
                this.LogErreur(new Object[] { e });
            }
        }
        public void Ctor_Default()
        {
            var attribute = new IDispatchConstantAttribute();

#pragma warning disable 0618 // DispatchWrapper is marked as Obsolete.
            DispatchWrapper wrapper = Assert.IsType <DispatchWrapper>(attribute.Value);
#pragma warning restore 0618
            Assert.Null(wrapper.WrappedObject);
        }
示例#5
0
 private void ConnectLoadAsyncCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (e.Error != null)
     {
         var wrapper = new DispatchWrapper(textBox6);
         ((TextBox)wrapper.WrappedObject).AppendText(e.Error.Message + "\r\n");
     }
     else if (e.Result == null)
     {
         var wrapper = new DispatchWrapper(textBox6);
         ((TextBox)wrapper.WrappedObject).AppendText(@"Error. Unable to bind DB list to ComboBoxes." + "\r\n");
     }
     else if (((List <string>)e.Result).Count == 1)
     {
         textBox6.AppendText(((List <string>)e.Result)[0] + "\r\n");
     }
     else
     {
         var ans = BindDbCombos((List <string>)e.Result);
         comboBox2.SelectedIndex = -1;
         comboBox3.SelectedIndex = -1;
         comboBox4.SelectedIndex = -1;
     }
 }
示例#6
0
        /// <summary>
        /// This thing does the saving.
        /// </summary>
        /// <param name="fl">A <see cref="System.Collections.Generic.List<>"/> of destination paths.</param>
        /// <returns>Returns a <see cref="System.Boolean"/>, indicating success.</returns>
        private Boolean SaveFiles(List <String> fl)
        {
            Int32             saveVersion     = (Int32)swSaveAsVersion_e.swSaveAsCurrentVersion;
            Int32             saveOptions     = (Int32)swSaveAsOptions_e.swSaveAsOptions_Silent;
            Int32             refErrors       = 0;
            Int32             refWarnings     = 0;
            Boolean           success         = true;
            string            tmpPath         = Path.GetTempPath();
            ModelDocExtension swModExt        = default(ModelDocExtension);
            ExportPdfData     swExportPDFData = default(ExportPdfData);

            foreach (String fileName in fl)
            {
                FileInfo fi      = new FileInfo(fileName);
                string   tmpFile = tmpPath + "\\" + fi.Name;
                if (drawingPath != String.Empty)
                {
                    swFrame.SetStatusBarText(String.Format("Checking path: '{0}'", fileName));
                    if (!CreatePath(fileName))
                    {
                        ExportPDFException e = new ExportPDFException("Unable to save file, folder could not be created.");
                        //e.Data.Add("who", System.Environment.UserName);
                        //e.Data.Add("when", DateTime.Now);
                        throw e;
                    }

                    String[]          obj  = (string[])swDraw.GetSheetNames();
                    object[]          objs = new object[obj.Length - 1];
                    DispatchWrapper[] dr   = new DispatchWrapper[obj.Length - 1];
                    for (int i = 0; i < obj.Length - 1; i++)
                    {
                        swDraw.ActivateSheet(obj[i]);
                        Sheet s = (Sheet)swDraw.GetCurrentSheet();
                        objs[i] = s;
                        dr[i]   = new DispatchWrapper(objs[i]);
                    }

                    swFrame.SetStatusBarText(String.Format("Exporting '{0}'", fileName));
                    bool layerPrint = swApp.GetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint);
                    swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint, true);
                    swExportPDFData = swApp.GetExportFileData((int)swExportDataFileType_e.swExportPdfData);
                    swModExt        = swModel.Extension;
                    success         = swExportPDFData.SetSheets((int)swExportDataSheetsToExport_e.swExportData_ExportAllSheets, (dr));
                    success         = swModExt.SaveAs(tmpFile, saveVersion, saveOptions, swExportPDFData, ref refErrors, ref refWarnings);
                    //success = swModel.SaveAs4(tmpFile, saveVersion, saveOptions, ref refErrors, ref refWarnings);

                    swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swPDFExportIncludeLayersNotToPrint, layerPrint);

                    try {
                        File.Copy(tmpFile, fileName, true);
                    } catch (UnauthorizedAccessException uae) {
                        throw new ExportPDFException(
                                  String.Format("You don't have the reqired permission to access '{0}'.", fileName),
                                  uae);
                    } catch (ArgumentException ae) {
                        throw new ExportPDFException(
                                  String.Format("Either '{0}' or '{1}' is not a proper file name.", tmpFile, fileName),
                                  ae);
                    } catch (PathTooLongException ptle) {
                        throw new ExportPDFException(
                                  String.Format("Source='{0}'; Dest='{1}' <= One of these is too long.", tmpFile, fileName),
                                  ptle);
                    } catch (DirectoryNotFoundException dnfe) {
                        throw new ExportPDFException(
                                  String.Format("Source='{0}'; Dest='{1}' <= One of these is invalid.", tmpFile, fileName),
                                  dnfe);
                    } catch (FileNotFoundException fnfe) {
                        throw new ExportPDFException(
                                  String.Format("Crap! I lost '{0}'!", tmpFile),
                                  fnfe);
                    } catch (IOException) {
                        System.Windows.Forms.MessageBox.Show(
                            String.Format("If you have the file, '{0}', selected in an Explorer window, " +
                                          "you may have to close it.", fileName), "This file is open somewhere.",
                            System.Windows.Forms.MessageBoxButtons.OK,
                            System.Windows.Forms.MessageBoxIcon.Error);
                        return(false);
                    } catch (NotSupportedException nse) {
                        throw new ExportPDFException(
                                  String.Format("Source='{0}'; Dest='{1}' <= One of these is an invalid format.",
                                                tmpFile, fileName), nse);
                    }


                    if (!File.Exists(fileName))
                    {
                        success = false;
                    }

                    if (success)
                    {
                        swFrame.SetStatusBarText(String.Format("Exported '{0}'", fileName));

                        if (fileName.StartsWith(Properties.Settings.Default.KPath) && APathSet.WriteToDb)
                        {
                            savedFile = fileName;
                            if (fileName.EndsWith("PDF"))
                            {
                                InsertIntoDb(fileName, Properties.Settings.Default.PDFTable);
                                drwKey = GetKeyCol(fi.Name);
                            }
                            if (fileName.EndsWith(@"EPRT") || fileName.EndsWith("EASM"))
                            {
                                InsertIntoDb(fileName, Properties.Settings.Default.eDrawingTable);
                            }
                        }

                        if ((fileName.StartsWith(Properties.Settings.Default.MetalPath) && fileName.EndsWith("PDF")) && APathSet.WriteToDb)
                        {
                            _metalDrawing = true;
                            InsertIntoDb(fileName, Properties.Settings.Default.metalTable);
                            drwKey = GetKeyCol(fi.Name);
                        }
                    }
                    else
                    {
                        ExportPDFException e = new ExportPDFException(String.Format("Failed to save '{0}'", fileName));
                        //e.Data.Add("who", System.Environment.UserName);
                        //e.Data.Add("when", DateTime.Now);
                        throw e;
                    }
                }
            }
            if (success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#7
0
        /// <summary>
        /// Intercept method calls
        /// </summary>
        /// <param name="myMessage">
        /// Contains information about the method being called
        /// </param>
        /// <returns>
        /// A <see cref="ReturnMessage"/>.
        /// </returns>
        public override IMessage Invoke(IMessage myMessage)
        {
            IMethodCallMessage callMessage = myMessage as IMethodCallMessage;

            if (null == callMessage)
            {
                //LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType().ToString());
                return(null);
            }

            MethodInfo method = callMessage.MethodBase as MethodInfo;

            if (null == method)
            {
                //LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase.ToString());
                return(null);
            }

            object returnValue = null;

            object[] outArgs      = null;
            int      outArgsCount = 0;

            string       methodName = method.Name;
            Type         returnType = method.ReturnType;
            BindingFlags flags      = BindingFlags.InvokeMethod;
            int          argCount   = callMessage.ArgCount;

            object invokeObject;
            Type   invokeType;
            Type   byValType;

            object[] args;
            object   arg;

            COMWrapper[] originalArgs;
            COMWrapper   wrapper;

            ParameterModifier[] argModifiers = null;
            ParameterInfo[]     parameters   = null;
            ParameterInfo       parameter;

            if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType)
            {
                this.Dispose();
            }
            else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType)
            {
                returnValue = this.ToString();
            }
            else if ("GetType" == methodName && 0 == argCount && typeof(System.Type) == returnType)
            {
                returnValue = this._InterceptType;
            }
            else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType)
            {
                returnValue = this.GetHashCode();
            }
            else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType)
            {
                returnValue = this.Equals(callMessage.Args[0]);
            }
            else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
            {
                bool removeHandler = methodName.StartsWith("remove_");
                methodName = methodName.Substring(removeHandler ? 7 : 4);

                Delegate handler = callMessage.InArgs[0] as Delegate;
                if (null == handler)
                {
                    return(new ReturnMessage(new ArgumentNullException("handler"), callMessage));
                }
            }
            else
            {
                invokeObject = this._COMObject;
                invokeType   = this._COMType;

                if (methodName.StartsWith("get_"))
                {
                    // Property Get
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.GetProperty;
                    args       = callMessage.InArgs;
                }
                else if (methodName.StartsWith("set_"))
                {
                    // Property Set
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.SetProperty;
                    args       = callMessage.InArgs;
                }
                else
                {
                    args = callMessage.Args;
                    if (null != args && 0 != args.Length)
                    {
                        // Modifiers for ref / out parameters
                        argModifiers    = new ParameterModifier[1];
                        argModifiers[0] = new ParameterModifier(args.Length);

                        parameters = method.GetParameters();
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            parameter = parameters[i];
                            if (parameter.IsOut || parameter.ParameterType.IsByRef)
                            {
                                argModifiers[0][i] = true;
                                outArgsCount++;
                            }
                        }

                        if (0 == outArgsCount)
                        {
                            argModifiers = null;
                        }
                    }
                }

                // Un-wrap wrapped COM objects before passing to the method
                if (null == args || 0 == args.Length)
                {
                    originalArgs = null;
                }
                else
                {
                    originalArgs = new COMWrapper[args.Length];
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (null != args[i] && RemotingServices.IsTransparentProxy(args[i]))
                        {
                            wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper;
                            if (null != wrapper)
                            {
                                originalArgs[i] = wrapper;
                                args[i]         = wrapper._COMObject;
                            }
                        }
                        else if (0 != outArgsCount && argModifiers[0][i])
                        {
                            byValType = GetByValType(parameters[i].ParameterType);
                            if (byValType.IsInterface)
                            {
                                // If we're passing a COM object by reference, and
                                // the parameter is null, we need to pass a
                                // DispatchWrapper to avoid a type mismatch exception.
                                if (null == args[i])
                                {
                                    args[i] = new DispatchWrapper(null);
                                }
                            }
                            else if (typeof(Decimal) == byValType)
                            {
                                // If we're passing a decimal value by reference,
                                // we need to pass a CurrencyWrapper to avoid a
                                // type mismatch exception.
                                // http://support.microsoft.com/?kbid=837378
                                args[i] = new CurrencyWrapper(args[i]);
                            }
                        }
                    }
                }

                try {
                    returnValue = invokeType.InvokeMember(methodName, flags, null, invokeObject, args, argModifiers, null, null);
                } catch (Exception ex) {
                    return(new ReturnMessage(ex, callMessage));
                }

                // Handle enum and interface return types
                if (null != returnValue)
                {
                    if (returnType.IsInterface)
                    {
                        // Wrap the returned value in an intercepting COM wrapper
                        if (Marshal.IsComObject(returnValue))
                        {
                            returnValue = COMWrapper.Wrap(returnValue, returnType);
                        }
                    }
                    else if (returnType.IsEnum)
                    {
                        // Convert to proper Enum type
                        returnValue = Enum.Parse(returnType, returnValue.ToString());
                    }
                }

                // Handle out args
                if (0 != outArgsCount)
                {
                    outArgs = new object[args.Length];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        if (!argModifiers[0][i])
                        {
                            continue;
                        }

                        arg = args[i];
                        if (null == arg)
                        {
                            continue;
                        }

                        parameter = parameters[i];
                        wrapper   = null;

                        byValType = GetByValType(parameter.ParameterType);
                        if (typeof(Decimal) == byValType)
                        {
                            if (arg is CurrencyWrapper)
                            {
                                arg = ((CurrencyWrapper)arg).WrappedObject;
                            }
                        }
                        else if (byValType.IsEnum)
                        {
                            arg = Enum.Parse(byValType, arg.ToString());
                        }
                        else if (byValType.IsInterface)
                        {
                            if (Marshal.IsComObject(arg))
                            {
                                wrapper = originalArgs[i];
                                if (null != wrapper && wrapper._COMObject != arg)
                                {
                                    wrapper.Dispose();
                                    wrapper = null;
                                }

                                if (null == wrapper)
                                {
                                    wrapper = new COMWrapper(arg, byValType);
                                }
                                arg = wrapper.GetTransparentProxy();
                            }
                        }
                        outArgs[i] = arg;
                    }
                }
            }

            return(new ReturnMessage(returnValue, outArgs, outArgsCount, callMessage.LogicalCallContext, callMessage));
        }
        private int SavePDFCopy(string fileName)
        {
            try
            {
                ModelDocExtension swModExt        = this.ModelDocument.Extension;
                ExportPdfData     swExportPDFData = (ExportPdfData)this.SolidworksApp.GetExportFileData((int)swExportDataFileType_e.swExportPdfData);
                bool     boolstatus = false;
                int      errors     = 0;
                int      warnings   = 0;
                string[] obj        = null;

                string description;
                string resolvedDescription;
                bool   wasResolved;
                string revision;
                string resolverdRevision;
                CustomPropertyManager swCustProp = swModExt.CustomPropertyManager[string.Empty];

                swCustProp.Get5("Description", false, out description, out resolvedDescription, out wasResolved);
                swCustProp.Get5("Revision", false, out revision, out resolverdRevision, out wasResolved);


                string pdffilename = fileName.ToUpper().Replace(".SLDDRW", string.Empty);

                string previousNames = pdffilename.Substring(pdffilename.LastIndexOf('\\') + 1);
                pdffilename = pdffilename.Substring(pdffilename.LastIndexOf('\\'));


                if (this.UserAddin.AppendRevision)
                {
                    pdffilename += ", Rev. " + revision;
                }

                if (this.UserAddin.AppendDescription)
                {
                    pdffilename += ", " + description;
                }

                string useDirectory;
                // find project sub-directory
                var subDir = new DirectoryInfo(this.UserAddin.PDFLocation + "\\" + previousNames.Substring(0, 2));
                if (subDir.Exists)
                {
                    useDirectory = this.UserAddin.PDFLocation + "\\" + previousNames.Substring(0, 2);
                }
                else
                {
                    useDirectory = this.UserAddin.PDFLocation;
                }

                //Delete the old versions
                if (this.UserAddin.RemovePrevious)
                {
                    var dir = new DirectoryInfo(useDirectory);

                    foreach (var file in dir.EnumerateFiles(previousNames + "*.pdf"))
                    {
                        file.Delete();
                    }
                }

                pdffilename = useDirectory + pdffilename + ".pdf";

                obj = this.doc.GetSheetNames();
                int count = 0;
                count = obj.Length;
                int               i        = 0;
                object[]          objs     = new object[count - 1];
                DispatchWrapper[] arrObjIn = new DispatchWrapper[count - 1];

                // Activate each drawing sheet, except the last drawing sheet, for
                // demonstration purposes only and add each sheet to an array
                // of drawing sheets
                for (i = 0; i < count - 1; i++)
                {
                    boolstatus = this.doc.ActivateSheet(obj[i]);
                    Sheet swSheet = (Sheet)this.doc.GetCurrentSheet();
                    objs[i]     = swSheet;
                    arrObjIn[i] = new DispatchWrapper(objs[i]);
                }

                // Save the drawings sheets to a PDF file
                swExportPDFData.SetSheets((int)swExportDataSheetsToExport_e.swExportData_ExportAllSheets, arrObjIn);
                swExportPDFData.ViewPdfAfterSaving = this.UserAddin.ShowPDF;

                swModExt.SaveAs(pdffilename, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, swExportPDFData, ref errors, ref warnings);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("Problem Saving the PDF. " + e.Message);
            }

            return(0);
        }
示例#9
0
        /// <summary>
        ///     Intercept method calls
        /// </summary>
        /// <param name="myMessage">
        ///     Contains information about the method being called
        /// </param>
        /// <returns>
        ///     A <see cref="ReturnMessage" />.
        /// </returns>
        public override IMessage Invoke(IMessage myMessage)
        {
            var callMessage = myMessage as IMethodCallMessage;

            if (null == callMessage)
            {
                Log.Debug().WriteLine("Message type not implemented: {0}", myMessage.GetType());
                return(null);
            }

            var method = callMessage.MethodBase as MethodInfo;

            if (null == method)
            {
                Log.Debug().WriteLine("Unrecognized Invoke call: {0}", callMessage.MethodBase);
                return(null);
            }

            object returnValue = null;

            object[] outArgs      = null;
            var      outArgsCount = 0;

            var methodName = method.Name;
            var returnType = method.ReturnType;
            var flags      = BindingFlags.InvokeMethod;
            var argCount   = callMessage.ArgCount;

            ParameterModifier[] argModifiers = null;
            ParameterInfo[]     parameters   = null;

            if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType)
            {
                Dispose();
            }
            else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType)
            {
                returnValue = ToString();
            }
            else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType)
            {
                returnValue = _interceptType;
            }
            else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType)
            {
                returnValue = GetHashCode();
            }
            else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType)
            {
                returnValue = Equals(callMessage.Args[0]);
            }
            else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
            {
                var removeHandler = methodName.StartsWith("remove_");
                methodName = methodName.Substring(removeHandler ? 7 : 4);
                // TODO: Something is missing here
                var handler = callMessage.InArgs[0] as Delegate;
                if (null == handler)
                {
                    return(new ReturnMessage(new ArgumentNullException(nameof(handler)), callMessage));
                }
            }
            else
            {
                var invokeObject = _comObject;
                var invokeType   = _comType;

                object[]      args;
                ParameterInfo parameter;
                if (methodName.StartsWith("get_"))
                {
                    // Property Get
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.GetProperty;
                    args       = callMessage.InArgs;
                }
                else if (methodName.StartsWith("set_"))
                {
                    // Property Set
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.SetProperty;
                    args       = callMessage.InArgs;
                }
                else
                {
                    args = callMessage.Args;
                    if (null != args && 0 != args.Length)
                    {
                        // Modifiers for ref / out parameters
                        argModifiers    = new ParameterModifier[1];
                        argModifiers[0] = new ParameterModifier(args.Length);

                        parameters = method.GetParameters();
                        for (var i = 0; i < parameters.Length; i++)
                        {
                            parameter = parameters[i];
                            if (parameter.IsOut || parameter.ParameterType.IsByRef)
                            {
                                argModifiers[0][i] = true;
                                outArgsCount++;
                            }
                        }

                        if (0 == outArgsCount)
                        {
                            argModifiers = null;
                        }
                    }
                }

                // Un-wrap wrapped COM objects before passing to the method
                Type         byValType;
                ComWrapper   wrapper;
                ComWrapper[] originalArgs;
                if (null == args || 0 == args.Length)
                {
                    originalArgs = null;
                }
                else
                {
                    originalArgs = new ComWrapper[args.Length];
                    for (var i = 0; i < args.Length; i++)
                    {
                        if (null != args[i] && RemotingServices.IsTransparentProxy(args[i]))
                        {
                            wrapper = RemotingServices.GetRealProxy(args[i]) as ComWrapper;
                            if (null != wrapper)
                            {
                                originalArgs[i] = wrapper;
                                args[i]         = wrapper._comObject;
                            }
                        }
                        else if (0 != outArgsCount && argModifiers[0][i])
                        {
                            byValType = GetByValType(parameters[i].ParameterType);
                            if (byValType.IsInterface)
                            {
                                // If we're passing a COM object by reference, and
                                // the parameter is null, we need to pass a
                                // DispatchWrapper to avoid a type mismatch exception.
                                if (null == args[i])
                                {
                                    args[i] = new DispatchWrapper(null);
                                }
                            }
                            else if (typeof(decimal) == byValType)
                            {
                                // If we're passing a decimal value by reference,
                                // we need to pass a CurrencyWrapper to avoid a
                                // type mismatch exception.
                                // http://support.microsoft.com/?kbid=837378
                                args[i] = new CurrencyWrapper(args[i]);
                            }
                        }
                    }
                }

                do
                {
                    try
                    {
                        returnValue = invokeType.InvokeMember(methodName, flags, null, invokeObject, args, argModifiers, null, null);
                        break;
                    }
                    catch (InvalidComObjectException icoEx)
                    {
                        // Should assist BUG-1616 and others
                        Log.Warn().WriteLine(
                            "COM object {0} has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.",
                            _interceptType.FullName);
                        return(new ReturnMessage(icoEx, callMessage));
                    }
                    catch (Exception ex)
                    {
                        // Test for rejected
                        var comEx = ex as COMException ?? ex.InnerException as COMException;
                        if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == RPC_E_FAIL))
                        {
                            var destinationName = _targetName;
                            // Try to find a "catchy" name for the rejecting application
                            if (destinationName != null && destinationName.Contains("."))
                            {
                                destinationName = destinationName.Substring(0, destinationName.IndexOf(".", StringComparison.Ordinal));
                            }
                            if (destinationName == null)
                            {
                                destinationName = _interceptType.FullName;
                            }

                            // TODO: Log destinationName and rejected information
                            Log.Error().WriteLine("Error while creating {0}: {1}", destinationName, comEx.ErrorCode);
                        }
                        // Not rejected OR pressed cancel
                        return(new ReturnMessage(ex, callMessage));
                    }
                } while (true);

                // Handle enum and interface return types
                if (null != returnValue)
                {
                    if (returnType.IsInterface)
                    {
                        // Wrap the returned value in an intercepting COM wrapper
                        if (Marshal.IsComObject(returnValue))
                        {
                            returnValue = Wrap(returnValue, returnType, _targetName);
                        }
                    }
                    else if (returnType.IsEnum)
                    {
                        // Convert to proper Enum type
                        returnValue = Enum.Parse(returnType, returnValue.ToString());
                    }
                }

                // Handle out args
                if (0 != outArgsCount)
                {
                    outArgs = new object[args.Length];
                    for (var i = 0; i < parameters.Length; i++)
                    {
                        if (!argModifiers[0][i])
                        {
                            continue;
                        }

                        var arg = args[i];
                        if (null == arg)
                        {
                            continue;
                        }

                        parameter = parameters[i];
                        wrapper   = null;

                        byValType = GetByValType(parameter.ParameterType);
                        if (typeof(decimal) == byValType)
                        {
                            var currencyWrapper = arg as CurrencyWrapper;
                            if (currencyWrapper != null)
                            {
                                arg = currencyWrapper.WrappedObject;
                            }
                        }
                        else if (byValType.IsEnum)
                        {
                            arg = Enum.Parse(byValType, arg.ToString());
                        }
                        else if (byValType.IsInterface && Marshal.IsComObject(arg))
                        {
                            wrapper = originalArgs[i];
                            if (null != wrapper && wrapper._comObject != arg)
                            {
                                wrapper.Dispose();
                                wrapper = null;
                            }

                            if (null == wrapper)
                            {
                                wrapper = new ComWrapper(arg, byValType, _targetName);
                            }
                            arg = wrapper.GetTransparentProxy();
                        }
                        outArgs[i] = arg;
                    }
                }
            }

            return(new ReturnMessage(returnValue, outArgs, outArgsCount, callMessage.LogicalCallContext, callMessage));
        }
        /// <summary>
        /// Intercept method calls
        /// </summary>
        /// <param name="myMessage">
        /// Contains information about the method being called
        /// </param>
        /// <returns>
        /// A <see cref="ReturnMessage"/>.
        /// </returns>
        public override IMessage Invoke(IMessage myMessage)
        {
            IMethodCallMessage callMessage = myMessage as IMethodCallMessage;

            if (null == callMessage)
            {
                LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType().ToString());
                return(null);
            }

            MethodInfo method = callMessage.MethodBase as MethodInfo;

            if (null == method)
            {
                LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase.ToString());
                return(null);
            }

            object returnValue = null;

            object[] outArgs      = null;
            int      outArgsCount = 0;

            string       methodName = method.Name;
            Type         returnType = method.ReturnType;
            BindingFlags flags      = BindingFlags.InvokeMethod;
            int          argCount   = callMessage.ArgCount;

            object invokeObject;
            Type   invokeType;
            Type   byValType;

            object[] args;
            object   arg;

            COMWrapper[] originalArgs;
            COMWrapper   wrapper;

            ParameterModifier[] argModifiers = null;
            ParameterInfo[]     parameters   = null;
            ParameterInfo       parameter;

            if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType)
            {
                Dispose();
            }
            else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType)
            {
                returnValue = ToString();
            }
            else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType)
            {
                returnValue = _InterceptType;
            }
            else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType)
            {
                returnValue = GetHashCode();
            }
            else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType)
            {
                returnValue = Equals(callMessage.Args[0]);
            }
            else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
            {
                bool removeHandler = methodName.StartsWith("remove_");
                methodName = methodName.Substring(removeHandler ? 7 : 4);

                Delegate handler = callMessage.InArgs[0] as Delegate;
                if (null == handler)
                {
                    return(new ReturnMessage(new ArgumentNullException("handler"), callMessage));
                }
            }
            else
            {
                invokeObject = _COMObject;
                invokeType   = _COMType;

                if (methodName.StartsWith("get_"))
                {
                    // Property Get
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.GetProperty;
                    args       = callMessage.InArgs;
                }
                else if (methodName.StartsWith("set_"))
                {
                    // Property Set
                    methodName = methodName.Substring(4);
                    flags      = BindingFlags.SetProperty;
                    args       = callMessage.InArgs;
                }
                else
                {
                    args = callMessage.Args;
                    if (null != args && 0 != args.Length)
                    {
                        // Modifiers for ref / out parameters
                        argModifiers    = new ParameterModifier[1];
                        argModifiers[0] = new ParameterModifier(args.Length);

                        parameters = method.GetParameters();
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            parameter = parameters[i];
                            if (parameter.IsOut || parameter.ParameterType.IsByRef)
                            {
                                argModifiers[0][i] = true;
                                outArgsCount++;
                            }
                        }

                        if (0 == outArgsCount)
                        {
                            argModifiers = null;
                        }
                    }
                }

                // Un-wrap wrapped COM objects before passing to the method
                if (null == args || 0 == args.Length)
                {
                    originalArgs = null;
                }
                else
                {
                    originalArgs = new COMWrapper[args.Length];
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (null != args[i] && RemotingServices.IsTransparentProxy(args[i]))
                        {
                            wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper;
                            if (null != wrapper)
                            {
                                originalArgs[i] = wrapper;
                                args[i]         = wrapper._COMObject;
                            }
                        }
                        else if (0 != outArgsCount && argModifiers[0][i])
                        {
                            byValType = GetByValType(parameters[i].ParameterType);
                            if (byValType.IsInterface)
                            {
                                // If we're passing a COM object by reference, and
                                // the parameter is null, we need to pass a
                                // DispatchWrapper to avoid a type mismatch exception.
                                if (null == args[i])
                                {
                                    args[i] = new DispatchWrapper(null);
                                }
                            }
                            else if (typeof(Decimal) == byValType)
                            {
                                // If we're passing a decimal value by reference,
                                // we need to pass a CurrencyWrapper to avoid a
                                // type mismatch exception.
                                // http://support.microsoft.com/?kbid=837378
                                args[i] = new CurrencyWrapper(args[i]);
                            }
                        }
                    }
                }

                do
                {
                    try
                    {
                        returnValue = invokeType.InvokeMember(methodName, flags, null, invokeObject, args, argModifiers, null, null);
                        break;
                    }
                    catch (Exception ex)
                    {
                        // Test for rejected
                        COMException comEx = ex as COMException;
                        if (comEx == null)
                        {
                            comEx = ex.InnerException as COMException;
                        }
                        if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == RPC_E_FAIL))
                        {
                            string destinationName = _TargetName;
                            // Try to find a "catchy" name for the rejecting application
                            if (destinationName != null && destinationName.Contains("."))
                            {
                                destinationName = destinationName.Substring(0, destinationName.IndexOf("."));
                            }
                            if (destinationName == null)
                            {
                                destinationName = _InterceptType.FullName;
                            }
                            DialogResult result = MessageBox.Show(Language.GetFormattedString("com_rejected", destinationName), Language.GetString("com_rejected_title"), MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                            if (result == DialogResult.OK)
                            {
                                continue;
                            }
                        }
                        // Not rejected OR pressed cancel
                        return(new ReturnMessage(ex, callMessage));
                    }
                } while (true);

                // Handle enum and interface return types
                if (null != returnValue)
                {
                    if (returnType.IsInterface)
                    {
                        // Wrap the returned value in an intercepting COM wrapper
                        if (Marshal.IsComObject(returnValue))
                        {
                            returnValue = Wrap(returnValue, returnType, _TargetName);
                        }
                    }
                    else if (returnType.IsEnum)
                    {
                        // Convert to proper Enum type
                        returnValue = Enum.Parse(returnType, returnValue.ToString());
                    }
                }

                // Handle out args
                if (0 != outArgsCount)
                {
                    outArgs = new object[args.Length];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        if (!argModifiers[0][i])
                        {
                            continue;
                        }

                        arg = args[i];
                        if (null == arg)
                        {
                            continue;
                        }

                        parameter = parameters[i];
                        wrapper   = null;

                        byValType = GetByValType(parameter.ParameterType);
                        if (typeof(Decimal) == byValType)
                        {
                            if (arg is CurrencyWrapper)
                            {
                                arg = ((CurrencyWrapper)arg).WrappedObject;
                            }
                        }
                        else if (byValType.IsEnum)
                        {
                            arg = Enum.Parse(byValType, arg.ToString());
                        }
                        else if (byValType.IsInterface)
                        {
                            if (Marshal.IsComObject(arg))
                            {
                                wrapper = originalArgs[i];
                                if (null != wrapper && wrapper._COMObject != arg)
                                {
                                    wrapper.Dispose();
                                    wrapper = null;
                                }

                                if (null == wrapper)
                                {
                                    wrapper = new COMWrapper(arg, byValType, _TargetName);
                                }
                                arg = wrapper.GetTransparentProxy();
                            }
                        }
                        outArgs[i] = arg;
                    }
                }
            }

            return(new ReturnMessage(returnValue, outArgs, outArgsCount, callMessage.LogicalCallContext, callMessage));
        }
        private object InvokeMemberInner(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            var requireDefaultMember = string.IsNullOrWhiteSpace(name) || (name == DispIdZeroIdentifier);

            if (!requireDefaultMember && invokeAttr.HasFlag(BindingFlags.GetProperty) && invokeAttr.HasFlag(BindingFlags.InvokeMethod))
            {
                // When VBScript tries to access a member that is not clearly a property or a method (eg. "a = x.Name") then it will include binding flags GetProperty AND
                // AND InvokeMethod but we need to try to work out which of the two it is now because the IDispatchAccess code doesn't like that ambiguity.
                var nameComparison = invokeAttr.HasFlag(BindingFlags.IgnoreCase) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
                if (_template.GetProperties().Any(p => p.Name.Equals(name, nameComparison)))
                {
                    invokeAttr = invokeAttr ^ BindingFlags.InvokeMethod;                     // It's a property so remove InvokeMethod by xor'ing
                }
                else
                {
                    invokeAttr = invokeAttr ^ BindingFlags.GetProperty;                     // It's not a property so remove GetProperty by xor'ing
                }
            }

            if (invokeAttr.HasFlag(BindingFlags.GetProperty))
            {
                object value;
                if (requireDefaultMember)
                {
                    value = IDispatchAccess.GetDefaultProperty <object>(_target, args);
                }
                else
                {
                    value = IDispatchAccess.GetProperty(_target, name, args);
                }
                return(CurrencyToFloatWhereApplicable(value));
            }

            if (requireDefaultMember)
            {
                throw new Exception("Currently there is only support for default member (DispId zero) on GetProperty requests");
            }

            if (invokeAttr.HasFlag(BindingFlags.SetProperty) || invokeAttr.HasFlag(BindingFlags.PutDispProperty) || invokeAttr.HasFlag(BindingFlags.PutRefDispProperty))
            {
                var value = args[args.Length - 1];
                if ((value == null) && invokeAttr.HasFlag(BindingFlags.PutRefDispProperty))
                {
                    // When a VBScript statement "Set x = Nothing" becomes an IReflect.InvokeMember call, the invokeAttr will have value PutRefDispProperty (because it's
                    // a property setter call for an *object* reference, rather than PutDispProperty - which is for a non-object type) but the value will have been
                    // interpreted as null (.net null, not VBScript null). This will be problematic if we try to pass it on to the underlying reference through
                    // IDispatch because it will be like us saying "Set x = Empty", which will fail because Empty is not an object. So we need to look out
                    // for this case and transform the .net null back into VBScript Nothing.
                    value = new DispatchWrapper(null);
                }
                var argsWithoutValues = new object[args.Length - 1];
                Array.Copy(args, argsWithoutValues, args.Length - 1);
                IDispatchAccess.SetProperty(_target, name, value, argsWithoutValues);
                return(null);
            }

            if (invokeAttr.HasFlag(BindingFlags.InvokeMethod))
            {
                return(CurrencyToFloatWhereApplicable(IDispatchAccess.CallMethod(_target, name, args)));
            }

            throw new Exception("Don't know what to do with invokeAttr " + invokeAttr);
        }
示例#12
0
        public void Ctor_NullWindows_Success()
        {
            var wrapper = new DispatchWrapper(null);

            Assert.Null(wrapper.WrappedObject);
        }
示例#13
0
        public override void Execute()
        {
            try
            {
                DsDoc = DsApp.GetActiveDocument();
                DsMdl = DsDoc.GetModel();
                LyM   = DsDoc.GetLayerManager();
                SkM   = DsMdl.GetSketchManager();
                SlM   = DsDoc.GetSelectionManager();

                DsApp.AbortRunningCommand();

                CommandMessage CmdLine = DsApp.GetCommandMessage();
                if (null == CmdLine)
                {
                    return;
                }

                // Erreur avec le premier prompt, la commande est automatiquement annulée
                // Pour contourner le pb, on lance une commande à vide.
                {
                    String sss = "";
                    CmdLine.PromptForString(true, "", "", out sss);
                }

                SelectionFilter SlFilter;
                SlFilter = SlM.GetSelectionFilter();

                ReferenceImage Image = null;

                SlFilter.Clear();
                SlFilter.AddEntityType(dsObjectType_e.dsReferenceImageType);
                SlFilter.Active = true;

                int    NbPoint         = 5000;
                Double Jeu             = 5;
                Double DiamMin         = 5;
                Double DiamMax         = 45; // Double.PositiveInfinity;
                int    SeuilNoirs      = 8;
                int    BlancPctDiam    = 65;
                int    TypeSampler     = 2;
                int    NbAffinage      = 6;
                bool   MaillageEtPoint = false;

                CmdLine.PromptForInteger("Nb de points maximum ", NbPoint, out NbPoint);
                CmdLine.PromptForDouble("Jeu entre les cercles ", Jeu, out Jeu);
                CmdLine.PromptForDouble("Supprimer les cercles de diam inf. à ", DiamMin, out DiamMin);
                CmdLine.PromptForDouble("Réduire les cercles de diam sup. à ", DiamMax, out DiamMax);
                CmdLine.PromptForInteger("Seuil mini pour les noirs (0 à 255) ", SeuilNoirs, out SeuilNoirs);
                CmdLine.PromptForInteger("Blanc, % du diam mini (0 à 100)", BlancPctDiam, out BlancPctDiam);
                CmdLine.PromptForInteger("Type de sampler : 1 -> Poisson / 2 -> Rejection ", TypeSampler, out TypeSampler);
                CmdLine.PromptForInteger("Nb d'iteration pour l'affinage ", NbAffinage, out NbAffinage);
                CmdLine.PromptForBool("Dessiner le maillage et les points d'origine ", "Oui", "Non", MaillageEtPoint, out MaillageEtPoint);

                if (CmdLine.PromptForSelection(true, "Selectionnez l'image", "Ce n'est pas une image"))
                {
                    dsObjectType_e entityType;
                    var            count = SlM.GetSelectedObjectCount(dsSelectionSetType_e.dsSelectionSetType_Previous);

                    object selectedEntity = SlM.GetSelectedObject(dsSelectionSetType_e.dsSelectionSetType_Previous, 0, out entityType);

                    if (dsObjectType_e.dsReferenceImageType == entityType)
                    {
                        Image = (ReferenceImage)selectedEntity;
                    }
                }

                //object ObjType = null;
                //object ObjEntites = null;
                //string[] TabNomsCalques = GetTabNomsCalques(DsDoc);
                //SkM.GetEntities(SlFilter, TabNomsCalques, out ObjType, out ObjEntites);
                //object[] TabEntites = ObjEntites as object[];
                //Image = (ReferenceImage)TabEntites[0];

                TimeSpan t; DateTime DateTimeStart;

                DateTimeStart = DateTime.Now;

                if (Image != null)
                {
                    CmdLine.PrintLine(String.Format("Image : {0}", Image.GetPath()));

                    Double ImgX, ImgY, ImgZ;
                    Image.GetPosition(out ImgX, out ImgY, out ImgZ);

                    CmdLine.PrintLine("Sampler");
                    Log.Message("Sampler");

                    List <PointF> listePoint;
                    if (TypeSampler == 1)
                    {
                        Double fact1 = 2;
                        Double fact2 = 0.7;
                        CmdLine.PromptForDouble("Facteur multip. du rayon de rejection ", fact1, out fact1);
                        CmdLine.PromptForDouble("Facteur multip. du rayon minimum à l'initialisation ", fact2, out fact2);
                        listePoint = BitmapPoissonSampler.Run(Image, NbPoint, fact1, fact2);
                    }
                    else
                    {
                        listePoint = BitmapRejectionSampler.Run(Image, NbPoint);
                    }

                    dsCreateObjectResult_e res;
                    var CalquePoint = LyM.GetLayer("Point");
                    if (CalquePoint == null)
                    {
                        LyM.CreateLayer("Point", out CalquePoint, out res);
                        var c = CalquePoint.Color;
                        c.SetColorByIndex(230);
                        CalquePoint.Color = c;
                    }

                    if (MaillageEtPoint)
                    {
                        CalquePoint.Activate();
                        foreach (var pc in listePoint)
                        {
                            SkM.InsertCircleByDiameter(ImgX + pc.X, ImgY + Image.Height - pc.Y, 0, 2);
                        }
                    }


                    CmdLine.PrintLine("Sampler terminé");
                    Log.Message("Sampler terminé");

                    Log.Message("Equilibrage des points");

                    VoronoiMap.VoronoiGraph graph;
                    var listeSitePoincon = VoronoiEquilibreur.Start(Image, listePoint, NbAffinage, out graph);

                    Log.Message("Equilibrage terminé");

                    var CalquePoincon = LyM.GetLayer("Poincon");
                    if (CalquePoincon == null)
                    {
                        LyM.CreateLayer("Poincon", out CalquePoincon, out res);
                        var c = CalquePoincon.Color;
                        c.SetColorByIndex(252);
                        CalquePoincon.Color = c;
                    }

                    var CalqueMaillage = LyM.GetLayer("Maillage");
                    if (CalqueMaillage == null)
                    {
                        LyM.CreateLayer("Maillage", out CalqueMaillage, out res);
                        var c = CalqueMaillage.Color;
                        c.SetColorByIndex(126);
                        CalqueMaillage.Color = c;
                    }

                    var CalqueHachures = LyM.GetLayer("Hachures");
                    if (CalqueHachures == null)
                    {
                        LyM.CreateLayer("Hachures", out CalqueHachures, out res);
                        var c = CalqueHachures.Color;
                        c.SetColorByIndex(100);
                        CalqueMaillage.Color = c;
                    }

                    var ListeCercles = new List <Circle>();
                    CalquePoincon.Activate();

                    var facteurGris    = (100 - BlancPctDiam) / (255 - SeuilNoirs);
                    var DiamMiniDessin = Double.PositiveInfinity;
                    var DiamMaxiDessin = 0.0;

                    foreach (var pc in listeSitePoincon)
                    {
                        var diam       = pc.CercleInscrit - (Jeu * 0.5);
                        var reduce     = (BlancPctDiam + (255 - pc.GrisCercleInscrit) * facteurGris) / 100;
                        var diamReduce = Math.Min(DiamMax, diam * reduce);

                        if (pc.GrisCercleInscrit > SeuilNoirs && diamReduce >= DiamMin)
                        {
                            //Log.Message("Ø : " + diam + " / f : " + reduce + " / Øred : " + diamReduce);
                            DiamMiniDessin = Math.Min(DiamMiniDessin, diamReduce);
                            DiamMaxiDessin = Math.Max(DiamMaxiDessin, diamReduce);
                            var cercle = SkM.InsertCircleByDiameter(ImgX + pc.Site.X, ImgY + Image.Height - pc.Site.Y, 0, diamReduce);
                            ListeCercles.Add(cercle);
                        }
                    }
                    var format = String.Format("Nb de percages : {0} / DiamMaxi : {1:0.0} / DiamMini : {2:0.0}", ListeCercles.Count, DiamMaxiDessin, DiamMiniDessin);
                    CmdLine.PrintLine(format);
                    Log.Message(format);

                    CalqueHachures.Activate();

                    foreach (var item in ListeCercles)
                    {
                        var ent = new DispatchWrapper[1] {
                            new DispatchWrapper(item)
                        };
                        SkM.InsertHatchByEntities(ent, "SOLID", 1, 0);
                    }

                    if (MaillageEtPoint)
                    {
                        CalqueMaillage.Activate();
                        foreach (var s in graph.Segments)
                        {
                            SkM.InsertLine(ImgX + s.P1.X, ImgY + Image.Height - s.P1.Y, 0, ImgX + s.P2.X, ImgY + Image.Height - s.P2.Y, 0);
                        }
                    }

                    LyM.GetLayer("0").Activate();

                    CalqueMaillage.Shown = false;
                    CalquePoint.Shown    = false;
                    CalquePoincon.Shown  = false;
                }
                else
                {
                    CmdLine.PrintLine("Pas d'image");
                }

                t = DateTime.Now - DateTimeStart;
                CmdLine.PrintLine(String.Format("Executé en {0}", GetSimplestTimeSpan(t)));
            }
            catch (Exception e)
            { Log.Write(e); }
        }
示例#14
0
        /// <summary>
        /// Gets the value of the specified property.
        /// </summary>
        /// <param name="propertyId">The Id of the property to retrieve.</param>
        /// <param name="propertyValue">The value of the specified property, or null if the property is not supported.</param>
        /// <returns>true if the property is supported; otherwise false.</returns>
        public virtual bool GetProperty(__VSHPROPID propertyId, out object propertyValue)
        {
            propertyValue = null;
            bool supported = true;

            // Get the property from the node.
            switch (propertyId)
            {
            case __VSHPROPID.VSHPROPID_BrowseObject:
                if (this.Properties != null)
                {
                    propertyValue = new DispatchWrapper(this.Properties);
                }
                break;

            case __VSHPROPID.VSHPROPID_Caption:
                propertyValue = this.Caption;
                break;

            case __VSHPROPID.VSHPROPID_ItemDocCookie:
                // We cast it to an IntPtr because some callers expect a VT_INT
                propertyValue = (IntPtr)this.DocumentCookie;
                break;

            case __VSHPROPID.VSHPROPID_EditLabel:
                if (this.CaptionEditable)
                {
                    propertyValue = this.Caption;
                }
                else
                {
                    supported = false;
                }
                break;

            case __VSHPROPID.VSHPROPID_Expandable:
                propertyValue = this.Expandable;
                break;

            case __VSHPROPID.VSHPROPID_ExpandByDefault:
                propertyValue = this.ExpandByDefault;
                break;

            case __VSHPROPID.VSHPROPID_Expanded:
                propertyValue = this.Expanded;
                break;

            case __VSHPROPID.VSHPROPID_FirstChild:
            case __VSHPROPID.VSHPROPID_FirstVisibleChild:
                propertyValue = (this.FirstChild != null ? this.FirstChild.HierarchyId : NativeMethods.VSITEMID_NIL);
                break;

            case __VSHPROPID.VSHPROPID_IconHandle:
                propertyValue = this.GetImageHandle(this.Image);
                if ((IntPtr)propertyValue == IntPtr.Zero)
                {
                    supported     = false;
                    propertyValue = null;
                }
                break;

            case __VSHPROPID.VSHPROPID_Name:
                propertyValue = this.Caption;
                break;

            case __VSHPROPID.VSHPROPID_NextSibling:
            case __VSHPROPID.VSHPROPID_NextVisibleSibling:
                propertyValue = (this.NextSibling != null ? this.NextSibling.HierarchyId : NativeMethods.VSITEMID_NIL);
                break;

            case __VSHPROPID.VSHPROPID_Parent:
                propertyValue = (this.Parent != null ? this.Parent.HierarchyId : NativeMethods.VSITEMID_NIL);
                break;

            case __VSHPROPID.VSHPROPID_SaveName:
                propertyValue = this.SaveName;
                break;

            case __VSHPROPID.VSHPROPID_TypeGuid:
                propertyValue = this.VisualStudioTypeGuid;
                break;

            default:
                supported = false;
                break;
            }

            return(supported);
        }