コード例 #1
0
        public static string DomainOf(string host)
        {
            if (HostUtils.IsNumeric(host))
            {
                return(host);
            }
            int n = host.Length;

            for (int i = 0; i < suffix.Length; i++)
            {
                if (host.EndsWith(suffix[i]))
                {
                    int p = LastDotBefore(host, n - suffix[i].Length);
                    if (p == -1)
                    {
                        return(host);
                    }
                    return(host.Substring(p + 1));
                }
            }
            int q = LastDotBefore(host, n);

            if (q == -1)
            {
                return(host);
            }
            int r = LastDotBefore(host, q);

            if (r == -1)
            {
                return(host);
            }
            return(host.Substring(r + 1));
        }
コード例 #2
0
        public int Attach(IDebugProgram2[] programs, IDebugProgramNode2[] rgpProgramNodes, uint celtPrograms, IDebugEventCallback2 pCallback, enum_ATTACH_REASON dwReason)
        {
            var            program = programs[0];
            IDebugProcess2 process;

            program.GetProcess(out process);
            Guid processId;

            process.GetProcessId(out processId);
            if (processId != this.processId.guidProcessId)
            {
                return(VSConstants.S_FALSE);
            }

            EngineUtils.RequireOk(program.GetProgramId(out programId));

            Task.Run(() =>
            {
                waiter.WaitOne();

                var ipAddress = HostUtils.ResolveHostOrIPAddress(settings.Host);
                Session.Run(new SoftDebuggerStartInfo(new SoftDebuggerConnectArgs("", ipAddress, 6438)),
                            new DebuggerSessionOptions {
                    EvaluationOptions = EvaluationOptions.DefaultOptions, ProjectAssembliesOnly = false
                });
            });

            MonoEngineCreateEvent.Send(this);
            MonoProgramCreateEvent.Send(this);

            return(VSConstants.S_OK);
        }
コード例 #3
0
        private static TestAppHost InitHost()
        {
            var host = HostUtils.InitHost <TestAppHost>();

            host.Start(BaseUrl);
            return(host);
        }
コード例 #4
0
        private static void OnSetVirtual3DVector(int serialNumber, int propertyId, bool callBaseClass, Vector3d value, int changeContext)
        {
            try
            {
                var texture = FromSerialNumber(serialNumber) as RenderTexture;
                if (texture == null)
                {
                    return;
                }
                if (callBaseClass)
                {
                    var pointer = texture.NonConstPointer();
                    UnsafeNativeMethods.Rdk_RenderTexture_SetVirtual3dVector(pointer, propertyId, true, value, changeContext);
                    return;
                }
                switch (propertyId)
                {
                case REPEAT_MODE:
                    texture.SetRepeat(value, (ChangeContexts)changeContext);
                    return;

                case OFFSET_MODE:
                    texture.SetOffset(value, (ChangeContexts)changeContext);
                    return;

                case ROTATION_MODE:
                    texture.SetRotation(value, (ChangeContexts)changeContext);
                    return;
                }
            }
            catch (Exception exception)
            {
                HostUtils.ExceptionReport(exception);
            }
        }
コード例 #5
0
        private static void OnGetVirtual3DVector(int serialNumber, int propertyId, bool fromBaseClass, ref Vector3d value)
        {
            try
            {
                var texture = FromSerialNumber(serialNumber) as RenderTexture;
                if (texture == null)
                {
                    return;
                }
                var const_pointer = texture.ConstPointer();
                if (fromBaseClass)
                {
                    UnsafeNativeMethods.Rdk_RenderTexture_GetVirtual3dVector(const_pointer, propertyId, true, ref value);
                    return;
                }
                switch (propertyId)
                {
                case REPEAT_MODE:
                    value = texture.GetRepeat();
                    return;

                case OFFSET_MODE:
                    value = texture.GetOffset();
                    return;

                case ROTATION_MODE:
                    value = texture.GetRotation();
                    return;
                }
            }
            catch (Exception exception)
            {
                HostUtils.ExceptionReport(exception);
            }
        }
コード例 #6
0
 public static string InvertHost(string host)
 {
     if (HostUtils.IsNumeric(host))
     {
         return(host);
     }
     else
     {
         int    n   = host.Length;
         char[] res = new char[n];
         int    a   = 0;
         while (a < n)
         {
             int c = a;
             while (c < n && host[c] != '.')
             {
                 c++;
             }
             int d = n - c;
             while (a < c)
             {
                 res[d++] = host[a++];
             }
             res[d++] = '.';
             a        = c + 1;
         }
         return(new string(res));
     }
 }
コード例 #7
0
 static Type GetRhinoDotNetType(string name)
 {
     System.Reflection.Assembly rhino_dot_net = HostUtils.GetRhinoDotNetAssembly();
     if (null == rhino_dot_net)
     {
         return(null);
     }
     return(rhino_dot_net.GetType(name));
 }
コード例 #8
0
 public NamedPipesServer(string address, RequestHandler requestHandler, Action<string> log = null)
     : base(address, requestHandler, HostUtils.DefaultLog("NamedPipesServer: ", log))
 {
     if (!address.StartsWith("namedpipe"))
     {
         throw new InvalidOperationException("Only named pipe transport is supported.");
     }
     _address = address;
 }
コード例 #9
0
ファイル: HostUtilsTests.cs プロジェクト: dmitriyse/ClrCoder
        public async Task HostControllerTest()
        {
            var baseUrl = "http://localhost:5082";

            using (IWebHost host = HostUtils.HostController <RightController>(baseUrl))
            {
                (await new Url(baseUrl).AppendPathSegment("/tst").GetAsync().ReceiveString())
                .Should()
                .Be("RightController");
            }
        }
コード例 #10
0
            public bool Initialize(RuntimeSetup runtimeSetup, ILogger logger)
            {
                hook = HostUtils.CreateInstance <ElevationHook>(host);

                if (!hook.HasElevatedPrivileges())
                {
                    logger.Log(LogSeverity.Warning, "Failed to create an elevation context out of process.  The process was created successfully but it did not acquire elevated privileges for an unknown reason.");
                    return(false);
                }

                hook.Initialize(runtimeSetup, new RemoteLogger(logger));
                return(true);
            }
コード例 #11
0
 public NamedPipesClientConnection(string address, Action <string> log = null)
 {
     _address = address.Replace(@"namedpipes://\\.\pipe\", "");
     _log     = HostUtils.DefaultLog("Host: ", log);
     _log($"Connecting to named pipe {_address}...");
     _clientStream = new NamedPipeClientStream(_address);
     _clientStream.Connect();
     _streamReader = new StreamReader(_clientStream);
     _streamWriter = new StreamWriter(_clientStream)
     {
         AutoFlush = true
     };
     _log("Connected.");
 }
コード例 #12
0
        /// <summary>
        /// For derived class implementers.
        /// <para>This method is called with argument true when class user calls Dispose(), while with argument false when
        /// the Garbage Collector invokes the finalizer, or Finalize() method.</para>
        /// <para>You must reclaim all used unmanaged resources in both cases, and can use this chance to call Dispose on disposable fields if the argument is true.</para>
        /// <para>Also, you must call the base virtual method within your overriding method.</para>
        /// </summary>
        /// <param name="disposing">true if the call comes from the Dispose() method; false if it comes from the Garbage Collector finalizer.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (IntPtr.Zero == m_ptr || m__parent is ConstCastHolder)
            {
                return;
            }

            Geometry.MeshHolder mh = m__parent as Geometry.MeshHolder;
            if (mh != null)
            {
                mh.ReleaseMesh();
            }

            if (m_bDestructOnDispose)
            {
                bool in_finalizer = !disposing;
                if (in_finalizer)
                {
                    // 11 Feb 2013 (S. Baer) RH-16157
                    // When running in the finalizer, the destructor is being called on the GC
                    // thread which results in nearly impossible to track down exceptions.
                    // Mask the exception in this case and post information to our logging system
                    // about the exception so we can better analyze and try to figure out what
                    // is going on
                    try
                    {
                        UnsafeNativeMethods.ON_Object_Delete(m_ptr);
                    }
                    catch (Exception ex)
                    {
                        HostUtils.ExceptionReport(ex);
                    }
                }
                else
                {
                    // See above. In this case we are running on the main thread of execution
                    // and throwing an exception is a good thing so we can analyze and quickly
                    // fix whatever is going wrong
                    UnsafeNativeMethods.ON_Object_Delete(m_ptr);
                }
                if (m_unmanaged_memory > 0)
                {
                    GC.RemoveMemoryPressure(m_unmanaged_memory);
                }
            }
            m_ptr      = IntPtr.Zero;
            m_disposed = true;
        }
コード例 #13
0
        protected override void OnStop()
        {
            // Update the service state to Start Pending.
            var serviceStatus = new ServiceStatus
            {
                dwCurrentState = ServiceState.SERVICE_START_PENDING,
                dwWaitHint     = 100000
            };

            SetServiceStatus(ServiceHandle, ref serviceStatus);

            Program.Host = HostUtils.TerminateHost(Program.Host);

            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(ServiceHandle, ref serviceStatus);
        }
コード例 #14
0
        static void OnSetVirtualInt(int serialNumber, int propertyId, bool callBaseClass, int value, int changeContext)
        {
            try
            {
                var texture = FromSerialNumber(serialNumber) as RenderTexture;
                if (texture == null)
                {
                    return;
                }
                if (callBaseClass)
                {
                    var pointer = texture.NonConstPointer();
                    UnsafeNativeMethods.Rdk_RenderTexture_SetVirtualIntValue(pointer, propertyId, true, value, changeContext);
                    return;
                }
                switch (propertyId)
                {
                case PROJECTION_MODE:
                    texture.SetProjectionMode((TextureProjectionMode)value, (ChangeContexts)changeContext);
                    break;

                case WRAP_TYPE_MODE:
                    texture.SetWrapType((TextureWrapType)value, (ChangeContexts)changeContext);
                    break;

                case REPEAT_LOCKED_MODE:
                    texture.SetRepeatLocked(value != 0, (ChangeContexts)changeContext);
                    break;

                case OFFSET_LOCKED_MODE:
                    texture.SetOffsetLocked(value != 0, (ChangeContexts)changeContext);
                    break;

                case PREVIEW_IN_3D_MODE:
                    texture.SetPreviewIn3D(value != 0, (ChangeContexts)changeContext);
                    break;
                }
            }
            catch (Exception exception)
            {
                HostUtils.ExceptionReport(exception);
            }
        }
コード例 #15
0
 static void OnSimulateTexture(int serialNumber, IntPtr pSim, int bDataOnly)
 {
     try
     {
         RenderTexture texture = FromSerialNumber(serialNumber) as RenderTexture;
         if (texture != null)
         {
             if (pSim != IntPtr.Zero)
             {
                 SimulatedTexture sim = new SimulatedTexture(pSim);
                 texture.SimulateTexture(ref sim, 1 == bDataOnly);
             }
         }
     }
     catch (Exception exception)
     {
         HostUtils.ExceptionReport(exception);
     }
 }
コード例 #16
0
 static void OnSimulateEnvironment(int serial_number, IntPtr pSim, int bDataOnly)
 {
     try
     {
         var texture = FromSerialNumber(serial_number) as RenderEnvironment;
         if (texture != null)
         {
             if (pSim != IntPtr.Zero)
             {
                 var sim = new SimulatedEnvironment(pSim);
                 texture.SimulateEnvironment(ref sim, 1 == bDataOnly);
             }
         }
     }
     catch (Exception exception)
     {
         HostUtils.ExceptionReport(exception);
     }
 }
コード例 #17
0
        public TcpClientConnection(string address, Action <string> log = null)
        {
            address = address.Replace("//:", "//127.0.0.1:");
            var url = new Uri(address);

            log = HostUtils.DefaultLog("TcpClient: ", log);

            log($"Connecting to {url} over TCP...");

            _client = new TcpClient(url.Host, url.Port);

            var stream = _client.GetStream();

            _streamReader = new StreamReader(stream);
            _streamWriter = new StreamWriter(stream)
            {
                AutoFlush = true
            };
            log("Connected.");
        }
コード例 #18
0
ファイル: opennurbs_subd.cs プロジェクト: gnalxom/rhino3dm
        /// <summary>
        /// Deletes the underlying native pointer during a Dispose call or GC collection
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            DestroySubDDisplay();
            ReleaseNonConstPointer();

            IntPtr subd_ref_ptr = m_ptr_subd_ref;

            m_ptr_subd_ref = IntPtr.Zero;

            if (IntPtr.Zero != subd_ref_ptr)
            {
                bool in_finalizer = !disposing;
                if (in_finalizer)
                {
                    // 11 Feb 2013 (S. Baer) RH-16157
                    // When running in the finalizer, the destructor is being called on the GC
                    // thread which results in nearly impossible to track down exceptions.
                    // Mask the exception in this case and post information to our logging system
                    // about the exception so we can better analyze and try to figure out what
                    // is going on
                    try
                    {
                        UnsafeNativeMethods.ON_SubDRef_Delete(subd_ref_ptr);
                    }
                    catch (Exception ex)
                    {
                        HostUtils.ExceptionReport(ex);
                    }
                }
                else
                {
                    // See above. In this case we are running on the main thread of execution
                    // and throwing an exception is a good thing so we can analyze and quickly
                    // fix whatever is going wrong
                    UnsafeNativeMethods.ON_SubDRef_Delete(subd_ref_ptr);
                }
            }

            base.Dispose(disposing);
        }
コード例 #19
0
        protected override void OnStart(string[] args)
        {
            // Update the service state to Start Pending.
            var serviceStatus = new ServiceStatus
            {
                dwCurrentState = ServiceState.SERVICE_START_PENDING,
                dwWaitHint     = 100000
            };

            SetServiceStatus(ServiceHandle, ref serviceStatus);

#if DEBUG
            System.Diagnostics.Debugger.Launch();
#endif
            // (Konrad) Configure NLog
            var arguments = Environment.GetCommandLineArgs();
            var endpoint  = arguments.Length >= 4 ? new Uri(arguments[3]) : null;
            NlogUtils.CreateConfiguration(endpoint);

            // (Konrad) Set host, settings and runner if they don't exist
            Program.Host     = HostUtils.CreateHost(Program.Host);
            Program.Settings = SettingsUtils.GetSettings(new[] { arguments[1], arguments[2] });
            Program.Runner   = new ZombieRunner(Program.Settings);

            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(ServiceHandle, ref serviceStatus);
#if DEBUG
            var dir        = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"..\..\..\"));
            var zombiePath = Path.Combine(dir, @"Zombie\bin\debug\Zombie.exe");
#else
            var dir        = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"..\");
            var zombiePath = Path.Combine(dir, @"Zombie\Zombie.exe");
#endif
            // launch the application
            var commandPath = "\"" + zombiePath + "\" hide";
            ApplicationLoader.PROCESS_INFORMATION procInfo;
            ApplicationLoader.StartProcessAndBypassUAC(commandPath, out procInfo);
        }
コード例 #20
0
        public async Task FlurlHttpExtensionsTest(string host, string dnsOrIp, string pathSegment)
        {
            try
            {
                using (HostUtils.HostController <TestFlurlController>(host))
                {
                    string response = await new Url(dnsOrIp).AppendPathSegment(pathSegment).GetAsync().ReceiveString();
                    if ((pathSegment == "Flurl") && (host == "http://localhost:5062"))
                    {
                        response.Should().BeEquivalentTo("Hello");
                    }
                }
            }
            catch (FlurlHttpTimeoutException)
            {
                TestContext.WriteLine("FlurlHttpTimeoutException");
            }
            catch (FlurlHttpException ex)
            {
                if (dnsOrIp == "http://nobody-knows-me-99923.com")
                {
                    ex.IsDnsResolveError().Should().Be(true);
                }
                else
                {
                    ex.IsDnsResolveError().Should().Be(false);
                }

                if ((dnsOrIp == "http://10.110.110.110/") || (dnsOrIp == "http://46.20.65.243:22222/"))
                {
                    ex.IsIpNotAvailable().Should().Be(true);
                }
                else
                {
                    ex.IsIpNotAvailable().Should().Be(false);
                }
            }
        }
コード例 #21
0
        static int OnGetVirtualInt(int serialNumber, int propertyId, bool fromBaseClass)
        {
            try
            {
                var texture = FromSerialNumber(serialNumber) as RenderTexture;
                if (texture == null)
                {
                    return(-1);
                }
                if (fromBaseClass)
                {
                    return(UnsafeNativeMethods.Rdk_RenderTexture_GetVirtualIntValue(texture.ConstPointer(), propertyId, true));
                }
                switch (propertyId)
                {
                case PROJECTION_MODE:
                    return((int)texture.GetProjectionMode());

                case WRAP_TYPE_MODE:
                    return((int)texture.GetWrapType());

                case REPEAT_LOCKED_MODE:
                    return(texture.GetRepeatLocked() ? 1 : 0);

                case OFFSET_LOCKED_MODE:
                    return(texture.GetOffsetLocked() ? 1 : 0);

                case PREVIEW_IN_3D_MODE:
                    return(texture.GetPreviewIn3D() ? 1 : 0);
                }
                return(-1);
            }
            catch (Exception exception)
            {
                HostUtils.ExceptionReport(exception);
            }
            return(-1);
        }
コード例 #22
0
        public async Task SendJsonAsyncWithDumpTest()
        {
            var data = new MethodInfoDto
            {
                Name         = "name",
                TypeFullName = "fullname"
            };

            IJsonLogger logger = new NUnitJsonLogger(SyncHandler.Instance);

            using (HostUtils.HostController <TestFlurlController>("http://localhost:5062"))
            {
                string response = await new Url("http://localhost:5062")
                                  .AppendPathSegment("Flurl")
                                  .WithDump(logger)
                                  .PostJsonAsync(data)
                                  .ReceiveString();

                var responseData = JsonConvert.DeserializeObject <MethodInfoDto>(response);
                responseData.Should().NotBeNull();
                responseData.Name.Should().Be(data.Name);
                responseData.TypeFullName.Should().Be(data.TypeFullName);
            }
        }
コード例 #23
0
        private static void UnpackScriptResources()
        {
            if (g_resources_unpacked)
            {
                return;
            }
            Guid python_plugin_id = new Guid("814d908a-e25c-493d-97e9-ee3861957f49");
            var  plugin           = Rhino.PlugIns.PlugIn.Find(python_plugin_id);

            if (plugin == null)
            {
                return;
            }

            g_resources_unpacked = true;

            // Unpack ghcomponents.py to the Python plug directory
            string settings_directory = plugin.SettingsDirectory;
            string marker_file        = Path.Combine(settings_directory, "ghpy_version.txt");

            try
            {
                if (File.Exists(marker_file))
                {
                    string  text          = File.ReadAllText(marker_file);
                    Version markedversion = new Version(text);
                    Version this_version  = typeof(ZuiPythonComponent).Assembly.GetName().Version;
                    if (markedversion == this_version)
                    {
#if !DEBUG
                        // everything looks good, bail out
                        return;
#endif
                    }
                }
            }
            catch (Exception ex)
            {
                HostUtils.ExceptionReport(ex);
            }

            try
            {
                // if we get to here, we need to unpack the resources
                if (!Directory.Exists(settings_directory))
                {
                    Directory.CreateDirectory(settings_directory);
                }
                string ghpython_package_dir = Path.Combine(settings_directory, "lib", PythonEnvironment.GHPYTHONLIB_NAME);
                if (Directory.Exists(ghpython_package_dir))
                {
                    Directory.Delete(ghpython_package_dir, true);
                }
                Directory.CreateDirectory(ghpython_package_dir);
                System.Reflection.Assembly a = typeof(ZuiPythonComponent).Assembly;
                string[] names = a.GetManifestResourceNames();

                const string prefix = "GhPython.package.";

                foreach (string name in names)
                {
                    if (!name.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    Stream resource_stream = a.GetManifestResourceStream(name);
                    if (resource_stream == null)
                    {
                        continue;
                    }
                    StreamReader stream = new StreamReader(resource_stream);
                    string       s      = stream.ReadToEnd();
                    stream.Close();
                    string filename = name.Replace(prefix, "");
                    string path     = Path.Combine(ghpython_package_dir, filename);
                    File.WriteAllText(path, s);
                }

                // Write the marker file at the very end to ensure that we actually got to this point.
                // If an exception occured for some reason like a file was in use, then the plug-in
                // will just attempt to unpack the resources next time.
                string str = a.GetName().Version.ToString();
                File.WriteAllText(marker_file, str);
            }
            catch (Exception ex)
            {
                HostUtils.DebugString("Exception while unpacking resources: " + ex.Message);
            }
        }
コード例 #24
0
 public static void SetHooks()
 {
     HostUtils.RegisterNamedCallback("CRhCmnFileEventWatcherInteropHook", HookProc);
 }
コード例 #25
0
        public void HostHelperCanBuildUrlsFromAppidConnectionStrings(string src, string result)
        {
            var resultUrl = HostUtils.ParseUrl(src);

            Assert.AreEqual(result, resultUrl);
        }
コード例 #26
0
        /// <summary>
        /// Runs an isolated task in a host.
        /// </summary>
        /// <typeparam name="TIsolatedTask">The isolated task type.</typeparam>
        /// <param name="hostSetup">The host setup which includes the test isolation option properties copied down, not null.</param>
        /// <param name="statusReporter">The status reporter, not null.</param>
        /// <param name="args">The task arguments.</param>
        /// <returns>The task result.</returns>
        protected virtual object RunIsolatedTaskInHost <TIsolatedTask>(HostSetup hostSetup, StatusReporter statusReporter, object[] args)
            where TIsolatedTask : IsolatedTask
        {
            IHost host = null;

            try
            {
                statusReporter("Creating test host.");
                host = hostFactory.CreateHost(hostSetup, logger);

                RemoteLogger remoteLogger = new RemoteLogger(logger);
                RuntimeSetup runtimeSetup = RuntimeAccessor.Instance.GetRuntimeSetup().Copy();

                Shim shim = HostUtils.CreateInstance <Shim>(host);
                try
                {
                    statusReporter("Initializing the runtime.");
                    shim.Initialize(runtimeSetup, remoteLogger);
                    statusReporter("");

                    var isolatedTask = HostUtils.CreateInstance <TIsolatedTask>(host);

                    ManualResetEvent disconnectedEvent        = new ManualResetEvent(false);
                    EventHandler     disconnectedEventHandler = (sender, e) => disconnectedEvent.Set();
                    try
                    {
                        host.Disconnected += disconnectedEventHandler;

                        RunIsolatedTaskDelegate isolatedTaskDelegate = isolatedTask.Run;
                        IAsyncResult            asyncResult          = isolatedTaskDelegate.BeginInvoke(args, null, null);

                        WaitHandle.WaitAny(new[] { disconnectedEvent, asyncResult.AsyncWaitHandle });

                        if (asyncResult.IsCompleted)
                        {
                            return(isolatedTaskDelegate.EndInvoke(asyncResult));
                        }

                        throw new TestIsolationException("The host disconnected or was terminated prematurely while the task was running.");
                    }
                    finally
                    {
                        host.Disconnected -= disconnectedEventHandler;
                    }
                }
                finally
                {
                    statusReporter("Shutting down the runtime.");
                    shim.Shutdown();

                    GC.KeepAlive(remoteLogger);
                }
            }
            finally
            {
                statusReporter("Disposing test host.");

                try
                {
                    if (host != null)
                    {
                        host.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    UnhandledExceptionPolicy.Report("An exception occurred while disposing the test host.", ex);
                }

                statusReporter("");
            }
        }
コード例 #27
0
        private static void ExecConduit(IntPtr pPipeline, uint conduitSerialNumber, uint channel)
        {
            if (_enabledConduits.TryGetValue(conduitSerialNumber, out DisplayConduit conduit) && conduit != null)
            {
                try
                {
                    switch (channel)
                    {
                    case (uint)CSupportChannels.SC_CALCBOUNDINGBOX:
                        conduit._CalculateBoundingBox(null, new CalculateBoundingBoxEventArgs(pPipeline, conduitSerialNumber));
                        break;

                    case (uint)CSupportChannels.SC_CALCCLIPPINGPLANES:
                        break;

                    case (uint)CSupportChannels.SC_DRAWBACKGROUND:
                        break;

                    case (uint)CSupportChannels.SC_DRAWFOREGROUND:
                        conduit._DrawForeground(null, new DrawEventArgs(pPipeline, conduitSerialNumber));
                        break;

                    case (uint)CSupportChannels.SC_DRAWOBJECT:
                        conduit._PreDrawObject(null, new DrawObjectEventArgs(pPipeline, conduitSerialNumber));
                        break;

                    case (uint)CSupportChannels.SC_DRAWOVERLAY:
                        conduit._DrawOverlay(null, new DrawEventArgs(pPipeline, conduitSerialNumber));
                        break;

                    case (uint)CSupportChannels.SC_INITFRAMEBUFFER:
                        break;

                    case (uint)CSupportChannels.SC_MESHINGPARAMETERS:
                        break;

                    case (uint)CSupportChannels.SC_OBJECTCULLING:
                        conduit._ObjectCulling(null, new CullObjectEventArgs(pPipeline, conduitSerialNumber));
                        break;

                    case (uint)CSupportChannels.SC_OBJECTDISPLAYATTRS:
                        break;

                    case (uint)CSupportChannels.SC_POSTDRAWOBJECTS:
                        conduit._PostDrawObjects(null, new DrawEventArgs(pPipeline, conduitSerialNumber));
                        break;

                    case (uint)CSupportChannels.SC_POSTOBJECTDRAW:
                        break;

                    case (uint)CSupportChannels.SC_POSTPROCESSFRAMEBUFFER:
                        break;

                    case (uint)CSupportChannels.SC_PREDRAWMIDDLEGROUND:
                        break;

                    case (uint)CSupportChannels.SC_PREDRAWOBJECTS:
                        conduit._PreDrawObjects(null, new DrawEventArgs(pPipeline, conduitSerialNumber));
                        break;

                    case (uint)CSupportChannels.SC_PREDRAWTRANSPARENTOBJECTS:
                        break;

                    case (uint)CSupportChannels.SC_PREOBJECTDRAW:
                        break;

                    case (uint)CSupportChannels.SC_SETUPFRUSTUM:
                        break;

                    case (uint)CSupportChannels.SC_SETUPLIGHTING:
                        break;

                    case (uint)CSupportChannels.SC_VIEWEXTENTS:
                        conduit._CalculateBoundingBoxZoomExtents(null, new CalculateBoundingBoxEventArgs(pPipeline, conduitSerialNumber));
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    HostUtils.ExceptionReport("DisplayConduit", ex);
                }
            }
        }
コード例 #28
0
        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            // Handle the RhinoCommon case.
            if (args.Name.StartsWith("RhinoCommon", StringComparison.OrdinalIgnoreCase) &&
                !args.Name.StartsWith("RhinoCommon.resources", StringComparison.OrdinalIgnoreCase))
            {
                return(Assembly.GetExecutingAssembly());
            }

            // Get the significant name of the assembly we're looking for.
            string searchname = args.Name;
            // Do not attempt to handle resource searching.
            int index = searchname.IndexOf(".resources", StringComparison.Ordinal);

            if (index > 0)
            {
                return(null);
            }

            // The resolver is commonly called multiple times with the same search name.
            // Keep the results around so we don't keep doing the same job over and over
            if (m_match_dictionary != null && m_match_dictionary.ContainsKey(args.Name))
            {
                return(m_match_dictionary[args.Name]);
            }

            bool probably_python = false;

            index = searchname.IndexOf(',');
            if (index > 0)
            {
                searchname = searchname.Substring(0, index);
            }
            else
            {
                // Python scripts typically just look for very short names, like "MyFunctions.dll"
                if (searchname.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                {
                    searchname = searchname.Substring(0, searchname.Length - ".dll".Length);
                }
                probably_python = true;
            }

            // See if the assembly is already loaded.
            var loaded_assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (var loaded_assembly in loaded_assemblies)
            {
                if (loaded_assembly.FullName.StartsWith(searchname + ",", StringComparison.OrdinalIgnoreCase))
                {
                    return(loaded_assembly);
                }
            }



            List <string> potential_files = new List <string>();

            // Collect all potential files in the plug-in directories.
#if RHINO_SDK
            string[] plugin_folders = HostUtils.GetAssemblySearchPaths();
            if (plugin_folders != null)
            {
                foreach (string plugin_folder in plugin_folders)
                {
                    string[] files = Directory.GetFiles(plugin_folder, @"*.dll", SearchOption.TopDirectoryOnly); //Why TopDirectoryOnly?
                    if (files != null)
                    {
                        potential_files.AddRange(files);
                    }

                    files = Directory.GetFiles(plugin_folder, @"*.rhp", SearchOption.TopDirectoryOnly); //Why TopDirectoryOnly?
                    if (files != null)
                    {
                        potential_files.AddRange(files);
                    }
                }
            }
#endif
            if (probably_python)
            {
                string current_dir = Directory.GetCurrentDirectory();
                if (!string.IsNullOrEmpty(current_dir))
                {
                    string[] files = Directory.GetFiles(current_dir, @"*.dll", SearchOption.TopDirectoryOnly); //Why TopDirectoryOnly?
                    if (files != null)
                    {
                        potential_files.AddRange(files);
                    }
                }
            }

            // Collect all potential files in the custom directories.
            if (m_custom_folders != null)
            {
                foreach (string custom_folder in m_custom_folders)
                {
                    string[] files = Directory.GetFiles(custom_folder, @"*.dll", SearchOption.TopDirectoryOnly); //Why TopDirectoryOnly?
                    if (files != null)
                    {
                        potential_files.AddRange(files);
                    }

                    files = Directory.GetFiles(custom_folder, @"*.rhp", SearchOption.TopDirectoryOnly); //Why TopDirectoryOnly?
                    if (files != null)
                    {
                        potential_files.AddRange(files);
                    }
                }
            }

            // Collect all potential files in the custom file list.
            if (m_custom_files != null)
            {
                potential_files.AddRange(m_custom_files);
            }

            // Remove the already loaded assemblies from the "potential" list. We've
            // already tested these.
            for (int i = 0; i < loaded_assemblies.Length; i++)
            {
                if (loaded_assemblies[i].GlobalAssemblyCache)
                {
                    continue;
                }
                if (loaded_assemblies[i].IsDynamic)
                {
                    continue; //dynamic assemblies won't have a Location anyways.
                }
                try
                {
                    // 6 Feb 2017 S. Baer (RH-35794)
                    // Remove loaded assemblies using filename as comparison. On systems
                    // where the same assembly is located in multiple search path locations
                    // we will start throwing exceptions when attempting to load those
                    // assemblies (even if they are not the ones we are looking for).
                    string filename = Path.GetFileName(loaded_assemblies[i].Location);
                    for (int j = potential_files.Count - 1; j >= 0; j--)
                    {
                        string potential_filename = Path.GetFileName(potential_files[j]);
                        if (string.Compare(filename, potential_filename, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            potential_files.RemoveAt(j);
                        }
                    }
                }
                catch { }
            }

#if RHINO_SDK
            // 7 Feb 2017 S. Baer (RH-30818)
            // Remove native DLLs from the list of potentials
            for (int i = potential_files.Count - 1; i >= 0; i--)
            {
                if (!HostUtils.IsManagedDll(potential_files[i]))
                {
                    potential_files.RemoveAt(i);
                }
            }
#endif

            // Sort all potential files based on fuzzy name matches.
            FuzzyComparer fuzzy = new FuzzyComparer(searchname);
            potential_files.Sort(fuzzy);

            // 23 August 2012 S. Baer
            // Make sure that at least part of the searchname matches part of the filename
            // Just use the first 5 characters as a required pattern in the filename
            const int length_match        = 5;
            string    must_be_in_filename = searchname.Substring(0, searchname.Length > length_match ? length_match : searchname.Length);

            Assembly asm = null;
            foreach (string file in potential_files)
            {
                if (file.IndexOf(must_be_in_filename, StringComparison.InvariantCultureIgnoreCase) == -1)
                {
                    continue;
                }
                asm = TryLoadAssembly(file, searchname);
                if (asm != null)
                {
                    break;
                }
            }

            if (m_match_dictionary == null)
            {
                m_match_dictionary = new Dictionary <string, Assembly>();
            }
            if (!m_match_dictionary.ContainsKey(args.Name))
            {
                m_match_dictionary.Add(args.Name, asm);
            }

            return(asm);
        }
コード例 #29
0
            public int Compare(string x, string y)
            {
                bool xExists = File.Exists(x);
                bool yExists = File.Exists(y);

                if (!xExists && !yExists)
                {
                    return(0);
                }

                if (!xExists)
                {
                    return(+1);
                }
                if (!yExists)
                {
                    return(-1);
                }

                // This can be made a lot smarter with substring searches.
                string xFileName = Path.GetFileName(x);
                string yFileName = Path.GetFileName(y);

                int xIndex = xFileName == null ? -1 : xFileName.IndexOf(m_search, StringComparison.OrdinalIgnoreCase);
                int yIndex = yFileName == null ? -1 : yFileName.IndexOf(m_search, StringComparison.OrdinalIgnoreCase);

                // 4 April 2012 - S. Baer
                // If the file names are the same, the highest version number or most
                // recent file date is sorted to the top.  Plug-ins like PanelingTools
                // have historically moved around on where they are installed on a user's
                // computer, so we may end up with duplicates
                if (xIndex >= 0 && yIndex >= 0 && string.Compare(xFileName, yFileName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    try
                    {
                        // 25 August 2015 - David Rutten:
                        // Error reports:
                        // http://mcneel.myjetbrains.com/youtrack/issue/RH-30818
                        // https://app.raygun.io/dashboard/6bsfxg/errors/561473847
                        // seem to originate on one of the ReflectionOnlyLoadFrom calls below,
                        // but they're already in a try_catch block. I'm really not sure how to
                        // determine whether an assembly will load prior to loading it.

                        // 3 Oct 2017 - S. Baer (RH-35794)
                        // Reflection loading two assemblies into the same appdomain is asking for exceptions
                        // Luckily, there is another way... Use AssemblyName.GetAssemblyName

                        var     xAssemblyName = AssemblyName.GetAssemblyName(x);
                        var     yAssemblyName = AssemblyName.GetAssemblyName(y);
                        Version xVersion      = xAssemblyName.Version;
                        Version yVersion      = yAssemblyName.Version;
                        int     rc            = xVersion.CompareTo(yVersion);
                        if (rc != 0)
                        {
                            return(rc);
                        }

                        // Same version. Try using the file date
                        FileInfo xInfo = new FileInfo(x);
                        FileInfo yInfo = new FileInfo(y);
                        rc = xInfo.LastAccessTimeUtc.CompareTo(yInfo.LastAccessTimeUtc);
                        if (rc != 0)
                        {
                            return(rc);
                        }
                    }
                    catch (Exception ex)
                    {
                        HostUtils.ExceptionReport("duplicate assembly resolve", ex);
                    }
                }

                if (xIndex < 0)
                {
                    xIndex = int.MaxValue;
                }
                if (yIndex < 0)
                {
                    yIndex = int.MaxValue;
                }
                return(xIndex.CompareTo(yIndex));
            }