コード例 #1
0
        public void ResponseParallelTest()
        {
            Parallel.For(0, 4, (index, state) =>
            {
                using (var clientProxy = new NpClient <INetTester>(CreateEndPoint()))
                {
                    const int count = 5;
                    const int start = 0;

                    var result = clientProxy.Proxy.Range(start, count);
                    for (var i = start; i < count; i++)
                    {
                        int temp;
                        if (result.TryGetValue(i, out temp))
                        {
                            if (i != temp)
                            {
                                state.Break();
                            }
                            Assert.Equal(i, temp);
                        }
                        else
                        {
                            state.Break();
                            Assert.True(false);
                        }
                    }
                }
            });
        }
コード例 #2
0
ファイル: ExecServerApp.cs プロジェクト: hammondjm/stride
            public ExecServerRemoteClient(string remoteAddress, RedirectLogger logger)
            {
                _client = new NpClient <IExecServerRemote>(new NpEndPoint(remoteAddress));

                //Create callback channel
                this.CallbackAddress = remoteAddress + "_callback";
                _callbackChannel     = new NpHost(this.CallbackAddress, null, null);
                _callbackChannel.AddService <IServerLogger>(logger);
            }
コード例 #3
0
ファイル: IPCMessaging.cs プロジェクト: Levrum/Levrum
        public IPCNamedPipeClient(string _pipeName)
        {
            if (string.IsNullOrEmpty(_pipeName))
            {
                throw new ArgumentException("PipeName is null or empty.");
            }

            PipeName = _pipeName;
            NpClient = new NpClient <IMessageService>(new NpEndPoint(PipeName));
        }
コード例 #4
0
#pragma warning disable IDE0060 // Remove unused parameter
        static void Main(string[] args)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            using (var npClient = new NpClient <ITransformationRunFactoryService>(new NpEndPoint(TransformationRunFactory.TransformationRunFactoryService)))
            {
                foreach (var uri in npClient.Proxy.GetAllChannelUri())
                {
                    Console.Out.WriteLine(uri.ToString());
                }
            }
        }
コード例 #5
0
 public void ResponseWithOutParameterTest()
 {
     using (var clientProxy = new NpClient <INetTester>(CreateEndPoint()))
     {
         int quantity = 0;
         var result   = clientProxy.Proxy.Get(Guid.NewGuid(), "SomeLabel", 45.65, out quantity);
         Assert.Equal(44, quantity);
         Assert.NotEqual(default(TestResponse), result);
         Assert.Equal("MyLabel", result.Label);
     }
 }
コード例 #6
0
        public RemoteLogForwarder(ILogger mainLogger, IEnumerable <string> logPipeNames)
        {
            this.mainLogger = mainLogger;

            foreach (var logPipeName in logPipeNames)
            {
                var client = new NpClient <IForwardSerializableLogRemote>(new NpEndPoint(logPipeName), new StrideServiceWireSerializer());
                remoteLogs.Add(client);
            }

            activeRemoteLogs = remoteLogs.Count > 0;
        }
コード例 #7
0
ファイル: IPCMessaging.cs プロジェクト: Levrum/Levrum
 private void verifyConnection()
 {
     if (NpClient == null || !NpClient.IsConnected)
     {
         if (!NpClient.IsConnected)
         {
             NpClient.Dispose();
             NpClient = null;
         }
         NpClient = new NpClient <IMessageService>(new NpEndPoint(PipeName));
     }
 }
コード例 #8
0
        public void SimpleTest()
        {
            var rnd = new Random();

            var a = rnd.Next(0, 100);
            var b = rnd.Next(0, 100);

            using (var clientProxy = new NpClient <INetTester>(CreateEndPoint()))
            {
                var result = clientProxy.Proxy.Min(a, b);
                Assert.Equal(Math.Min(a, b), result);
            }
        }
コード例 #9
0
ファイル: NpTests.cs プロジェクト: wouterroos/ServiceWire
        public async Task CalculateAsyncTest()
        {
	        var rnd = new Random();

	        var a = rnd.Next(0, 100);
	        var b = rnd.Next(0, 100);

	        using (var clientProxy = new NpClient<INetTester>(CreateEndPoint()))
	        {
		        var result = await clientProxy.Proxy.CalculateAsync(a, b);
		        Assert.Equal(a + b, result);
	        }
        }
コード例 #10
0
        public void ResponseWithOutParameterNewtonsoftSerializerTest()
        {
            using (var nphost = new NpHost(PipeName + "JsonResponseOut", serializer: new NewtonsoftSerializer()))
            {
                nphost.AddService <INetTester>(_tester);
                nphost.Open();

                using (var clientProxy = new NpClient <INetTester>(new NpEndPoint(PipeName + "JsonResponseOut"), new NewtonsoftSerializer()))
                {
                    int quantity = 0;
                    var result   = clientProxy.Proxy.Get(Guid.NewGuid(), "SomeLabel", 45.65, out quantity);
                    Assert.Equal(44, quantity);
                    Assert.NotEqual(default(TestResponse), result);
                    Assert.Equal("MyLabel", result.Label);
                }
            }
        }
コード例 #11
0
        public void ResponseTest()
        {
            using (var clientProxy = new NpClient <INetTester>(CreateEndPoint()))
            {
                const int count = 50;
                const int start = 0;

                var result = clientProxy.Proxy.Range(start, count);

                for (var i = start; i < count; i++)
                {
                    int temp;
                    Assert.True(result.TryGetValue(i, out temp));
                    Assert.Equal(i, temp);
                }
            }
        }
コード例 #12
0
        private static void ClosePipeAndProcess()
        {
            if (strideCommands != null)
            {
                try
                {
                    strideCommands.Dispose();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine($"Unexpected exception when closing remote connection to VS Commands: {ex}");
                }
                strideCommands = null;
            }

            strideCommandsProcessJob?.Dispose();
            strideCommandsProcessJob = null;
        }
コード例 #13
0
ファイル: NpTests.cs プロジェクト: wouterroos/ServiceWire
        public void SimpleParallelTest()
        {
            var rnd = new Random();

            Parallel.For(0, 50, (index, state) =>
            {
                var a = rnd.Next(0, 100);
                var b = rnd.Next(0, 100);

                using (var clientProxy = new NpClient<INetTester>(CreateEndPoint()))
                {
                    var result = clientProxy.Proxy.Min(a, b);

                    if (Math.Min(a, b) != result) state.Break();
                    Assert.Equal(Math.Min(a, b), result);
                }
            });
        }
コード例 #14
0
        public override async Task ConnectAsync()
        {
            while (!IsConnected)
            {
                try
                {
                    NpClient = new NpClient <TService>(new NpEndPoint(ChannelName), serialization);
                }
                catch (TimeoutException)
                {
                    if (!EnableAutomaticConnection)
                    {
                        throw;
                    }

                    await Task.Delay(ReconnectionInterval);
                }
            }
        }
コード例 #15
0
        public void SimpleProtobufSerializerTest()
        {
            using (var nphost = new NpHost(PipeName + "Proto", serializer: new ProtobufSerializer()))
            {
                nphost.AddService <INetTester>(_tester);
                nphost.Open();

                var rnd = new Random();

                var a = rnd.Next(0, 100);
                var b = rnd.Next(0, 100);

                using (var clientProxy = new NpClient <INetTester>(new NpEndPoint(PipeName + "Proto"), new ProtobufSerializer()))
                {
                    var result = clientProxy.Proxy.Min(a, b);
                    Assert.Equal(Math.Min(a, b), result);
                }
            }
        }
コード例 #16
0
ファイル: PackageBuilder.cs プロジェクト: ykafia/stride
        private static void RegisterRemoteLogger(NpClient <IProcessBuilderRemote> processBuilderRemote)
        {
            // The pipe might be broken while we try to output log, so let's try/catch the call to prevent program for crashing here (it should crash at a proper location anyway if the pipe is broken/closed)
            // ReSharper disable EmptyGeneralCatchClause
            GlobalLogger.GlobalMessageLogged += logMessage =>
            {
                try
                {
                    var assetMessage = logMessage as AssetLogMessage;
                    var message      = assetMessage != null ? new AssetSerializableLogMessage(assetMessage) : new SerializableLogMessage((LogMessage)logMessage);

                    processBuilderRemote.Proxy.ForwardLog(message);
                }
                catch
                {
                }
            };
            // ReSharper restore EmptyGeneralCatchClause
        }
コード例 #17
0
        public int Run(string currentDirectory, Dictionary <string, string> environmentVariables, string[] args, bool shadowCache, int?debuggerProcessId, string callbackAddress)
        {
            bool lockTaken = false;

            try
            {
                Monitor.TryEnter(runLock, ref lockTaken);
                if (!lockTaken)
                {
                    // Busy, exit right away
                    return(BusyReturnCode);
                }

                // Do your stuff...
                Console.WriteLine("Run Received {0}", string.Join(" ", args));

                upTime.Restart();

                if (debuggerProcessId.HasValue && !Debugger.IsAttached)
                {
                    using (var debugger = VisualStudioDebugger.GetByProcess(debuggerProcessId.Value))
                    {
                        debugger?.Attach();
                    }
                }
                using (var callbackChannel = new NpClient <IServerLogger>(new NpEndPoint(callbackAddress)))
                {
                    var result = shadowManager.Run(currentDirectory, environmentVariables, args, shadowCache, callbackChannel);
                    return(result);
                }
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(runLock);
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Gets the current proxy.
        /// </summary>
        /// <returns>StrideCommandsProxy.</returns>
        public static IStrideCommands GetProxy()
        {
            lock (commandProxyLock)
            {
                // New instance?
                bool shouldReload = strideCommands == null || solutionChanged || ShouldReload();
                if (!shouldReload)
                {
                    // TODO: Assemblies changed?
                    //shouldReload = ShouldReload();
                }

                // If new instance or assemblies changed, reload
                if (shouldReload)
                {
                    ClosePipeAndProcess();

                    var address = "Stride/VSPackageCommands/" + Guid.NewGuid();

                    var stridePackageInfo = FindStrideSdkDir(solution).Result;
                    if (stridePackageInfo.LoadedVersion == null)
                    {
                        return(null);
                    }

                    var commandAssembly   = stridePackageInfo.SdkPaths.First(x => Path.GetFileNameWithoutExtension(x) == "Stride.VisualStudio.Commands");
                    var commandExecutable = Path.ChangeExtension(commandAssembly, ".exe"); // .NET Core: .dll => .exe

                    var startInfo = new ProcessStartInfo
                    {
                        // Note: try to get exec server if it exists, otherwise use CompilerApp.exe
                        FileName         = commandExecutable,
                        Arguments        = $"--pipe=\"{address}\"",
                        WorkingDirectory = Environment.CurrentDirectory,
                        UseShellExecute  = false,
                    };

                    var strideCommandsProcess = new Process {
                        StartInfo = startInfo
                    };
                    strideCommandsProcess.Start();

                    strideCommandsProcessJob = new AttachedChildProcessJob(strideCommandsProcess);

                    for (int i = 0; i < 10; ++i)
                    {
                        try
                        {
                            strideCommands = new NpClient <IStrideCommands>(new NpEndPoint(address + "/IStrideCommands"));
                            break;
                        }
                        catch
                        {
                            // Last try, forward exception
                            if (i == 9)
                            {
                                throw;
                            }
                            // Wait until process is ready to accept connections
                            Thread.Sleep(100);
                        }
                    }

                    solutionChanged = false;
                }

                return(strideCommands?.Proxy);
            }
        }
コード例 #19
0
        /// <summary>
        /// Runs the assembly with the specified arguments.xit
        /// </summary>
        /// <param name="workingDirectory">The working directory.</param>
        /// <param name="environmentVariables">The environment variables.</param>
        /// <param name="args">The main arguments.</param>
        /// <param name="shadowCache">If [true], use shadow cache.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>System.Int32.</returns>
        public int Run(string workingDirectory, Dictionary <string, string> environmentVariables, string[] args, bool shadowCache, NpClient <IServerLogger> callbackChannel)
        {
            lock (disposingLock)
            {
                if (isDisposed)
                {
                    callbackChannel.Proxy.OnLog("Error, server is being shutdown, cannot run Compiler", ConsoleColor.Red);
                    return(1);
                }
            }


            AppDomainShadow shadowDomain = null;

            try
            {
                shadowDomain = GetOrNew(shadowCache, IsCachingAppDomain);
                return(shadowDomain.Run(workingDirectory, environmentVariables, args, callbackChannel));
            }
            finally
            {
                if (shadowDomain != null)
                {
                    shadowDomain.EndRun();
                    if (!IsCachingAppDomain)
                    {
                        shadowDomain.Dispose();
                    }
                }
            }
        }
コード例 #20
0
ファイル: GameDebuggerHost.cs プロジェクト: Aggror/Stride
 public void RegisterTarget(string callbackAddress)
 {
     callbackChannel = new NpClient <IGameDebuggerTarget>(new NpEndPoint(callbackAddress));
     target.TrySetResult(callbackChannel.Proxy);
 }
コード例 #21
0
ファイル: Program.cs プロジェクト: Ethereal77/stride
        public static int Main(string[] args)
        {
            var exeName  = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
            var showHelp = false;

            string hostPipe           = null;
            bool   waitDebuggerAttach = false;

            var p = new OptionSet
            {
                "Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)",
                "Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)",
                "Stride Debugger Host tool - Version: " + Format("{0}.{1}.{2}",
                                                                 typeof(Program).Assembly.GetName().Version.Major,
                                                                 typeof(Program).Assembly.GetName().Version.Minor,
                                                                 typeof(Program).Assembly.GetName().Version.Build),
                Empty,
                $"Usage: {exeName} --host=[hostpipe]",
                Empty,
                "=== Options ===",
                Empty,
                { "h|help", "Show this message and exit", v => showHelp = v != null },
                { "host=", "Host pipe", v => hostPipe = v },
                { "wait-debugger-attach", "Process will wait for a debugger to attach, for 5 seconds", v => waitDebuggerAttach = true },
            };

            try
            {
                var unexpectedArgs = p.Parse(args);
                if (unexpectedArgs.Any())
                {
                    throw new OptionException($"Unexpected arguments [{Join(", ", unexpectedArgs)}].", "args");
                }

                if (waitDebuggerAttach)
                {
                    // Wait for 5 second max
                    for (int i = 0; i < 500; ++i)
                    {
                        if (System.Diagnostics.Debugger.IsAttached)
                        {
                            break;
                        }

                        Thread.Sleep(10);
                    }
                }

                if (hostPipe is null)
                {
                    throw new OptionException("Host pipe not specified.", "host");
                }

                // Open ServiceWire channel with master builder
                using var channel = new NpClient <IGameDebuggerHost>(new NpEndPoint(hostPipe));
                var gameDebuggerTarget = new GameDebuggerTarget();
                gameDebuggerTarget.MainLoop(channel.Proxy);
            }
            catch (OptionException ex)
            {
                Console.WriteLine("Command option '{0}': {1}", ex.OptionName, ex.Message);
                return(-1);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unhandled exception: {0}", ex);
                return(-1);
            }

            return(0);
        }
コード例 #22
0
ファイル: IPCMessaging.cs プロジェクト: Levrum/Levrum
 public void Dispose()
 {
     NpClient?.Dispose();
     NpClient = null;
 }
コード例 #23
0
ファイル: PackageBuilder.cs プロジェクト: ykafia/stride
        private BuildResultCode BuildSlave()
        {
            // Mount build path
            ((FileSystemProvider)VirtualFileSystem.ApplicationData).ChangeBasePath(builderOptions.BuildDirectory);

            VirtualFileSystem.CreateDirectory(VirtualFileSystem.ApplicationDatabasePath);

            // Open ServiceWire Client Channel
            using (var client = new NpClient <IProcessBuilderRemote>(new NpEndPoint(builderOptions.SlavePipe), new StrideServiceWireSerializer()))
            {
                RegisterRemoteLogger(client);

                // Make sure to laod all assemblies containing serializers
                // TODO: Review how costly it is to do so, and possibily find a way to restrict what needs to be loaded (i.e. only app plugins?)
                foreach (var assemblyLocation in client.Proxy.GetAssemblyContainerLoadedAssemblies())
                {
                    AssemblyContainer.Default.LoadAssemblyFromPath(assemblyLocation, builderOptions.Logger);
                }

                // Create scheduler
                var scheduler = new Scheduler();

                var status = ResultStatus.NotProcessed;

                // Schedule command
                string buildPath = builderOptions.BuildDirectory;

                Builder.OpenObjectDatabase(buildPath, VirtualFileSystem.ApplicationDatabaseIndexName);

                var         logger      = builderOptions.Logger;
                MicroThread microthread = scheduler.Add(async() =>
                {
                    // Deserialize command and parameters
                    Command command = client.Proxy.GetCommandToExecute();

                    // Run command
                    var inputHashes    = FileVersionTracker.GetDefault();
                    var builderContext = new BuilderContext(inputHashes, null);

                    var commandContext = new RemoteCommandContext(client.Proxy, command, builderContext, logger);
                    MicrothreadLocalDatabases.MountDatabase(commandContext.GetOutputObjectsGroups());
                    command.PreCommand(commandContext);
                    status = await command.DoCommand(commandContext);
                    command.PostCommand(commandContext, status);

                    // Returns result to master builder
                    client.Proxy.RegisterResult(commandContext.ResultEntry);
                });

                while (true)
                {
                    scheduler.Run();

                    // Exit loop if no more micro threads
                    lock (scheduler.MicroThreads)
                    {
                        if (!scheduler.MicroThreads.Any())
                        {
                            break;
                        }
                    }

                    Thread.Sleep(0);
                }

                // Rethrow any exception that happened in microthread
                if (microthread.Exception != null)
                {
                    builderOptions.Logger.Fatal(microthread.Exception.ToString());
                    return(BuildResultCode.BuildError);
                }

                if (status == ResultStatus.Successful || status == ResultStatus.NotTriggeredWasSuccessful)
                {
                    return(BuildResultCode.Successful);
                }

                return(BuildResultCode.BuildError);
            }
        }
コード例 #24
0
ファイル: AppDomainShadow.cs プロジェクト: hammondjm/stride
        /// <summary>
        /// Runs the main entry point method passing arguments to it
        /// </summary>
        /// <param name="workingDirectory"></param>
        /// <param name="environmentVariables">The environment variables.</param>
        /// <param name="args">The arguments.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>System.Int32.</returns>
        /// <exception cref="System.InvalidOperationException">Must call TryLock before calling this method</exception>
        public int Run(string workingDirectory, Dictionary <string, string> environmentVariables, string[] args, NpClient <IServerLogger> callbackChannel)
        {
            if (!isRunning)
            {
                throw new InvalidOperationException("Must call TryLock before calling this method");
            }

            try
            {
                lastRunTime = DateTime.Now;
                appDomainCallback.CallbackChannel      = callbackChannel;
                appDomainCallback.CurrentDirectory     = workingDirectory;
                appDomainCallback.EnvironmentVariables = environmentVariables;
                appDomainCallback.Arguments            = args;
                appDomain.DoCallBack(appDomainCallback.Run);
                var result = appDomain.GetData("Result") as int?;

                //var result = appDomain.ExecuteAssembly(mainAssemblyPath, args);
                Console.WriteLine("Return result: {0}", result);
                return(result ?? -1);
            }
            catch (Exception exception)
            {
                callbackChannel.Proxy.OnLog(string.Format("Unexpected exception: {0}", exception), ConsoleColor.Red);
                return(1);
            }
            finally
            {
                lastRunTime = DateTime.Now;
            }
        }