示例#1
0
        public void NamedPipeActivityTest()
        {
            const string pipeName = "test.pipe";
            var          logger   = XUnitLogger.CreateLogger(_testOutput);

            // Arrange
            var activity = new Activity
            {
                Id   = Guid.NewGuid().ToString("N"),
                Type = ActivityTypes.Message,
                From = new ChannelAccount {
                    Id = "testUser"
                },
                Conversation = new ConversationAccount {
                    Id = Guid.NewGuid().ToString("N")
                },
                Recipient = new ChannelAccount {
                    Id = "testBot"
                },
                ServiceUrl = "unknown",
                ChannelId  = "test",
                Text       = "hi"
            };

            var bot = new StreamingTestBot((turnContext, cancellationToken) =>
            {
                var activityClone  = JsonConvert.DeserializeObject <Activity>(JsonConvert.SerializeObject(turnContext.Activity));
                activityClone.Text = $"Echo: {turnContext.Activity.Text}";

                return(turnContext.SendActivityAsync(activityClone, cancellationToken));
            });

            var verifiedResponse     = false;
            var clientRequestHandler = new Mock <RequestHandler>();

            clientRequestHandler
            .Setup(h => h.ProcessRequestAsync(It.IsAny <ReceiveRequest>(), It.IsAny <ILogger <RequestHandler> >(), It.IsAny <object>(), It.IsAny <CancellationToken>()))
            .Returns <ReceiveRequest, ILogger <RequestHandler>, object, CancellationToken>((request, anonLogger, context, cancellationToken) =>
            {
                var body     = request.ReadBodyAsString();
                var response = JsonConvert.DeserializeObject <Activity>(body, SerializationSettings.DefaultDeserializationSettings);

                Assert.NotNull(response);
                Assert.Equal("Echo: hi", response.Text);
                verifiedResponse = true;

                return(Task.FromResult(StreamingResponse.OK()));
            });

            // Act
            var server        = new CloudAdapter(new StreamingTestBotFrameworkAuthentication(), logger);
            var serverRunning = server.ConnectNamedPipeAsync(pipeName, bot, "testAppId", "testAudience", "testCallerId");
            var client        = new NamedPipeClient(pipeName, ".", clientRequestHandler.Object, logger: logger);
            var clientRunning = client.ConnectAsync();

            SimulateMultiTurnConversation(1, new[] { activity }, client, logger);

            // Assert
            Assert.True(verifiedResponse);
        }
示例#2
0
        static void Main(string[] args)
        {
            var client = new NamedPipeClient("npstest", TimeSpan.FromSeconds(2));

            client.ConnectAsync().Wait();
            client.SendAsync(new byte[] { 1, 2, 3 }).Wait();
        }
        public async void NamedPipeClient_SendAsync_With_No_Message()
        {
            var pipeName = Guid.NewGuid().ToString().Substring(0, 18);
            var pipe     = new NamedPipeClient(pipeName);

            await Assert.ThrowsAsync <ArgumentNullException>(() => pipe.SendAsync(null));
        }
示例#4
0
        private static bool KillOtherInstanceAndRestart(string pipeName, bool createdNew)
        {
            //Mutex used by another instance of the app
            //Ask the other instance to stop and restart this instance to get the mutex again.
            if (!createdNew)
            {
                using var pipeClient = new NamedPipeClient(pipeName);
                Log.Information("Other instance detected.");
                pipeClient.SendMsg("Close");
                Log.Information("Other instance detected: asked to stop, restarting now.");
                RestartApp();
                return(true);
            }

            using var pipeServer = new NamedPipeServer(pipeName);
            pipeServer.Start(message =>
            {
                if (message == "Close")
                {
                    Log.Information("Other instance detected and asked to stop.");
                    Application.Exit();
                }
            });
            return(false);
        }
示例#5
0
        private void HandleMultiInstance()
        {
            _mutex = new Mutex(true, @"Global\WinDynamicDesktop", out bool isFirstInstance);
            GC.KeepAlive(_mutex);

            if (isFirstInstance)
            {
                _namedPipe = new NamedPipeServer <string>("WinDynamicDesktop");
                _namedPipe.ClientMessage += OnNamedPipeClientMessage;
                _namedPipe.Start();
            }
            else
            {
                if (ThemeManager.importPaths.Count > 0)
                {
                    var namedPipeClient = new NamedPipeClient <string>("WinDynamicDesktop");
                    namedPipeClient.Start();
                    namedPipeClient.WaitForConnection();
                    namedPipeClient.PushMessage(string.Join("|", ThemeManager.importPaths));
                    Thread.Sleep(1000);
                    namedPipeClient.Stop();
                }
                else
                {
                    MessageBox.Show(_("Another instance of WinDynamicDesktop is already " +
                                      "running. You can access it by clicking on the icon in the system tray."),
                                    _("Error"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                Environment.Exit(0);
            }
        }
        public void StartEchoServerAndClientAndSend()
        {
            var     pipeName = Guid.NewGuid().ToString("N");
            Process p        = null;

            try {
                p = Program.StartEchoServer(pipeName, 4, 1);
                var client = new NamedPipeClient(pipeName, 100);
                var c      = 0;
                var m      = 1000;
                for (var i = 0; i < m; i++)
                {
                    try {
                        var response = client.SendRequest("Ping");
                        if (response == "Pong")
                        {
                            c++;
                        }
                    }
                    catch (Exception ex) {
                        Console.WriteLine($"Exception at counter: {i}");
                        throw;
                    }
                }
                client.Dispose();
                Assert.AreEqual(m, c);
            }
            finally {
                p?.CloseMainWindow();
                p?.WaitForExit(500);
                p?.Kill();
                Debug.WriteLine("done");
            }
        }
示例#7
0
 public void init()
 {
     try
     {
         if (Initilized)
         {
             return;
         }
         Initilized   = false;
         _windowCache = new HwndCache();
         Log.Debug("javahook.init()");
         accessBridge.Initilized += (e1, e2) =>
         {
             Initilized = true;
             Log.Information("javahook._accessBridge.Initilized");
             OnInitilized?.Invoke(accessBridge);
         };
         accessBridge.Initialize();
         refreshJvms(200);
         EnsureJavaBridge();
         pipeclient = new NamedPipeClient <JavaEvent>("openrpa_javabridge");
         pipeclient.ServerMessage += Pipeclient_ServerMessage;
         pipeclient.AutoReconnect  = true;
         pipeclient.Start();
     }
     catch (Exception ex)
     {
         Log.Error(ex.ToString());
     }
 }
示例#8
0
 public MyClient(string pipeName)
 {
     client = new NamedPipeClient <MyMessage>(pipeName);
     client.ServerMessage += OnServerMessage;
     client.Error         += OnError;
     client.Start();
 }
示例#9
0
 public MyClient(string pipeName)
 {
     this.client = new NamedPipeClient<string>(pipeName);
     client.ServerMessage += OnServerMessage;
     client.Error += OnError;
     client.Start();
 }
示例#10
0
文件: Program.cs 项目: noonnee/GVFS
        private static void RunLockRequest(string[] args, LockRequestDelegate requestToRun)
        {
            try
            {
                if (ShouldLock(args))
                {
                    using (NamedPipeClient pipeClient = new NamedPipeClient(enlistmentPipename))
                    {
                        if (!pipeClient.Connect())
                        {
                            ExitWithError("The repo does not appear to be mounted. Use 'gvfs status' to check.");
                        }

                        string fullCommand = "git " + string.Join(" ", args.Skip(1).Where(arg => !arg.StartsWith(GitPidArg)));
                        int    pid         = GetParentPid(args);

                        Process parentProcess = null;
                        if (pid == Program.InvalidProcessId ||
                            !ProcessHelper.TryGetProcess(pid, out parentProcess))
                        {
                            ExitWithError("GVFS.Hooks: Unable to find parent git.exe process " + "(PID: " + pid + ").");
                        }

                        requestToRun(fullCommand, pid, parentProcess, pipeClient);
                    }
                }
            }
            catch (Exception exc)
            {
                ExitWithError(
                    "Unable to initialize Git command.",
                    "Ensure that GVFS is running.",
                    exc.ToString());
            }
        }
示例#11
0
        public void SendNotification(NamedPipeMessages.Notification.Request request)
        {
            string pipeName = Path.Combine(Path.GetTempPath(), NotificationServerPipeName);

            using (NamedPipeClient client = new NamedPipeClient(pipeName))
            {
                if (client.Connect())
                {
                    try
                    {
                        client.SendRequest(request.ToMessage());
                    }
                    catch (Exception ex)
                    {
                        EventMetadata metadata = new EventMetadata();
                        metadata.Add("Area", nameof(NotificationHandler));
                        metadata.Add("Exception", ex.ToString());
                        metadata.Add(TracingConstants.MessageKey.ErrorMessage, "MacOS notification display error");
                        this.tracer.RelatedError(metadata, $"MacOS notification: {request.Title} - {request.Message}.");
                    }
                }
                else
                {
                    this.tracer.RelatedError($"ERROR: Communication failure with native notification display tool. Notification info: {request.Title} - {request.Message}.");
                }
            }
        }
示例#12
0
        private void AcquireLock(string enlistmentRoot)
        {
            string pipeName = Paths.GetNamedPipeName(enlistmentRoot);

            using (NamedPipeClient pipeClient = new NamedPipeClient(pipeName))
            {
                try
                {
                    if (!pipeClient.Connect())
                    {
                        this.ReportErrorAndExit("Unable to connect to GVFS while acquiring lock to unmount.  Try 'gvfs status' to verify if the repo is mounted.");
                        return;
                    }

                    Process currentProcess = Process.GetCurrentProcess();
                    string  result         = null;
                    if (!GVFSLock.TryAcquireGVFSLockForProcess(
                            this.Unattended,
                            pipeClient,
                            "gvfs unmount",
                            currentProcess.Id,
                            GVFSPlatform.Instance.IsElevated(),
                            checkAvailabilityOnly: false,
                            gvfsEnlistmentRoot: enlistmentRoot,
                            result: out result))
                    {
                        this.ReportErrorAndExit("Unable to acquire the lock prior to unmount. " + result);
                    }
                }
                catch (BrokenPipeException)
                {
                    this.ReportErrorAndExit("Unable to acquire the lock prior to unmount.  Try 'gvfs status' to verify if the repo is mounted.");
                }
            }
        }
示例#13
0
        public void ConnectClient()
        {
            _client = new NamedPipeClient <PipedData>(ServerName);
            _client.Start();

            _client.WaitForConnection();
        }
示例#14
0
        protected override void PreCreateEnlistment()
        {
            string errorMessage;
            string enlistmentRoot;

            if (!GVFSPlatform.Instance.TryGetGVFSEnlistmentRoot(this.EnlistmentRootPathParameter, out enlistmentRoot, out errorMessage))
            {
                this.ReportErrorAndExit("Error: '{0}' is not a valid GVFS enlistment", this.EnlistmentRootPathParameter);
            }

            if (!this.SkipMountedCheck)
            {
                using (NamedPipeClient pipeClient = new NamedPipeClient(GVFSPlatform.Instance.GetNamedPipeName(enlistmentRoot)))
                {
                    if (pipeClient.Connect(500))
                    {
                        this.ReportErrorAndExit(tracer: null, exitCode: ReturnCode.Success, error: "This repo is already mounted.");
                    }
                }
            }

            if (!DiskLayoutUpgrade.TryRunAllUpgrades(enlistmentRoot))
            {
                this.ReportErrorAndExit("Failed to upgrade repo disk layout. " + ConsoleHelper.GetGVFSLogMessage(enlistmentRoot));
            }

            string error;

            if (!DiskLayoutUpgrade.TryCheckDiskLayoutVersion(tracer: null, enlistmentRoot: enlistmentRoot, error: out error))
            {
                this.ReportErrorAndExit("Error: " + error);
            }
        }
示例#15
0
        protected override void PreExecute(string enlistmentRootPath, ITracer tracer = null)
        {
            this.Output.WriteLine("Validating repo for mount");
            this.CheckElevated();
            this.CheckGVFltRunning();

            if (string.IsNullOrWhiteSpace(enlistmentRootPath))
            {
                enlistmentRootPath = Environment.CurrentDirectory;
            }

            string enlistmentRoot = GVFSEnlistment.GetEnlistmentRoot(enlistmentRootPath);

            if (enlistmentRoot == null)
            {
                this.ReportErrorAndExit("Error: '{0}' is not a valid GVFS enlistment", enlistmentRootPath);
            }

            using (NamedPipeClient pipeClient = new NamedPipeClient(GVFSEnlistment.GetNamedPipeName(enlistmentRoot)))
            {
                if (pipeClient.Connect(500))
                {
                    this.ReportErrorAndExit("This repo is already mounted.  Try running 'gvfs status'.");
                }
            }

            string error;

            if (!RepoMetadata.CheckDiskLayoutVersion(Path.Combine(enlistmentRoot, GVFSConstants.DotGVFSPath), out error))
            {
                this.ReportErrorAndExit("Error: " + error);
            }
        }
示例#16
0
        private void ShouldConnectToServerAndReceiveRandomResponse()
        {
            string       namedPipe              = Resources.GetUniquePipeName();
            const string testMessage            = "TestMessage";
            bool         receivedCorrectMessage = false;

            using (CreateServer(namedPipe, new PipePlatformBase(),
                                (string request, IPC.IConnection connection) =>
            {
                if (request == testMessage)
                {
                    receivedCorrectMessage = true;
                }
                connection.TrySendResponse("RandomResponse");
            }))
            {
                using (INamedPipeClient pipeClient = new NamedPipeClient(namedPipe))
                {
                    if (SendPipeMessage(pipeClient, testMessage))
                    {
                        Assert.NotEqual(pipeClient.ReadRawResponse(), testMessage);
                    }
                }
            }
            Assert.True(receivedCorrectMessage);
        }
示例#17
0
        private void ShouldConnectToServerAndReceiveMultipleResponses()
        {
            string       namedPipe    = Resources.GetUniquePipeName();
            const string testMessage1 = "TestMessage1";
            const string testMessage2 = "TestMessage2";
            const string testMessage3 = "TestMessage3";

            using (CreateServer(namedPipe, new PipePlatformBase(),
                                (string request, IPC.IConnection connection) =>
            {
                connection.TrySendResponse(request);
            }))
            {
                using (INamedPipeClient pipeClient = new NamedPipeClient(namedPipe))
                {
                    if (pipeClient.Connect(3000))
                    {
                        pipeClient.SendRequest(testMessage1);
                        pipeClient.SendRequest(testMessage2);
                        pipeClient.SendRequest(testMessage3);

                        Assert.Equal(pipeClient.ReadRawResponse(), testMessage1);
                        Assert.Equal(pipeClient.ReadRawResponse(), testMessage2);
                        Assert.Equal(pipeClient.ReadRawResponse(), testMessage3);
                    }
                }
            }
        }
示例#18
0
        public MainForm(string[] args)
        {
            InitializeComponent();
            regStateButton.BackColor = Color.DarkGray;

            _accountId     = -1;
            _callId        = -1;
            _recordId      = -1;
            _runBackground = false;

            ParseArgs(args);

            labelIncomeMsgQueu.Text = _pipeName;

            if (!string.IsNullOrEmpty(_pipeName))
            {
                _pipe = new NamedPipeClient(_pipeName);
                _pipe.OnReceivedMessage += OnReceiveMsg;
                _pipe.Start();

                HandsetNotifyMsg msg = new HandsetNotifyMsg();
                msg.MsgNotifyCode = HANDSETMSG_NOTIFY_CODE.MSG_NOTIFY_ONLINE;
                SendMessage(msg);
            }

            if (_runBackground)
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }
        private void LaunchServiceUIIfNotRunning(int sessionId)
        {
            NamedPipeClient client;

            using (client = new NamedPipeClient(GVFSConstants.Service.UIName))
            {
                if (!client.Connect())
                {
                    this.tracer.RelatedError($"Could not connect with {GVFSConstants.Service.UIName}. Attempting to relaunch.");

                    this.TerminateExistingProcess(GVFSConstants.Service.UIName, sessionId);

                    CurrentUser currentUser = new CurrentUser(this.tracer, sessionId);
                    if (!currentUser.RunAs(
                            Configuration.Instance.GVFSServiceUILocation,
                            string.Empty))
                    {
                        this.tracer.RelatedError("Could not start " + GVFSConstants.Service.UIName);
                    }
                    else
                    {
                        this.tracer.RelatedInfo($"Successfully launched {GVFSConstants.Service.UIName}. ");
                    }
                }
            }
        }
        public void SetUp()
        {
            Logger.Debug("Setting up test...");

            _barrier.Reset();

            _server = new NamedPipeServer<byte[]>(PipeName);
            _client = new NamedPipeClient<byte[]>(PipeName);

            _expectedData = null;
            _expectedHash = null;
            _actualData = null;
            _actualHash = null;
            _clientDisconnected = false;

            _server.ClientDisconnected += ServerOnClientDisconnected;
            _server.ClientMessage += ServerOnClientMessage;

            _server.Error += ServerOnError;
            _client.Error += ClientOnError;

            _server.Start();
            _client.Start();

            // Give the client and server a few seconds to connect before sending data
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Logger.Debug("Client and server started");
            Logger.Debug("---");

            _startTime = DateTime.Now;
        }
示例#21
0
        public void SetUp()
        {
            Logger.Debug("Setting up test...");

            _barrier.Reset();

            _server = new NamedPipeServer <byte[]>(PipeName);
            _client = new NamedPipeClient <byte[]>(PipeName);

            _expectedData       = null;
            _expectedHash       = null;
            _actualData         = null;
            _actualHash         = null;
            _clientDisconnected = false;

            _server.ClientDisconnected += ServerOnClientDisconnected;
            _server.ClientMessage      += ServerOnClientMessage;

            _server.Error += ServerOnError;
            _client.Error += ClientOnError;

            _server.Start();
            _client.Start();

            // Give the client and server a few seconds to connect before sending data
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Logger.Debug("Client and server started");
            Logger.Debug("---");

            _startTime = DateTime.Now;
        }
 private void PipeClientForceDisconnectAfterError(ref bool _pipeClientProcessErrorOccurred, ref bool _pipeClientDiconnected, ref bool _consoleProcessDisconnected)
 {
     #region Error handling message
     if (_pipeClientProcessErrorOccurred || _pipeClientDiconnected || _consoleProcessDisconnected)
     {
         //Don't disconnect on "consoleProcessErrorOccurred" Console Errors, Error from console can be data error, database error, etc..
         try
         {
             if (pipeClient != null)
             {
                 Logger.Trace("[Windows Live Photo Gallery | Pipe Client] Force Disconnect After Error");
                 pipeClient.Stop();
                 pipeClient.WaitForDisconnection(5000);
             }
         }
         finally
         {
             lock (_PipeClientLock)
             {
                 pipeClient            = null;
                 pipeClientDiconnected = true;
                 Logger.Trace("[Windows Live Photo Gallery | Pipe Client] Force Disconnect After Error - null");
             }
         }
     }
     #endregion
 }
        public void SetUp()
        {
            Logger.Debug("Setting up test...");

            _barrier.Reset();
            _exceptions.Clear();

            var serializer = new BinaryFormatterSerializer <TestCollection>();

            _server = new NamedPipeServer <TestCollection>(PipeName, serializer);
            _client = new NamedPipeClient <TestCollection>(PipeName, serializer);

            _expectedData       = null;
            _expectedHash       = 0;
            _actualData         = null;
            _actualHash         = 0;
            _clientDisconnected = false;

            _server.ClientMessage += ServerOnClientMessage;

            _server.Error += OnError;
            _client.Error += OnError;

            _server.Start();
            _client.Start();

            // Give the client and server a few seconds to connect before sending data
            Thread.Sleep(TimeSpan.FromSeconds(1));

            Logger.Debug("Client and server started");
            Logger.Debug("---");

            _startTime = DateTime.Now;
        }
示例#24
0
        private static void RunLockRequest(string[] args, bool unattended, LockRequestDelegate requestToRun)
        {
            try
            {
                if (ShouldLock(args))
                {
                    using (NamedPipeClient pipeClient = new NamedPipeClient(enlistmentPipename))
                    {
                        if (!pipeClient.Connect())
                        {
                            ExitWithError("The repo does not appear to be mounted. Use 'gvfs status' to check.");
                        }

                        int pid = GetParentPid(args);
                        if (pid == Program.InvalidProcessId ||
                            !GVFSHooksPlatform.IsProcessActive(pid))
                        {
                            ExitWithError("GVFS.Hooks: Unable to find parent git.exe process " + "(PID: " + pid + ").");
                        }

                        requestToRun(unattended, args, pid, pipeClient);
                    }
                }
            }
            catch (Exception exc)
            {
                ExitWithError(
                    "Unable to initialize Git command.",
                    "Ensure that GVFS is running.",
                    exc.ToString());
            }
        }
示例#25
0
 public void SendNotification(NamedPipeMessages.Notification.Request request)
 {
     using (NamedPipeClient client = new NamedPipeClient(GVFSConstants.Service.UIName))
     {
         if (client.Connect())
         {
             try
             {
                 if (!client.TrySendRequest(request.ToMessage()))
                 {
                     this.tracer.RelatedInfo("Failed to send notification request to " + GVFSConstants.Service.UIName);
                 }
             }
             catch (Exception ex)
             {
                 EventMetadata metadata = new EventMetadata();
                 metadata.Add("Exception", ex.ToString());
                 metadata.Add("Identifier", request.Id);
                 this.tracer.RelatedError(metadata, $"{nameof(this.SendNotification)}- Could not send notification request({request.Id}. {ex.ToString()}");
             }
         }
         else
         {
             this.tracer.RelatedError($"{nameof(this.SendNotification)}- Could not connect with GVFS.Service.UI, failed to send notification request({request.Id}.");
         }
     }
 }
示例#26
0
        private void StartClient(string pipeName)
        {
            var clientTask = RunClientAsync(NamedPipeClient.CreatePipeStream(pipeName));

            // Wait for the client to exit.
            clientTask.GetAwaiter().GetResult();
        }
示例#27
0
        protected override void PreCreateEnlistment()
        {
            this.CheckGVFltHealthy();

            string enlistmentRoot = Paths.GetGVFSEnlistmentRoot(this.EnlistmentRootPath);

            if (enlistmentRoot == null)
            {
                this.ReportErrorAndExit("Error: '{0}' is not a valid GVFS enlistment", this.EnlistmentRootPath);
            }

            if (!this.SkipMountedCheck)
            {
                using (NamedPipeClient pipeClient = new NamedPipeClient(Paths.GetNamedPipeName(enlistmentRoot)))
                {
                    if (pipeClient.Connect(500))
                    {
                        this.ReportErrorAndExit(ReturnCode.Success, "This repo is already mounted.");
                    }
                }
            }

            bool   allowUpgrade = true;
            string error;

            if (!RepoMetadata.CheckDiskLayoutVersion(Path.Combine(enlistmentRoot, GVFSConstants.DotGVFS.Root), allowUpgrade, out error))
            {
                this.ReportErrorAndExit("Error: " + error);
            }
        }
示例#28
0
        private static void AcquireLock(string enlistmentPipename)
        {
            using (NamedPipeClient pipeClient = new NamedPipeClient(enlistmentPipename))
            {
                if (!pipeClient.Connect())
                {
                    throw new Exception("The repo does not appear to be mounted. Use 'gvfs status' to check.");
                }

                int pid = Process.GetCurrentProcess().Id;

                string result;
                if (!GVFSLock.TryAcquireGVFSLockForProcess(
                        unattended: false,
                        pipeClient: pipeClient,
                        fullCommand: AcquireGVFSLockVerb.fullCommand,
                        pid: pid,
                        isElevated: false,
                        isConsoleOutputRedirectedToFile: false,
                        checkAvailabilityOnly: false,
                        gvfsEnlistmentRoot: null,
                        gitCommandSessionId: string.Empty,
                        result: out result))
                {
                    throw new Exception(result);
                }
            }
        }
示例#29
0
        private void HandleMultiInstance()
        {
            _mutex = new Mutex(true, @"Global\WinDynamicDesktop", out bool isFirstInstance);
            GC.KeepAlive(_mutex);

            if (isFirstInstance)
            {
                _namedPipe = new NamedPipeServer <string[]>("WinDynamicDesktop");
                _namedPipe.ClientMessage += OnNamedPipeClientMessage;
                _namedPipe.Start();
            }
            else
            {
                if (ThemeManager.importPaths.Count > 0)
                {
                    // TODO Test passing string[] through named pipe
                    var namedPipeClient = new NamedPipeClient <string[]>("WinDynamicDesktop");
                    namedPipeClient.Start();
                    namedPipeClient.WaitForConnection();
                    namedPipeClient.PushMessage(ThemeManager.importPaths.ToArray());
                    Thread.Sleep(1000);
                    namedPipeClient.Stop();
                }
                else
                {
                    MessageDialog.ShowWarning(_("Another instance of WinDynamicDesktop is already running. You can " +
                                                "access it by clicking on the icon in the system tray."), _("Error"));
                }

                Environment.Exit(0);
            }
        }
示例#30
0
        public override void MyDispose()
        {
            if (!this.disposed)
            {
                this.Log("[SharedContext " + (this._lock?"Client":"Trigger") + "] Destroying. > " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fffff tt"));
                if (this._lock)
                {
                    this.theClient.PushMessage(this.deserialisedContextContents);

                    this.expectingLastMessage = true;
                    for (int i = 0; i < 10; i++)
                    {
                        if (!this.lastMessageReceived)
                        {
                            Thread.Sleep(5);
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (!this.lastMessageReceived)
                    {
                        this.Log("[SharedContext Client] Destroying. The last Server message hasn't been received > " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fffff tt"));
                    }

                    this._dotNetMutex.ReleaseMutex();
                }

                this.theClient.Stop();
                this.theClient = null;
                this.disposed  = true;
            }
        }
示例#31
0
        protected override void Execute(GVFSEnlistment enlistment, ITracer tracer = null)
        {
            this.CheckAntiVirusExclusion(enlistment);

            this.Output.WriteLine("Attempting to connect to GVFS at {0}...", enlistment.EnlistmentRoot);
            using (NamedPipeClient pipeClient = new NamedPipeClient(enlistment.NamedPipeName))
            {
                if (!pipeClient.Connect())
                {
                    this.ReportErrorAndExit("Unable to connect to GVFS.  Try running 'gvfs mount'");
                }

                this.Output.WriteLine("Connected");
                this.Output.WriteLine();

                try
                {
                    pipeClient.SendRequest(NamedPipeMessages.GetStatus.Request);
                    NamedPipeMessages.GetStatus.Response getStatusResponse =
                        NamedPipeMessages.GetStatus.Response.FromJson(pipeClient.ReadRawResponse());

                    this.Output.WriteLine("Mount status: " + getStatusResponse.MountStatus);
                    this.Output.WriteLine("GVFS Lock: " + getStatusResponse.LockStatus);
                    this.Output.WriteLine("Enlistment root: " + getStatusResponse.EnlistmentRoot);
                    this.Output.WriteLine("Repo URL: " + getStatusResponse.RepoUrl);
                    this.Output.WriteLine("Objects URL: " + getStatusResponse.ObjectsUrl);
                    this.Output.WriteLine("Background operations: " + getStatusResponse.BackgroundOperationCount);
                    this.Output.WriteLine("Disk layout version: " + getStatusResponse.DiskLayoutVersion);
                }
                catch (BrokenPipeException e)
                {
                    this.ReportErrorAndExit("Unable to communicate with GVFS: " + e.ToString());
                }
            }
        }
示例#32
0
        private void AcquireLock(string enlistmentRoot)
        {
            string pipeName = Paths.GetNamedPipeName(enlistmentRoot);

            using (NamedPipeClient pipeClient = new NamedPipeClient(pipeName))
            {
                try
                {
                    if (!pipeClient.Connect())
                    {
                        this.ReportErrorAndExit("Unable to connect to GVFS while acquiring lock to unmount.  Try 'gvfs status' to verify if the repo is mounted.");
                        return;
                    }

                    Process currentProcess = Process.GetCurrentProcess();
                    string  result         = null;
                    if (!GVFSLock.TryAcquireGVFSLockForProcess(
                            pipeClient,
                            "gvfs unmount",
                            currentProcess.Id,
                            currentProcess,
                            enlistmentRoot,
                            out result))
                    {
                        this.ReportErrorAndExit("Unable to acquire the lock prior to unmount. " + result);
                    }
                }
                catch (BrokenPipeException)
                {
                    this.ReportErrorAndExit("Unable to acquire the lock prior to unmount.  Try 'gvfs status' to verify if the repo is mounted.");
                }
            }
        }
        public void Generate(int thumbnailWidth, int secondStep, string thumbnailDir, string filepath, NamedPipeClient<string> mediaScribeServer)
        {
            if (State != GeneratorState.Stopped)
                throw new Exception("ThumbnailGenerator must be in a 'stopped' state before we can start generating thumbnails. Currently, it is in state: " + State.ToString());

            State = GeneratorState.Running;
            GenerateImpl(thumbnailWidth, secondStep, thumbnailDir, filepath, mediaScribeServer);
            State = GeneratorState.Stopped;
        }
示例#34
0
 public MyClient(string pipeName)
 {
     var client = new NamedPipeClient<MyMessage>(pipeName);
     client.ServerMessage += OnServerMessage;
     client.Error += OnError;
     client.Start();
     while (KeepRunning)
     {
         // Do nothing - wait for user to press 'q' key
     }
     client.Stop();
 }
示例#35
0
文件: App.xaml.cs 项目: jaywick/pastr
        protected override void OnStartup(StartupEventArgs e)
        {
            var message = String.Join("\n", Environment.GetCommandLineArgs().Skip(1));
            //MessageBox.Show(message);

            var client = new NamedPipeClient<string>("io-jaywick-labs-pastr-messaging");
            client.Start();
            client.WaitForConnection();
            client.PushMessage(message);

            Shutdown(0);
        }
示例#36
0
        public void Shutdown()
        {
            var client = new NamedPipeClient<PipeMessage>(PipeName);
            client.Error += Client_Error;
            client.ServerMessage += Client_ServerMessage;

            Console.WriteLine("Staring client...");
            client.Start();

            Console.WriteLine("Waiting for connection...");
            client.WaitForConnection(TimeSpan.FromSeconds(1));

            // wait for ack
            Console.WriteLine("Waiting for ack from scheduler...");
            Task.Delay(TimeSpan.FromSeconds(2)).Wait();

            if (_ack)
            {
                Console.WriteLine("Sending shutdown request...");
                client.PushMessage(new PipeMessage() { ShutdownRequest = true });

                // wait for max 60 seconds
                try
                {
                    Console.WriteLine("Waiting for shutting down...");
                    Task.Delay(TimeSpan.FromSeconds(60)).Wait(_waitToken.Token);
                    Console.WriteLine("Timeout exceeded.");
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("Scheduler shutted down.");
                    // ignored
                }
            }
            else
            {
                Console.WriteLine("Scheduler not responding. Probably not running.");
            }
        }
        private void GenerateImpl(int thumbnailWidth, int secondStep, string thumbnailDir, string filepath, NamedPipeClient<string> mediaScribeServer)
        {
            //TODO - ensure that these don't get wrapped in quotes, so we don't have to strip them out.
            filepath = filepath.Substring(1, filepath.Length - 2);
            thumbnailDir = thumbnailDir.Substring(1, thumbnailDir.Length - 2);

            if (false == Directory.Exists(thumbnailDir))
                Directory.CreateDirectory(thumbnailDir);

            if (null == library)
            {
                #region start VLC
                string[] vlcargs = {
                   "--intf", "dummy",                  /* no interface                   */
                   "--vout", "dummy",                  /* we don't want video (output)   */
                   "--no-audio",                       /* we don't want audio (decoding) */
                   "--no-video-title-show",            /* nor the filename displayed     */
                   "--no-stats",                       /* no stats                       */
                   "--no-sub-autodetect-file",         /* we don't want subtitles        */
                   "--no-spu",
                   "--no-osd",

             //      "--no-inhibit",                     /* we don't want interfaces       */
                   "--no-disable-screensaver",         /* we don't want interfaces       */
                   "--no-snapshot-preview",            /* no blending in dummy vout      */
                                      };
                library = LibVLCLibrary.Load(null);
                IntPtr m;

                /* Load the VLC engine */
                inst = library.libvlc_new(vlcargs);

                /* Create a new item */
                m = library.libvlc_media_new_path(inst, filepath);

                /* Create a media player playing environement */
                mp = library.libvlc_media_player_new_from_media(m);

                //hook up the libvlc event listening
                int event_index = 0;
                IntPtr media_player_event_manager = library.libvlc_media_player_event_manager(mp);
                LibVLCLibrary.libvlc_callback_t m_EventManagerEventCallback = EventManager_Event;
                while (event_index < m_Events.Length)
                    if (library.libvlc_event_attach(media_player_event_manager, m_Events[event_index++], m_EventManagerEventCallback, IntPtr.Zero) != 0)
                        throw new LibVLCException(library);

                #endregion
            }
            else
            {
                library.libvlc_media_player_release(mp);
                IntPtr m = library.libvlc_media_new_path(inst, filepath);
                mp = library.libvlc_media_player_new_from_media(m);
                //hook up the libvlc event listening
                int event_index = 0;
                IntPtr media_player_event_manager = library.libvlc_media_player_event_manager(mp);
                LibVLCLibrary.libvlc_callback_t m_EventManagerEventCallback = EventManager_Event;
                while (event_index < m_Events.Length)
                    if (library.libvlc_event_attach(media_player_event_manager, m_Events[event_index++], m_EventManagerEventCallback, IntPtr.Zero) != 0)
                        throw new LibVLCException(library);
            }
            //configure time tracking
            TimeSpan time = new TimeSpan(0, 0, 0);
            TimeSpan step = new TimeSpan(0, 0, secondStep);

            //wait until VLC is playing
            signalPlaying = new SemaphoreSlim(0, 1);
            /* play the media_player */
            int successCode = library.libvlc_media_player_play(mp);
            signalPlaying.Wait();
            if (errorOccured)
            {
                string errormsg = library.libvlc_errmsg();
                throw new Exception("libvlc_MediaPlayerEncounteredError error: " + errormsg ?? "unknown error... ah crap.");
            }

            endReached = false;
            stopped = false;

            int thumbnailHeight = -1;

            long trackLength = library.libvlc_media_player_get_length(mp);

            //while there's still video left, collect screenshots
            while (endReached != true && stopped != true)
            {
                //if we're flagged to cancel, exit out.
                if (State == GeneratorState.Cancelling)
                    return;

                //take screenshot
                string fileName = time.TotalSeconds + ".jpg";
                string thumbnailFullPath = Path.Combine(thumbnailDir, fileName);

                int result = -1;
                do
                {
                    if (endReached)
                        break;
                    //if we're flagged to cancel, exit out.
                    if (State == GeneratorState.Cancelling)
                        return;

                    int tryCount = 3;
                    bool successfulSnapshot = false;
                    Exception error = null;
                    do
                    {
                        try
                        {
                            //if we're flagged to cancel, exit out.
                            if (State == GeneratorState.Cancelling)
                                return;
                            successfulSnapshot = false;
                            result = library.libvlc_video_take_snapshot(mp, 0, thumbnailFullPath, (uint)thumbnailWidth, 0);
                            successfulSnapshot = true;
                        }
                        catch (Exception ex)
                        {
                            tryCount--;
                            error = ex;
                        }
                    }
                    while (!successfulSnapshot && tryCount > 0);
                    if (null != error && tryCount == 0)
                    {
                        throw error;
                    }
                }
                while (false == File.Exists(thumbnailFullPath));

                if (result == 0)
                {
                    mediaScribeServer.PushMessage(time.TotalSeconds.ToString().PadLeft(6, '0') + " " + fileName);
                    //Thread.Sleep(70);
                }

                //increment the time
                time += step;
                //signalPosChanged.Reset();
                library.libvlc_media_player_set_time(mp, (long)time.TotalMilliseconds);
                if (library.libvlc_media_player_get_state(mp) == LibVLCLibrary.libvlc_state_t.libvlc_Playing)
                    library.libvlc_media_player_pause(mp);

                if (library.libvlc_media_player_get_time(mp) > trackLength)
                    return;

                if (endReached)
                    return;
            }
        }
示例#38
0
 public void Dispose()
 {
     _namedPipeClient = null;
        if(_childProcess != null) _childProcess.Dispose();
 }
示例#39
0
        public bool Start()
        {
            if (string.IsNullOrEmpty(FileName))
            {
                Errors.Add("Process Filename can not be null or empty");
                return false;
            }
            if (string.IsNullOrEmpty(PipeName))
            {
                Errors.Add("PipeName can not be null or empty");
                return false;
            }

            _childProcess = new Process();
            _childProcess.StartInfo.FileName = FileName;
            _childProcess.StartInfo.Arguments = Arguments;
            _childProcess.StartInfo.UseShellExecute = false;
            _childProcess.StartInfo.RedirectStandardOutput = false;
            if (!_childProcess.Start())
            {
                Errors.Add("Process could not be started");
                return false;
            }

            _namedPipeClient = new NamedPipeClient(PipeName);
            _namedPipeClient.OnReceivedMessage += new EventHandler<ReceivedMessageEventArgs>(client_OnReceivedMessage);
            _namedPipeClient.Start();
            return true;
        }
 public ThumbnailGeneratorHost()
 {
     mediaScribeServer = new NamedPipeClient<string>("MediaScribe-ThumbnailGenerator");
     mediaScribeServer.Start();
     mediaScribeServer.ServerMessage += mediaScribeServer_ServerMessage;
 }
 private void StartClient()
 {
     Client = new NamedPipeClient(NAME_OF_PIPE);
     Client.OnReceivedMessage += new EventHandler<ReceivedMessageEventArgs>(Client_OnReceivedMessage);
     Client.Start();
 }