Exemplo n.º 1
1
        private async void StartInternal(CancellationToken cancellationToken)
        {
            byte[] buffer = new byte[256];
            var commandBuilder = new StringBuilder();

            var serverStream = new NamedPipeServerStream(this.PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0);

            using (cancellationToken.Register(() => serverStream.Close()))
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    await Task.Factory.FromAsync(serverStream.BeginWaitForConnection, serverStream.EndWaitForConnection, TaskCreationOptions.None);

                    int read = await serverStream.ReadAsync(buffer, 0, buffer.Length);
                    commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));

                    while (!serverStream.IsMessageComplete)
                    {
                        read = serverStream.Read(buffer, 0, buffer.Length);
                        commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));
                    }

                    var response = this.HandleReceivedCommand(commandBuilder.ToString());
                    var responseBytes = Encoding.ASCII.GetBytes(response);
                    serverStream.Write(responseBytes, 0, responseBytes.Length);

                    serverStream.WaitForPipeDrain();
                    serverStream.Disconnect();

                    commandBuilder.Clear();
                }
            }
        }
Exemplo n.º 2
0
        private void UserSignIn(string username, string password)
        {
            string hashed_password = sha256(password);
            MessageBox.Show(hashed_password);
            //send username and password to python and checks if correct
            string info = username + "#" + hashed_password;
            // Open the named pipe.

            var server = new NamedPipeServerStream("Communicate");
            server.WaitForConnection();     
            var br = new BinaryReader(server);
            var bw = new BinaryWriter(server); 
            send(bw, info);
            string message = recv(br); 
            server.Close();
            server.Dispose();

            //if receives true then send the user to the next gui.
            if (message == "1")
            {
                
                SaveFile form = new SaveFile();
                form.Show();

            }
            else
            {
                
                MessageBox.Show("incorrect password or username");
                this.Show();
            }
            
            
        }
Exemplo n.º 3
0
        private void UserSignIn(string username, string password)
        {
            if (username == "")
            {
                MessageBox.Show("Please enter username");
                this.Show();
            }
            else if(password == "")
            {
                MessageBox.Show("Please enter password");
                this.Show();
            }
            else
            {

                string hashed_password = sha256(password);
                //send username and password to python and checks if correct
                string info = "login#" + username + "#" + hashed_password;
                // Open the named pipe.

                var server = new NamedPipeServerStream("Communicate");
                server.WaitForConnection();     
                var br = new BinaryReader(server);
                var bw = new BinaryWriter(server); 
                send(bw, info);
                string message_to_split = recv(br);
                message_to_split = message_to_split + recv(br);
                string message = message_to_split.Split('#')[0];
                if (message_to_split.Split('#')[1] != "0")
                {
                    this.my_uid = message_to_split.Split('#')[2];
                    this.firstname = message_to_split.Split('#')[1];
                    this.lastname = message_to_split.Split('#')[3];
                    MessageBox.Show(my_uid + firstname + lastname);
                }
                server.Close();
                server.Dispose();
                
                //if receives true then send the user to the next gui.
                if (message == "Signed in")
                {
                    string user_info = this.my_uid + "#" + this.firstname + "#" + this.lastname;
                    SaveFile form = new SaveFile(user_info);
                    form.Show();
                }
                else
                {
                
                    MessageBox.Show("incorrect password or username");
                    this.Show();
                }
            
            
            
            }
        }
        void PipeThread()
        {
            NamedPipeServerStream pipeServer = null;
            try
            {
                pipeServer = new NamedPipeServerStream("NowPlayingtunesSongPipe", PipeDirection.InOut);
                pipeServer.WaitForConnection();
                //When Connected
                StreamString stream = new StreamString(pipeServer);
                String playerStr = stream.ReadString();
                Debug.WriteLine("[foobar2000]Song changed.");
                Debug.WriteLine(playerStr);
                Debug.WriteLine("[foobar2000]dump end.");
                String[] playerStrSplit = playerStr.Split('\n');
                Core.iTunesClass song = new Core.iTunesClass();
                song.AlbumArtworkEnabled = false;
                song.SongTitle = playerStrSplit[0];
                song.SongAlbum = playerStrSplit[1];
                song.SongArtist = playerStrSplit[2];
                song.SongAlbumArtist = playerStrSplit[3];
                song.isFoobar = true;
                try
                {
                    song.SongTrackNumber = int.Parse(playerStrSplit[4]);
                }
                catch (Exception ex2)
                {
                }
                song.SongGenre = playerStrSplit[5];
                song.SongComposer = playerStrSplit[6];

                pipeServer.Close();
                pipeServer.Dispose();
                //適当にイベント発生させる
                onSongChangedEvent(song);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("[foobar2000] ERROR");
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                if (pipeServer != null)
                {
                    if (pipeServer.IsConnected)
                    {
                        pipeServer.Dispose();
                    }
                }
            }
            //Remake thread
            StartThread();
        }
Exemplo n.º 5
0
        internal void Run()
        {
            // Create pipe instance
            using (var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4))
            {
                Console.WriteLine("[SJPS] Thread created");
                // wait for connection
                Console.WriteLine("[SJPS] Waiting for connection");
                pipeServer.WaitForConnection();
                Console.WriteLine("[SJPS] Client has connected");
                IsRunning = true;
                pipeServer.ReadTimeout = 1000;

                // Stream for the request.
                var sr = new StreamReader(pipeServer);
                // Stream for the response.
                var sw = new StreamWriter(pipeServer) {AutoFlush = true};

                while (IsRunning)
                {
                    try
                    {
                        // Read request from the stream.
                        var echo = sr.ReadLine();
                        Console.WriteLine("[SJPS] Recieved request: " + echo);

                        if (echo == "Close")
                        {
                            IsRunning = false;
                            break;
                        }

                        try
                        {
                            ParseRequest(echo);
                            sw.WriteLine("Ack");
                        }
                        catch (Exception)
                        {
                            sw.WriteLine("Error");
                        }
                    }
                    catch (IOException e)
                    {
                        Console.WriteLine("[SJPS] Error: {0}", e.Message);
                        IsRunning = false;
                    }
                }

                pipeServer.Disconnect();
                pipeServer.Close();
            }
        }
        /// <summary>
        /// Connect from core to the service - used in core to listen for commands from the service
        /// </summary>
        public static void ConnectToService()
        {
            if (connected) return; //only one connection...

            Async.Queue("MBService Connection", () =>
            {
                using (NamedPipeServerStream pipe = new NamedPipeServerStream(MBSERVICE_OUT_PIPE,PipeDirection.In))
                {
                    connected = true;
                    bool process = true;
                    while (process)
                    {
                        pipe.WaitForConnection(); //wait for the service to tell us something
                        try
                        {
                            // Read the request from the service.
                            StreamReader sr = new StreamReader(pipe);

                            string command = sr.ReadLine();
                            switch (command.ToLower())
                            {
                                case IPCCommands.ReloadItems:
                                    //refresh just finished, we need to re-load everything
                                    Logger.ReportInfo("Re-loading due to request from service.");
                                    Application.CurrentInstance.ReLoad();
                                    break;
                                case IPCCommands.Shutdown:
                                    //close MB
                                    Logger.ReportInfo("Shutting down due to request from service.");
                                    Application.CurrentInstance.Close();
                                    break;
                                case IPCCommands.CloseConnection:
                                    //exit this connection
                                    Logger.ReportInfo("Service requested we stop listening.");
                                    process = false;
                                    break;

                            }
                            pipe.Disconnect();
                        }
                        catch (IOException e)
                        {
                            Logger.ReportException("Error in MBService connection", e);
                        }
                    }
                    pipe.Close();
                    connected = false;
                }
            });
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            Console.Title = "Log - Trinix";

            if (!Directory.Exists("Logs"))
                Directory.CreateDirectory("Logs");

            Parser parser = null;
            while (true)
            {
                NamedPipeServerStream pipeServer = new NamedPipeServerStream("trinix");
                pipeServer.WaitForConnection();

                if (parser != null)
                    parser.Dispose();

              //  MemoryStream ms = new MemoryStream();
                //parser = new Parser();
               // parser.Parse(ms);
                StreamWriter log = new StreamWriter("Logs\\" + String.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now) + ".log");

                try
                {
                    while (pipeServer.IsConnected)
                    {
                        int v = pipeServer.ReadByte();

                        if (v == -1)
                            break;

                       // ms.WriteByte((byte)v);
                        Console.Write((char)v);
                        log.Write((char)v);
                    }

                    pipeServer.Close();
                    log.Close();
                }
                catch
                {
                }

                Console.Write(Environment.NewLine);
                Console.WriteLine("----------- Connection ended -----------");
                Console.Write(Environment.NewLine);
            }
        }
Exemplo n.º 8
0
    // Use this for initialization
    void Start()
    {
        Debug.Log("Starting Server");
        server = new NamedPipeServerStream("NPtest");

        //Console.WriteLine("Waiting for connection...");
        Debug.Log("Waiting for connection...");
        server.WaitForConnection();

        //Console.WriteLine("Connected.");
        Debug.Log("Connected.");

        br = new BinaryReader(server);
        bw = new BinaryWriter(server);

        while (true)
        {
            try
            {
                var len = (int)br.ReadUInt32();            // Read string length
                var str = new string(br.ReadChars(len));    // Read string

                //Console.WriteLine("Read: \"{0}\"", str);
                Debug.Log(String.Format("Read: {0}", str));
                str = new string(str.Reverse().ToArray());  // Just for fun

                var buf = Encoding.ASCII.GetBytes(str);     // Get ASCII byte array     
                bw.Write((uint)buf.Length);                // Write string length
                bw.Write(buf);                              // Write string
                //Console.WriteLine("Wrote: \"{0}\"", str);
                Debug.Log(String.Format("Wrote: {0}", str));
            }
            catch (EndOfStreamException)
            {
                break;                    // When client disconnects
            }
        }

        //Console.WriteLine("Client disconnected.");
        Debug.Log("Client disconnected.");
        server.Close();
        server.Dispose();


    }
Exemplo n.º 9
0
 public void ThreadStartServer()
 {
     //FileStream fs = new FileStream("c:\\1\\server.txt", FileMode.Create,FileAccess.ReadWrite);            
   //  StreamWriter sw = new StreamWriter(fs);
  //   sw.AutoFlush = true;
     
     while (true)
     {
         NamedPipeServerStream pipeStream = new NamedPipeServerStream(pipeName,PipeDirection.InOut,1);
         //sw.WriteLine("NamedPipeServerStream pipeStream = new NamedPipeServerStream(mytestpipe,PipeDirection.InOut,1);");
         while (true)
         {
             if (G.mainWindow != null) break;
         }                
         pipeStream.WaitForConnection();                
         //sw.WriteLine("pipeStream.WaitForConnection();");
         StreamReader sr = new StreamReader(pipeStream);
         //sw.WriteLine("StreamReader sr = new StreamReader(pipeStream);");
         string temp = sr.ReadLine();
        // sw.WriteLine("string temp = sr.ReadLine();");                
        // sw.WriteLine(temp);
        // sw.WriteLine("//sw.WriteLine(temp);");
         if (temp!=null)
         if (temp.Length!=0)
         {
          //   sw.WriteLine("if (temp != null || temp.Length!=0)");
             G.mainWindow.Dispatcher.Invoke(
                 new Action(
                     delegate()
                     {
                         //if (G.mainWindow == null) MessageBox.Show("Хуй тебе!");
                             G.mainWindow.OpenFile(temp); 
                         }
                         ));
          //   sw.WriteLine("G.mainWindow.Dispatcher.Invoke(new Action(delegate() { G.mainWindow.OpenFile(temp); }));");
         }
         //pipeStream.WaitForPipeDrain();
         pipeStream.Close();
         //sw.WriteLine("pipeStream.Close();");
         pipeStream = null;
         sr.Close();// sr = null;
     //    sw.WriteLine("sr.Close();");
         //sw.Close();
     }   //while
 }
Exemplo n.º 10
0
        static void Main()
        {
            string echo = "";
            while (true)
            {
                //Create pipe instance
                NamedPipeServerStream pipeServer =
                new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4);
                Console.WriteLine("[ECHO DAEMON] NamedPipeServerStream thread created.");

                //wait for connection
                Console.WriteLine("[ECHO DAEMON] Wait for a client to connect");
                pipeServer.WaitForConnection();

                Console.WriteLine("[ECHO DAEMON] Client connected.");
                try
                {
                    // Stream for the request.
                    StreamReader sr = new StreamReader(pipeServer);
                    // Stream for the response.
                    StreamWriter sw = new StreamWriter(pipeServer);
                    sw.AutoFlush = true;

                    // Read request from the stream.
                     echo = sr.ReadLine();

                    Console.WriteLine("[ECHO DAEMON] Request message: " + echo);

                    // Write response to the stream.
                    sw.WriteLine("[ECHO]: " + echo);

                    pipeServer.Disconnect();
                }
                catch (IOException e)
                {
                    Console.WriteLine("[ECHO DAEMON]ERROR: {0}", e.Message);
                }

                System.IO.File.WriteAllText(@"C:\Users\tlewis\Desktop\WriteLines.txt", echo);

                pipeServer.Close();
            }
        }
Exemplo n.º 11
0
            public async Task NoServerConnection()
            {
                using (var readyMre = new ManualResetEvent(initialState: false))
                using (var doneMre = new ManualResetEvent(initialState: false))
                {
                    var pipeName = Guid.NewGuid().ToString();
                    var mutexName = BuildServerConnection.GetServerMutexName(pipeName);
                    bool created = false;
                    bool connected = false;

                    var thread = new Thread(() =>
                    {
                        using (var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out created))
                        using (var stream = new NamedPipeServerStream(pipeName))
                        {
                            readyMre.Set();

                            // Get a client connection and then immediately close it.  Don't give any response.
                            stream.WaitForConnection();
                            connected = true;
                            stream.Close();

                            doneMre.WaitOne();
                            mutex.ReleaseMutex();
                        }
                    });

                    // Block until the mutex and named pipe is setup.
                    thread.Start();
                    readyMre.WaitOne();

                    var exitCode = await RunShutdownAsync(pipeName, waitForProcess: false);

                    // Let the fake server exit.
                    doneMre.Set();
                    thread.Join();

                    Assert.Equal(CommonCompiler.Failed, exitCode);
                    Assert.True(connected);
                    Assert.True(created);
                }
            }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            // Open the named pipe.
            var server = new NamedPipeServerStream("NPtest");

            Console.WriteLine("Waiting for connection...");
            server.WaitForConnection();

            Console.WriteLine("Connected.");
            var br = new BinaryReader(server);
            var bw = new BinaryWriter(server);

            while (true)
            {
                try
                {
                    var len = (int)br.ReadUInt32();            // Read string length
                    var str = new string(br.ReadChars(len));    // Read string

                    Console.WriteLine("Read: \"{0}\"", str);

                    str = new string(str.Reverse().ToArray());  // Just for fun

                    var buf = Encoding.ASCII.GetBytes(str);     // Get ASCII byte array     
                    bw.Write((uint)buf.Length);                // Write string length
                    bw.Write(buf);                              // Write string
                    Console.WriteLine("Wrote: \"{0}\"", str);
                }
                catch (EndOfStreamException)
                {
                    break;                    // When client disconnects
                }
            }

            Console.WriteLine("Client disconnected.");
            server.Close();
            server.Dispose();



        }
Exemplo n.º 13
0
        private void button1_Click(object sender, EventArgs e)
        {
            var  server = new NamedPipeServerStream("NPtest1");
               Console.WriteLine("Waiting for connection...");
               server.WaitForConnection();
               Console.WriteLine("Connected.");
               var br = new BinaryReader(server);
               var bw = new BinaryWriter(server);
               string UN = username2.Text;
               string PW = password2.Text;
               string EM = email.Text;
               string FD = folderdir.Text;
               string[] send = new string[5];
               send[0]="register";
               send[1]=UN;
               send[2]=PW;
               send[3]=EM;
               send[4]=FD;
               for(int i=0; i<send.Length;i++)

                try
                {

                     var str = new string(send[i].ToArray());  // Just for fun

                    var buf = Encoding.ASCII.GetBytes(str);     // Get ASCII byte array
                    bw.Write((uint)buf.Length);                // Write string length
                    bw.Write(buf);                              // Write string
                    Console.WriteLine("Wrote: \"{0}\"", str);
                }
                catch (EndOfStreamException)
                {
                    Console.WriteLine("Client disconnected.");
                    server.Close();
                    server.Dispose();   // When client disconnects
                }

                     var len2 = (int)br.ReadUInt32();            // Read string length
                     var str2 = new string(br.ReadChars(len2));    // Read string
                     MessageBox.Show(str2);
        }
Exemplo n.º 14
0
    private static void ServerThread(object data)
    {
        NamedPipeServerStream pipeServer =
            new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);

        int threadId = Thread.CurrentThread.ManagedThreadId;

        // Wait for a client to connect
        pipeServer.WaitForConnection();

        Console.WriteLine("Client connected on thread[{0}].", threadId);
        //try
        //{
        //    // Read the request from the client. Once the client has
        //    // written to the pipe its security token will be available.

        //    StreamString ss = new StreamString(pipeServer);

        //    // Verify our identity to the connected client using a
        //    // string that the client anticipates.

        //    ss.WriteString("I am the one true server!");
        //    string filename = ss.ReadString();

        //    // Read in the contents of the file while impersonating the client.
        //    ReadFileToStream fileReader = new ReadFileToStream(ss, filename);

        //    // Display the name of the user we are impersonating.
        //    Console.WriteLine("Reading file: {0} on thread[{1}] as user: {2}.",
        //        filename, threadId, pipeServer.GetImpersonationUserName());
        //    pipeServer.RunAsClient(fileReader.Start);
        //}
        //// Catch the IOException that is raised if the pipe is broken
        //// or disconnected.
        //catch (IOException e)
        //{
        //    Console.WriteLine("ERROR: {0}", e.Message);
        //}
        pipeServer.Close();
    }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            while (true)
            {
                //Create pipe instance
                NamedPipeServerStream pipeServer =
                new NamedPipeServerStream("mojotestpipe", PipeDirection.InOut, 4);
                Console.WriteLine(String.Format("[DOTNET] {0} NamedPipeServerStream thread created.", DateTime.Now.ToString("T")));

                //wait for connection
                Console.WriteLine(String.Format("[DOTNET] {0} Wait for a client to connect...", DateTime.Now.ToString("T")));
                pipeServer.WaitForConnection();

                Console.WriteLine(String.Format("[DOTNET] {0} Client connected.", DateTime.Now.ToString("T")));
                try
                {
                    // Stream for the request.
                    StreamReader sr = new StreamReader(pipeServer);
                    // Stream for the response.
                    StreamWriter sw = new StreamWriter(pipeServer);
                    sw.AutoFlush = true;

                    // Read request from the stream.
                    string echo = sr.ReadLine();

                    Console.WriteLine(String.Format("[DOTNET] {0} Request message: {1}", DateTime.Now.ToString("T"), echo));

                    // Write response to the stream.
                    sw.WriteLine("[ECHO]: " + echo);

                    pipeServer.Disconnect();
                }
                catch (IOException e)
                {
                    Console.WriteLine(String.Format("[DOTNET] {0} Error: {1}", DateTime.Now.ToString("T"), e.Message));
                }
                pipeServer.Close();
            }
        }
Exemplo n.º 16
0
        void pipeServerThread(object o)
        {
            NamedPipeServerStream pipeServer = null;
            try
            {
                while (true)
                {
                    pipeServer = new NamedPipeServerStream(
                        this.ServerName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                    IAsyncResult async = pipeServer.BeginWaitForConnection(null, null);
                    int index = WaitHandle.WaitAny(new WaitHandle[] { async.AsyncWaitHandle, closeApplicationEvent });
                    switch (index)
                    {
                        case 0:
                            pipeServer.EndWaitForConnection(async);
                            using (StreamReader sr = new StreamReader(pipeServer))
                            using (StreamWriter sw = new StreamWriter(pipeServer))
                            {
                                this.Recived(this, new ServerReciveEventArgs(sr, sw));
                            }
                            if (pipeServer.IsConnected)
                            {
                                pipeServer.Disconnect();
                            }
                            break;
                        case 1:
                            return;
                    }
                }
            }
            finally
            {
                if (pipeServer != null)
                {
                    pipeServer.Close();
                }
            }
        }
Exemplo n.º 17
0
    private static void ServerThread(object data)
    {
        NamedPipeServerStream pipeServer =
            new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);
        int threadId = Thread.CurrentThread.ManagedThreadId;

        //wait for client to connect
        pipeServer.WaitForConnection();

        Console.WriteLine("Client connected on thread[{0}].", threadId);
        try
        {
            //Read the request from the client. Once the client has
            //written to the pipe its security token will be available.
            //We might not need this security token ? 
            //We need interprocess communication on the same computer
            StreamString ss = new StreamString(pipeServer);

            //Verify our identity to the connected client using a 
            //string that the client anticipates

            ss.WriteString("I am the one true server!");
            string filename = ss.ReadString();

            //Read in the contents of the file while impersonating the client.
            ReadFileToStream fileReader = new ReadFileToStream(ss, filename);

            //Display the name of the user we are impersonating. //Impersonating ? 
            Console.WriteLine("Reading file: {0} on thread{1} as user: {2}.",
                filename, threadId, pipeServer.GetImpersonationUserName()); //So impersonation is nothing but name of client at the other end ? Cool!
            pipeServer.RunAsClient(fileReader.Start);
        }
        catch(IOException e)
        {
            Console.WriteLine("ERROR: {0}", e.Message);
        }
        pipeServer.Close();
    }
Exemplo n.º 18
0
 static void Main(string[] args)
 {
     NamedPipeServerStream pipeServer = new NamedPipeServerStream("PipeConnection", PipeDirection.InOut, 4, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
     pipeServer.WaitForConnection();
     Console.WriteLine("Connected");
     Console.WriteLine("Enter data in format - %d,%d,%d ... (\"send\" to send data, \"end\" to stop input)");
     StreamString ss = new StreamString(pipeServer);
     string input = Console.ReadLine();
     while (!input.Equals("end"))
     {              
         while (!input.Equals("send"))
         {
             ss.WriteString(input + ',' + DateTime.Now.ToString());
             input = Console.ReadLine();
             //Thread.Sleep(1000);
         }
         Console.WriteLine("Data sent");
         ss.WriteString("send");
         input = Console.ReadLine();
     }
     
     ss.WriteString("end");
     pipeServer.Close();
 }
Exemplo n.º 19
0
        private static void ServerThread(object data)
        {
            var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);
            int threadId = Thread.CurrentThread.ManagedThreadId;

            pipeServer.WaitForConnection();

            Console.WriteLine("Client connected on thread[{0}].", threadId);
            try
            {
                StreamString ss = new StreamString(pipeServer);
                ss.WriteString("I am the one true server!");
                string filename = ss.ReadString();
                ReadFileToStream fileReader = new ReadFileToStream(ss, filename);
                Console.WriteLine("Reading file: {0} on thread[{1}] as user: {2}.",
                    filename, threadId, pipeServer.GetImpersonationUserName());
                pipeServer.RunAsClient(fileReader.Start);
            }
            catch (IOException e)
            {
                Console.WriteLine("ERROR: {0}", e.Message);
            }
            pipeServer.Close();
        }
Exemplo n.º 20
0
        private void StartPipeListen(object state)
        {
            try
            {
                serverPipe = new NamedPipeServerStream(_pipename, PipeDirection.In);
                Trace.WriteLine("Waiting for connection...");
                serverPipe.WaitForConnection();
                Trace.WriteLine("Connection established...");

                using (StreamReader sr = new StreamReader(serverPipe))
                {
                    while (!_pipeStopper)
                    {
                        string content = sr.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            // Json des...
                            try
                            {
                                SharpBuildEventWrapper eventWrapper = Newtonsoft.Json.JsonConvert.DeserializeObject<SharpBuildEventWrapper>(content);

                                switch (eventWrapper.EventType)
                                {
                                    case SharpBuildEventType.Start:
                                        {
                                            SharpBuildStartEvent log = Newtonsoft.Json.JsonConvert.DeserializeObject<SharpBuildStartEvent>(eventWrapper.EmbeddedMessage);
                                            string msg = string.Format("*-------- Build Started: {0} --------*\r\n", log.GeneratedTime.ToLongTimeString());

                                            BuildWindow.OutputStringThreadSafe(msg);

                                            // report error...
                                            if (OnBuildStart != null)
                                                OnBuildStart(this, log);
                                        }
                                        break;
                                    case SharpBuildEventType.ErrorLog:
                                        {
                                            SharpBuildErrorEvent log = Newtonsoft.Json.JsonConvert.DeserializeObject<SharpBuildErrorEvent>(eventWrapper.EmbeddedMessage);
                                            string msg = string.Format("{0}({1},{2}): error {3}: {4}\r\n", log.File, log.LineNumber, log.ColumnNumber, log.Code, log.Message);
                                            BuildWindow.OutputStringThreadSafe(msg);

                                            // report error...
                                            if (OnBuildError != null)
                                                OnBuildError(this, log);
                                        }
                                        break;
                                    case SharpBuildEventType.WarningLog:
                                        {
                                            SharpBuildWarningEvent log = Newtonsoft.Json.JsonConvert.DeserializeObject<SharpBuildWarningEvent>(eventWrapper.EmbeddedMessage);
                                            string msg = string.Format("{0}({1},{2}): warning {3}: {4}", log.File, log.LineNumber, log.ColumnNumber, log.Code, log.Message);
                                            BuildWindow.OutputStringThreadSafe(msg + "\r\n");

                                            // report error...
                                            if (OnBuildWarning != null)
                                                OnBuildWarning(this, log);
                                        }
                                        break;
                                    case SharpBuildEventType.Log:
                                        {
                                            SharpBuildLogEvent log = Newtonsoft.Json.JsonConvert.DeserializeObject<SharpBuildLogEvent>(eventWrapper.EmbeddedMessage);
                                            BuildWindow.OutputStringThreadSafe(log.Message + "\r\n");
                                        }
                                        break;

                                    case SharpBuildEventType.InternalError:
                                        {
                                            SharpBuildInternalErrorEvent error = Newtonsoft.Json.JsonConvert.DeserializeObject<SharpBuildInternalErrorEvent>(eventWrapper.EmbeddedMessage);
                                            BuildWindow.OutputStringThreadSafe(error.Message + "\r\n");
                                            if (OnBuildInternalError != null)
                                                OnBuildInternalError(this, error);
                                        }
                                        break;

                                    case SharpBuildEventType.Finished:
                                        {
                                            SharpBuildFinishedEvent finishedevnt = Newtonsoft.Json.JsonConvert.DeserializeObject<SharpBuildFinishedEvent>(eventWrapper.EmbeddedMessage);
                                            string msg = string.Format("*-------- Build Finished: {0} {1}--------*\r\n", finishedevnt.Successed ? "Success" : "Falied", finishedevnt.GeneratedTime.ToLongTimeString());
                                            BuildWindow.OutputStringThreadSafe(msg);

                                            if (OnBuildFinished != null)
                                                OnBuildFinished(this, finishedevnt);
                                        }
                                        break;

                                    default:
                                        break;
                                }

                            }
                            catch (Exception ee)
                            {
                                BuildWindow.OutputStringThreadSafe(string.Format("Failed to get pipe events, general issues {0} \r\n ", ee.Message));
                            }
                        }
                        System.Threading.Thread.Sleep(200);
                    }
                }

                Debug.WriteLine("close pipe....");
                serverPipe.Close();
                _pipeStopper = false;
            }
            catch (Exception e)
            {
                BuildWindow.OutputString(@"Failed to setup msbuild due to:  " + e.Message);
            }
            finally
            {
            }
        }
Exemplo n.º 21
0
        public void ServerThread()
        {
            NamedPipeServerStream pipeServer = new NamedPipeServerStream("FTPbox Server", PipeDirection.InOut, 5);
            int threadID = Thread.CurrentThread.ManagedThreadId;

            pipeServer.WaitForConnection();

            Log.Write(l.Client, "Client connected, id: {0}", threadID);

            try
            {
                StreamString ss = new StreamString(pipeServer);

                ss.WriteString("ftpbox");
                string args = ss.ReadString();

                ReadMessageSent fReader = new ReadMessageSent(ss, "All done!");

                Log.Write(l.Client, "Reading file: \n {0} \non thread [{1}] as user {2}.", args, threadID, pipeServer.GetImpersonationUserName());

                List<string> li = new List<string>();
                li = ReadCombinedParameters(args);

                CheckClientArgs(li.ToArray());

                pipeServer.RunAsClient(fReader.Start);
            }
            catch (IOException e)
            {
                Common.LogError(e);
            }
            pipeServer.Close();
        }
        /// <summary>
        /// Listen from service for commands from core or configurator
        /// </summary>
        public static void StartListening()
        {
            if (connected) return; //only one connection...

            Async.Queue("MB Connection", () =>
            {
                System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);

                PipeSecurity pipeSa = new PipeSecurity();
                pipeSa.SetAccessRule(new PipeAccessRule(sid,
                       PipeAccessRights.ReadWrite, AccessControlType.Allow));

                using (NamedPipeServerStream pipe = new NamedPipeServerStream(MBServiceController.MBSERVICE_IN_PIPE, PipeDirection.In,1,PipeTransmissionMode.Message,PipeOptions.None,1024,1024,pipeSa))
                {
                    connected = true;
                    bool process = true;
                    while (process)
                    {
                        pipe.WaitForConnection(); //wait for the core to tell us something
                        try
                        {
                            // Read the request from the sender.
                            StreamReader sr = new StreamReader(pipe);

                            string command = sr.ReadLine();
                            switch (command.ToLower())
                            {
                                case IPCCommands.ReloadKernel: //don't use this yet - need to figure out how to unload first do a shutdown and restart
                                    //something changed, we need to re-load everything
                                    Logger.ReportInfo("Re-loading kernel due to request from client.");
                                    Kernel.Init(KernelLoadDirective.ShadowPlugins);
                                    break;
                                case IPCCommands.ReloadConfig:
                                    //re-load the main config file
                                    Kernel.Instance.ReLoadConfig();
                                    break;
                                case IPCCommands.Shutdown:
                                    //close Service
                                    Logger.ReportInfo("Shutting down due to request from client.");
                                    MainWindow.Instance.Shutdown();
                                    break;
                                case IPCCommands.Restart:
                                    //restart Service
                                    Logger.ReportInfo("Restarting due to request from client.");
                                    MainWindow.Instance.Restart();
                                    break;
                                case IPCCommands.CancelRefresh:
                                    //cancel any running refresh
                                    MainWindow.Instance.CancelRefresh();
                                    break;
                                case IPCCommands.ForceRebuild:
                                    //force a re-build of the library - used with new version that requires it
                                    Logger.ReportInfo("Forcing re-build of library due to request from client.");
                                    MainWindow.Instance.ForceRebuild();
                                    break;
                                case IPCCommands.Refresh:
                                    Logger.ReportInfo("Refreshing now due to request from client.");
                                    MainWindow.Instance.RefreshNow();
                                    break;
                                case IPCCommands.CloseConnection:
                                    //exit this connection
                                    Logger.ReportInfo("Client requested we stop listening.");
                                    process = false;
                                    break;

                            }
                            pipe.Disconnect();
                        }
                        catch (IOException e)
                        {
                            Logger.ReportException("Error in MB connection", e);
                        }
                    }
                    pipe.Close();
                    connected = false;
                }
            });
        }
Exemplo n.º 23
0
        private void ServerThreadRoutine(object data)
        {
            string defaultTimeOutValuestring = TimeOutValuestring;
            TvBusinessLayer layer = new TvBusinessLayer();
            Setting setting = null;

            while (PipeServerActive)
            {
                try
                {
                    var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,System.Security.AccessControl.AccessControlType.Allow);
                    var sec = new PipeSecurity();
                    sec.AddAccessRule(rule);

#if (MPTV2)
                    string pipeName = "MP2TvWishListPipe";
#else
                    string pipeName = "TvWishListPipe";
#endif

                    pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, sec);  //only 1 thread for pipe

                    int threadId = Thread.CurrentThread.ManagedThreadId;

                    // Wait for a client to connect
                    Logdebug("TvServer: Waiting for client to connect");
                    PipeServerBusy = false;

                    pipeServer.WaitForConnection();
                    ServerMessage = string.Empty;
                    Logdebug("Client connected on pipe server thread.");
                    PipeServerBusy = true; ;
                    // Read the request from the client. Once the client has
                    // written to the pipe its security token will be available.

                    //pipeServer.ReadTimeout = 5000; //timeout not supported for async streams

                    StreamString ss = new StreamString(pipeServer);

                    // Verify our identity to the connected client using a
                    // string that the client anticipates.


                    MessageFromClient = ss.ReadString();            //receive message from client first
                    //labelreceivedTextServer.Text = messagefromclient;
                    Logdebug("***** CLIENTMESSAGE=" + MessageFromClient);

                    //*******************************
                    //commandinterpretation 
                    //*******************************
                    if (MessageFromClient == PipeCommands.RequestTvVersion.ToString())
                    {
                        string response = PipeCommands.RequestTvVersion.ToString() + "=" + this.Version;
                        Logdebug("sending response " + response);
                        ss.WriteString(response);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.StartEpg.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;
                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }
                        Logdebug("Starting EPG Search from pipe command");
                        Thread StartEPGsearchThread = new Thread(StartEPGsearchCommand);
                        StartEPGsearchThread.Start();
                        

                        while ((ServerMessage.StartsWith(PipeCommands.Ready.ToString())==false) && (ServerMessage.StartsWith(PipeCommands.Error.ToString()) == false))
                        {
                            ServerTimeOutCounter = new Thread(ServerTimeOutError);
                            ServerTimeOutCounter.Start();
                            while ((NewServerMessage == false) || (ServerMessage==string.Empty))
                            {
                                Thread.Sleep(500);
                                Logdebug("waiting for new servermessage (ServerMessage="+ServerMessage);
                            }
                            Logdebug("Sending Servermessage=" + ServerMessage);
                            ss.WriteString(ServerMessage);                   //send response messages until done
                            ServerTimeOutCounter.Abort();
                            NewServerMessage = false;
                        }
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.Error_TimeOut.ToString()) == true)
                    {
                        TimeOutValuestring = MessageFromClient.Replace(PipeCommands.Error_TimeOut.ToString(), string.Empty);
                        Logdebug("new TimeOutValuestring="+TimeOutValuestring);
                        ss.WriteString(TimeOutValuestring);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ExportTvWishes.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Log.Debug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        if (MessageFromClient.Contains("VIEWONLY=TRUE") == true)
                        {
                            ServerMessage = ExportTvWishes(true);
                        }
                        else //Email & Record Mode
                        {
                            ServerMessage = ExportTvWishes(false);
                        }

                        ss.WriteString(ServerMessage);

                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ImportTvWishes.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        if (MessageFromClient.Contains("VIEWONLY=TRUE") == true)
                        {
                            ServerMessage = ImportTvWishes(true);
                        }
                        else //Email & Record Mode
                        {
                            ServerMessage = ImportTvWishes(false);
                        }

                        ss.WriteString(ServerMessage);

                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveSetting.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        string tag = tokens[0].Replace(PipeCommands.RemoveSetting.ToString(), string.Empty);

                        
                        setting = layer.GetSetting(tag, string.Empty);
                        if (setting != null)
                        {
                            setting.Remove();
                            ServerMessage = "Setting " + tag + " removed";
                            Logdebug("Setting " + tag + " removed");
                        }
                        else
                        {
                            ServerMessage = "Setting " + tag + " could not be removed";
                            Logdebug("Eror: Setting " + tag + " could not be removed");
                 
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveRecording.ToString()) == true)
                    {//string command = Main_GUI.PipeCommands.RemoveRecording.ToString() + this.IdRecording.ToString() + ":10";
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        string idRecordingString = tokens[0].Replace(PipeCommands.RemoveRecording.ToString(), string.Empty);
                        try
                        {
                            int idRecording = -1;
                            int.TryParse(idRecordingString, out idRecording);
                            Logdebug("idRecording=" + idRecording.ToString());
                            Recording myrecording = Recording.Retrieve(idRecording);
                            Logdebug("idRecording=" + myrecording.Title.ToString());
                            myrecording.Delete();
                            Logdebug("Recording deleted");
                            ServerMessage = "Recording deleted"; 
                        }
                        catch (Exception exc)
                        {
                            Logdebug("no recording found for idRecordingString = " + idRecordingString);
                            Logdebug("exception is " + exc.Message);
                            ServerMessage = "Error: Recording could not be deleted check the tvserver log file"; 
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveLongSetting.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        //processing
                        string mysetting = string.Empty;
                        try
                        {
                            //cleanup work
                            mysetting = tokens[0].Replace(PipeCommands.RemoveLongSetting.ToString(), string.Empty);
                            Log.Debug("mysetting=" + mysetting);
                            for (int i = 1; i < 1000; i++)
                            {
                                setting = layer.GetSetting(mysetting + "_" + i.ToString("D3"), "_DOES_NOT_EXIST_");
                                Log.Debug("save_longsetting setting=" + setting.Value);
                                if (setting.Value == "_DOES_NOT_EXIST_")
                                {
                                    setting.Remove();
                                    break;
                                }
                                else
                                {
                                    string value = setting.Value;
                                    setting.Remove();

                                }
                            }
                            ServerMessage = "Long setting could be removed";
                        }
                        catch (Exception exc)
                        {
                            Logdebug("Longsetting could not be removed for mysetting= " + mysetting);
                            Logdebug("exception is " + exc.Message);
                            ServerMessage = "Error: Long setting could not be removed - check the tvserver log file";
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
#if (MPTV2)
                    else if (MessageFromClient.StartsWith(PipeCommands.WriteSetting.ToString()) == true)
                    {
                        string tag = MessageFromClient.Replace(PipeCommands.WriteSetting.ToString(), string.Empty);
                        string[] tags = tag.Split('\n');
                        ServiceAgents.Instance.SettingServiceAgent.SaveValue(tags[0], tags[1]);

                        ServerMessage = "SUCCESS";
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadSetting.ToString()) == true)
                    {
                        string tag = MessageFromClient.Replace(PipeCommands.ReadSetting.ToString(), string.Empty);
                        Log.Debug("tag="+tag);
                        string value = ServiceAgents.Instance.SettingServiceAgent.GetValue(tag, string.Empty);
                        Log.Debug("value=" + value);
                        ServerMessage = value;
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllCards.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        ServerMessage = string.Empty;
                        foreach (Card mycard in Card.ListAll())
                        {
                            ServerMessage += mycard.IdCard.ToString() + "\n" + mycard.Name + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }                  
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelsByGroup.ToString()) == true)
                    {
                        string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllChannelsByGroup.ToString(), string.Empty);
                        Log.Debug("groupIdString="+groupIdString);
                        int groupId = -1;
                        int.TryParse(groupIdString, out groupId);
                        Log.Debug("groupId=" + groupId.ToString());

                        ServerMessage = string.Empty;
                        foreach (Channel mychannel in Channel.ListAllByGroup(groupId))
                        {
                            ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n";
                        }
                        Log.Debug("Groupchannels=" + ServerMessage);
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannels.ToString()) == true)//must be after ReadAllChannelsByGroup
                    {
                        ServerMessage = string.Empty;
                        foreach (Channel mychannel in Channel.ListAll())
                        {
                            ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelsByGroup.ToString()) == true)
                    {
                        string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllRadioChannelsByGroup.ToString(), string.Empty);
                        Log.Debug("radiogroupIdString=" + groupIdString);
                        int groupId = -1;
                        int.TryParse(groupIdString, out groupId);
                        Log.Debug("radiogroupId=" + groupId.ToString());

                        ServerMessage = string.Empty;
                        foreach (RadioChannel myradiochannel in RadioChannel.ListAllByGroup(groupId))
                        {
                            ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n";
                        }
                        Log.Debug("radioGroupchannels=" + ServerMessage);
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannels.ToString()) == true)//must be after ReadAllRadioChannelsByGroup
                    {
                        ServerMessage = string.Empty;
                        foreach (RadioChannel myradiochannel in RadioChannel.ListAll())
                        {
                            ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelGroups.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (ChannelGroup mygroup in ChannelGroup.ListAll())
                        {
                            ServerMessage += mygroup.Id.ToString() + "\n" + mygroup.GroupName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelGroups.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (RadioChannelGroup myradiogroup in RadioChannelGroup.ListAll())
                        {
                            ServerMessage += myradiogroup.Id.ToString() + "\n" + myradiogroup.GroupName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRecordings.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (Recording myrecording in Recording.ListAll())
                        {
                            ServerMessage += myrecording.IdRecording.ToString() + "\n" + myrecording.Title + "\n"+myrecording.FileName + "\n" +
                                             myrecording.IdChannel.ToString() + "\n" + myrecording.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) +
                                             "\n" + myrecording.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllSchedules.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (Schedule myschedule in Schedule.ListAll())
                        {
                            ServerMessage += myschedule.IdSchedule.ToString() + "\n" + myschedule.ProgramName + "\n" + 
                                             myschedule.IdChannel.ToString() + "\n" + myschedule.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) +
                                             "\n" + myschedule.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" +
                                             myschedule.ScheduleType.ToString() + "\n" + myschedule.PreRecordInterval.ToString() + "\n" +
                                             myschedule.PostRecordInterval.ToString() + "\n" + myschedule.MaxAirings.ToString() + "\n" +
                                             myschedule.KeepDate.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" +
                                             myschedule.KeepMethod.ToString() + "\n" + myschedule.Priority.ToString() + "\n" +
                                             myschedule.PreRecordInterval.ToString() + "\n" + myschedule.Series.ToString() + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ScheduleDelete.ToString()) == true)
                    {
                        string scheduleIdString = MessageFromClient.Replace(PipeCommands.ScheduleDelete.ToString(), string.Empty);
                        Log.Debug("scheduleIdString=" + scheduleIdString);
                        int scheduleId = -1;
                        int.TryParse(scheduleIdString, out scheduleId);
                        Log.Debug("scheduleId=" + scheduleId.ToString());
                        Schedule.Delete(scheduleId);
                        
                        //65000 max chars                        
                        ss.WriteString("Deleted");
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ScheduleNew.ToString()) == true)
                    {
                        string schedule = MessageFromClient.Replace(PipeCommands.ScheduleNew.ToString(), string.Empty);
                        string[] scheduletags = schedule.Split('\n');

                        int idChannel = -1;
                        int.TryParse(scheduletags[1], out idChannel);
                        DateTime start = DateTime.ParseExact(scheduletags[2], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture);
                        DateTime end = DateTime.ParseExact(scheduletags[3], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture);

                        Schedule myschedule = new Schedule(idChannel, scheduletags[0], start, end);
                        myschedule.Persist();
                        

                        ServerMessage = "SUCCESS";
                        ss.WriteString(ServerMessage);
                    }

#endif

                    else //Unknown command
                    {
                        Logdebug("sending response " + PipeCommands.UnknownCommand.ToString());
                        ss.WriteString(PipeCommands.UnknownCommand.ToString());
                    }
                    
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Log.Error("ServerThread ERROR: " + e.Message);
                }
                catch (Exception e)
                {
                    Log.Error("ServerThread ERROR: " + e.Message);
                }

                if (pipeServer != null)
                {
                    if (pipeServer.IsConnected)
                        pipeServer.Disconnect();

                    pipeServer.Close();
                    pipeServer.Dispose();
                    pipeServer = null;
                }
                Logdebug("Connection closed");

            }

            Logdebug("Pipe Server Thread Completed");
        }
Exemplo n.º 24
0
        public static bool StartListening()
        {
            if (connected) return false; //only one connection...
            if (Application.RunningOnExtender)
            {
                Logger.ReportInfo("Running on an extender.  Not starting client listener.");
                return true; //no comms for extenders
            }

            NamedPipeServerStream pipe;
            try
            {
                pipe = new NamedPipeServerStream(Kernel.MBCLIENT_MUTEX_ID);
            }
            catch (IOException)
            {
                Logger.ReportInfo("Client listener already going - activating that instance of MB...");
                //already started - must be another instance of MB Core - tell it to come to front
                string entryPoint = EntryPointResolver.EntryPointPath;
                if (string.IsNullOrEmpty(entryPoint))
                {
                    SendCommandToCore("activate");
                }
                else //nav to the proper entrypoint
                {
                    Logger.ReportInfo("Navigating current instance to entrypoint " + entryPoint);
                    SendCommandToCore("activateentrypoint," + entryPoint);
                }
                //and exit
                return false;
            }

            connected = true;

            Async.Queue("MBClient Listener", () =>
            {

                bool process = true;
                while (process)
                {
                    pipe.WaitForConnection(); //wait for someone to tell us something
                    string[] commandAndArgs;
                    try
                    {
                        // Read the request from the client.
                        StreamReader sr = new StreamReader(pipe);

                        commandAndArgs = sr.ReadLine().Split(',');
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Error during IPC communication.  Attempting to re-start listener", e);
                        try
                        {
                            //be sure we're cleaned up
                            pipe.Disconnect();
                            pipe.Close();
                        }
                        catch
                        { //we don't care if these fail now - and they very well may
                        }
                        finally
                        {
                            connected = false;
                        }
                        StartListening();
                        return;
                    }
                    try
                    {
                        string command = commandAndArgs[0];
                        switch (command.ToLower())
                        {
                            case "play":
                                //request to play something - our argument will be the GUID of the item to play
                                Guid id = new Guid(commandAndArgs[1]);
                                Logger.ReportInfo("Playing ...");
                                //to be implemented...
                                break;
                            case "activateentrypoint":
                                //re-load ourselves and nav to the entrypoint
                                Kernel.Instance.ReLoadRoot();
                                Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ =>
                                {
                                    MediaBrowser.Application.CurrentInstance.LaunchEntryPoint(commandAndArgs[1]);
                                });
                                //and tell MC to navigate to us
                                Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.ReturnToApplication();
                                break;
                            case "activate":
                                Logger.ReportInfo("Asked to activate by another process..");
                                //if we were in an entrypoint and we just got told to activate - we need to re-load and go to real root
                                if (Application.CurrentInstance.IsInEntryPoint)
                                {
                                    Kernel.Instance.ReLoadRoot();
                                    Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ =>
                                    {
                                        MediaBrowser.Application.CurrentInstance.LaunchEntryPoint(""); //this will start at root
                                    });
                                }
                                else
                                {
                                    //just need to back up to the root
                                    Application.CurrentInstance.BackToRoot();
                                }

                                // set npv visibility according to current state
                                Application.CurrentInstance.ShowNowPlaying = Application.CurrentInstance.IsPlaying || Application.CurrentInstance.IsExternalWmcApplicationPlaying;

                                //tell MC to navigate to us
                                Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.ReturnToApplication();
                                break;
                            case "shutdown":
                                //close MB
                                Logger.ReportInfo("Shutting down due to request from a client (possibly new instance of MB).");
                                Application.CurrentInstance.Close();
                                break;
                            case "closeconnection":
                                //exit this connection
                                Logger.ReportInfo("Service requested we stop listening.");
                                process = false;
                                break;

                        }
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Error trying to process IPC command", e);
                    }
                    try
                    {
                        pipe.Disconnect();
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Unexpected Error trying to close IPC connection", e);
                    }
                }
                pipe.Close();
                connected = false;
            });
            return true;
        }
Exemplo n.º 25
0
        /*************************** MAIN ******************************/

        static void Main(string[] args)
        {


            Tree alberonostro;

            try
            {


                if (args.Length == 0)
                {
                    Console.WriteLine("- ENGINE modalità manuale attivata -" + Environment.NewLine);

                    Console.WriteLine("Inserire nome Database: ");
                    string DB = Console.ReadLine();

                    //Settaggio connessione a database  
                    SqlConnection myconn = new SqlConnection(string.Format("Persist Security Info=False;Integrated Security=true;Initial Catalog={0};server=(local)", DB)); 

                    SqlCommand cmd = null; //comando di select 
                    SqlDataReader myReader = null;  

                    //Tentativo di connessione al database
                    myconn.Open();
                    //connessione stabilita 

                    //numero alberi in DB 
                    int numeroAlberi = 0; 

                    cmd = new SqlCommand("SELECT Nome FROM Albero", myconn); //COMANDO SQL 

                    //settaggio un datareader sul comando appena eseguito             
                    myReader = cmd.ExecuteReader();

                    //Lettura dati dal database 
                    while (myReader.Read())  
                    {
                        numeroAlberi++; 
                    }
 
                    // Chiusura DataReader		
                    myReader.Close();

                    
                    //stampa alberi in DB 
                    cmd = new SqlCommand("SELECT Nome FROM Albero", myconn); //COMANDO SQL 

                    //settaggio datareader sul comando appena eseguito             
                    myReader = cmd.ExecuteReader();

                    int[] index = new int[numeroAlberi];
                    string[] trees = new string[numeroAlberi]; 
                     

                    int count = 0; 
                    //Lettura dati dal database 
                    while (myReader.Read()) 
                    {
                        index[count] = count;
                        trees[count] = myReader.GetString(0); 

                        Console.WriteLine((count++) + "-) " + myReader.GetString(0)); 
                    }

 
                    //Chiusura DataReader		
                    myReader.Close();


                    Console.WriteLine(Environment.NewLine + "Inserire index albero: ");
                    int scelta = int.Parse(Console.ReadLine());

                    string nalbero = trees[scelta]; 

                    Console.WriteLine("Albero '{0}' selezionato", nalbero);

                    int numVertex = 0; //contatore per il numero di vertici 

                    SqlConnection conn = new SqlConnection(string.Format("Persist Security Info=False;Integrated Security=true;Initial Catalog={0};server=(local)", DB)); 
                    string s = string.Format("SELECT * FROM Albero, Vertex WHERE Albero.Nome='{0}' AND Vertex.IdAlbero=Albero.Id ", nalbero);
                    conn.Open();
                    SqlCommand msc = new SqlCommand(s, conn);
                    SqlDataReader msdr = msc.ExecuteReader();

                    while (msdr.Read())
                    {
                        numVertex++; //contatore numero vertici 
                    }
                    msdr.Close();
                    conn.Close();


                    Console.WriteLine(Environment.NewLine + "Inserire START Vertex: " + Environment.NewLine + "Default: 0");
                    int start = Int32.Parse(Console.ReadLine());
                    Console.WriteLine("Inserire END Vertex: " + Environment.NewLine + "Default END: {0}", (numVertex-1));
                    int end = Int32.Parse(Console.ReadLine());

                    //Controllo RANGE

                    if(!(start >= 0 && start< end && start < numVertex))
                    {
                        //Range startVertex sbagliato! 
                        Console.WriteLine("Sono stati inseriti parametri non corretti");
                        System.Threading.Thread.Sleep(5000);
                        return; 
                    }

                    if (!(end > 0 && end > start && end < numVertex))
                    {
                        //Range endVertex sbagliato! 
                        Console.WriteLine("Sono stati inseriti parametri non corretti");
                        System.Threading.Thread.Sleep(5000);
                        return; 
                    }

                    //Verifica andata a buon fine, dati OK

                    Console.WriteLine(Environment.NewLine + "Parametri Inseriti dall'utente: " + Environment.NewLine + "Database scelto: " + DB + Environment.NewLine + "Nome albero: " + nalbero + Environment.NewLine + "Vertice START: " + start + Environment.NewLine + "Vertice END: " + end);

                    //creazione istanza albero tramite riceviDB() 
                    alberonostro = riceviDB(nalbero, DB);


                    string nStart = alberonostro.albero[start].getNome();
                    string nEnd = alberonostro.albero[end].getNome();

                    long[] res = alberonostro.EsecuzioneCalcolo(nStart, nEnd);

                    long resVertex = res[1];
                    long resEdge = res[0];

                    Console.WriteLine(Environment.NewLine + "La somma sui Vertex è: {0}" + Environment.NewLine + "la somma sugli Edge è: {1}", resVertex, resEdge);

                    Console.WriteLine(Environment.NewLine + "Premere [INVIO] per uscire"); 
                    Console.ReadLine();
                    return;
                }

                if (!(args[0].Equals("GUI")))
                {
                    Console.WriteLine("ERRORE GENERALE: CHIAMATA ENGINE CON PARAMETRO NON ESATTO", args[0]);
                    System.Threading.Thread.Sleep(5000);
                    return;
                }

                if (args[0].Equals("GUI")) Console.WriteLine("RILEVATA CHIAMATA DA GUI. Modalità automatica attivata");
                //Se chiamato da GUI continuo altrimenti no


                alberonostro = new Tree();             //albero sul quale eseguire il calcolo


                //Creazione pipe che si aspetta dati dalla GUI
                NamedPipeServerStream Pipe1 = new NamedPipeServerStream("Pipe1");

                Console.WriteLine("Attendendo connessione con GUI...");
                //aspetto che la GUI si connetta alla pipe
                Pipe1.WaitForConnection();

                Console.WriteLine("Connessione con la GUI stabilita");

                //ricezione messaggio 
                messaggio ricevuto = new messaggio(); //Classe che conterrà Albero, vertice START e vertice END e il futuro risultato 
                var f = new System.Xml.Serialization.XmlSerializer(typeof(messaggio));
                ricevuto = (messaggio)f.Deserialize(Pipe1); 


                //chiusura pipe ricezione dalla GUI
                Pipe1.Close();


                alberonostro = ricevuto.Albero;

                string strv = alberonostro.albero[ricevuto.startVertex].getNome();
                string endv = alberonostro.albero[ricevuto.endVertex].getNome();

                //calcoli su Albero 

                long[] risultati = alberonostro.EsecuzioneCalcolo(strv, endv);
                //l'array risultati conterrà la somma su attr1Int e attr2Int, prendendo il relativo nome (con la funzione getNome()) dalla posizione nell'array di Vertex identificato dall'indice (startVertex o endVertex)

                string msg = string.Format("La somma sui Vertici è: {0}" + Environment.NewLine + "La somma sugli Edge è: {1}", risultati[1], risultati[0]); //risultato (Conteggio su Vertici, conteggio su Archi) da mandare


                //invio messaggio tramite pipe                
                NamedPipeClientStream Pipe2 = new NamedPipeClientStream("Pipe2"); //creazione pipe che invia dati alla GUI
                Thread.Sleep(1000);
                Pipe2.Connect();


                //creazione classe messaggio che conterrà il risultato da mandare 
                messaggio invio = new messaggio();
                invio.Risposta = msg;
                f.Serialize(Pipe2, invio); //invio dati alla GUI


                //chiusura pipe invio e uscita
                Pipe2.Close();

            }
            catch (Exception ex)
            {
                //Eccezioni

                if (args.Length == 0) //stampa eccezione a video
                {
                    Console.WriteLine("ERROR: " + ex.Message);
                    System.Threading.Thread.Sleep(5000);
                    return; 
                }

                //se Engine chiamato dalla GUI invia l'eccezione ad essa 
                var f = new System.Xml.Serialization.XmlSerializer(typeof(messaggio));


                string msg = "ERROR IN ENGINE: " + ex.Message;
                //invio messaggio errore tramite pipe  
                NamedPipeClientStream Pipe2 = new NamedPipeClientStream("Pipe2"); //creazione pipe che invia dati alla GUI
                Thread.Sleep(1000);
                Pipe2.Connect();


                //creazione casse messaggio che conterrà il risultato da mandare 
                messaggio invio = new messaggio();
                invio.Risposta = msg;
                f.Serialize(Pipe2, invio); //invio i dati alla GUI


                //chiusura pipe invio e uscita
                Pipe2.Close();


            }

        }
Exemplo n.º 26
0
        private void background_CommandServer_DoWork(object sender, DoWorkEventArgs e)
        {
            if (Thread.CurrentThread.Name == null)
                Thread.CurrentThread.Name = "CommandServer";

            NamedPipeServerStream pipeServer = null;
            try
            {
                pipeServer = new NamedPipeServerStream("pipeBloodSpiderDetectorOut", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

                pipeServer.WaitForConnection();

                StreamString ss = new StreamString(pipeServer);

                //verify identity
                ss.WriteString("BloodSpider_NotifyIcon");

                //get command from client
                var command = ss.ReadString();
                var split = command.Split(new string[] { "|" }, StringSplitOptions.None);

                switch (split[0].ToUpperInvariant().Trim())
                {
                    case "MSG":
                        ToolTipIcon icon = ToolTipIcon.None;
                        switch (split[3])
                        {
                            case "1": icon = ToolTipIcon.Info;
                                break;
                            case "2": icon = ToolTipIcon.Warning;
                                break;
                            case "3": icon = ToolTipIcon.Error;
                                break;
                            default:
                                break;
                        }
                        ShowNotificationBalloon(5000, split[1], split[2], icon);
                        break;
                    case "ULD":
                        DialogResult result = MessageBox.Show(split[2], split[1], MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                        if (result == DialogResult.Yes)
                        {
                            pipeWrite("ULD_YES", string.Empty, string.Empty, 0);
                        }
                        break;
                    case "BUSYICON":
                        switch (split[1].ToLowerInvariant())
                        {
                            case "busy": ChangeNotifyIcon(Icons.Busy);
                                break;
                            case "notbusy": ChangeNotifyIcon(Icons.Enabled);
                                break;
                            case "disabled": ChangeNotifyIcon(Icons.Disabled);
                                break;
                            default:
                                break;
                        }
                        break;
                    case "PATH_REQ":
                        pipeWrite("ULD_PATH_RESP", Path.Combine(Common.Statics.BaseFilepath, "BloodSpider.sav"), string.Empty, 0);
                        break;
                    case "UPDATE_CHECK_FINISHED":
                        PerformUpdate(split[1]);
                        break;
                    default: break;
                };
            }
            catch (Exception)
            {
            }
            finally
            {
                if (pipeServer != null)
                    pipeServer.Close();
            }
        }
Exemplo n.º 27
0
        private void StartPipeListen(object state)
        {
            try
            {
                serverPipe = new NamedPipeServerStream(PIPENAME, PipeDirection.In);
                Trace.WriteLine("Waiting for connection...");
                serverPipe.WaitForConnection();
                Trace.WriteLine("Connection established...");

                using (StreamReader sr = new StreamReader(serverPipe))
                {
                    while (!_pipeStopper)
                    {
                        string content = sr.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                            BuildWindow.OutputStringThreadSafe(content + "\r\n");
                        System.Threading.Thread.Sleep(200);
                    }
                }

                Debug.WriteLine("close pipe....");
                serverPipe.Close();
                _pipeStopper = false;
            }
            finally
            {
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Checks to see if memory is available, and if it is creates a new
        /// Connection object, awaits the completion of the connection, then
        /// runs <see cref="ConnectionCompleted"/> for cleanup.
        /// </summary>
        private async Task DispatchConnection(NamedPipeServerStream pipeStream)
        {
            try
            {
                // There is always a race between timeout and connections because
                // there is no way to cancel listening on the pipe without
                // closing the pipe. We immediately increment the connection
                // semaphore while processing connections in order to narrow
                // the race window as much as possible.
                Interlocked.Increment(ref this.activeConnectionCount);

                if (Environment.Is64BitProcess || MemoryHelper.IsMemoryAvailable())
                {
                    CompilerServerLogger.Log("Memory available - accepting connection");

                    Connection connection = new Connection(pipeStream, handler);

                    await connection.ServeConnection().ConfigureAwait(false);

                    // The connection should be finished
                    ConnectionCompleted(connection);
                }
                else
                {
                    CompilerServerLogger.Log("Memory tight - rejecting connection.");
                    // As long as we haven't written a response, the client has not 
                    // committed to this server instance and can look elsewhere.
                    pipeStream.Close();

                    // We didn't create a connection -- decrement the semaphore
                    Interlocked.Decrement(ref this.activeConnectionCount);

                    // Start a terminate server timer if there are no active
                    // connections
                    StartTimeoutTimerIfNecessary();
                }
            }
            catch (Exception e) if (CompilerFatalError.Report(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        /// <summary>
        /// Create an instance of the pipe. This might be the first instance, or a subsequent instance.
        /// There always needs to be an instance of the pipe created to listen for a new client connection.
        /// </summary>
        /// <returns>The pipe instance, or NULL if the pipe couldn't be created..</returns>
        private NamedPipeServerStream ConstructPipe()
        {
            // Add the process ID onto the pipe name so each process gets a unique pipe name.
            // The client must user this algorithm too to connect.
            string pipeName = basePipeName + Process.GetCurrentProcess().Id.ToString();

            try
            {
                CompilerServerLogger.Log("Constructing pipe '{0}'.", pipeName);

                SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
                PipeSecurity security = new PipeSecurity();

                // Restrict access to just this account.  
                PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow);
                security.AddAccessRule(rule);
                security.SetOwner(identifier);

                NamedPipeServerStream pipeStream = new NamedPipeServerStream(
                    pipeName,
                    PipeDirection.InOut,
                    NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections.
                    PipeTransmissionMode.Byte,
                    PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                    PipeBufferSize, // Default input buffer
                    PipeBufferSize, // Default output buffer
                    security,
                    HandleInheritability.None);

                CompilerServerLogger.Log("Successfully constructed pipe '{0}'.", pipeName);

                return pipeStream;
            }
            catch (Exception e)
            {
                // Windows may not create the pipe for a number of reasons.
                CompilerServerLogger.LogException(e, string.Format("Construction of pipe '{0}' failed", pipeName));
                return null;
            }
        }
Exemplo n.º 29
0
        //private const int ALLSELECT = 60;
        //private const int CUT = 52;
        static void Main(string[] args)
        {
            string[] simpleNames = { "Yukari", "Maki", "Zunko", "Akane", "Aoi", "Koh" };
            string[] voiceroidNames = {
                                          "VOICEROID+ 結月ゆかり EX",
                                          "VOICEROID+ 民安ともえ EX",
                                          "VOICEROID+ 東北ずん子 EX",
                                          "VOICEROID+ 琴葉茜",
                                          "VOICEROID+ 琴葉葵",
                                          "VOICEROID+ 水奈瀬コウ EX"
                                      };
            Console.WriteLine("");

            //引数のチェック
            if (args.Length < 1) {
                string mergeName = "";
                for (int i = 0; i < simpleNames.Length; i++) {
                    mergeName = mergeName + simpleNames[i];
                    if (i < simpleNames.Length - 1)
                        mergeName = mergeName + ", ";
                }
                Console.WriteLine("使用するVOICEROIDを引数に追加してください: " + mergeName);
                return;
            }
            //引数に設定されたボイスロイドの名前をチェック
            string selectedSimple = null;
            int selectedIndex = 0;
            for (int i = 0; i < simpleNames.Length; i++) {
                if (args[0].CompareTo(simpleNames[i]) == 0) {
                    selectedSimple = simpleNames[i];
                    selectedIndex = i;
                    break;
                }
            }
            if (selectedSimple == null) {
                string mergeName = "";
                for (int i = 0; i < simpleNames.Length; i++) {
                    mergeName = mergeName + simpleNames[i];
                    if (i < simpleNames.Length - 1)
                        mergeName = mergeName + ", ";
                }
                Console.WriteLine("引数に指定されたVOICEROIDの名前が正しくありません. 使用できる名前は次のとおりです: " + mergeName);
                return;
            }
            //VOICEROID.exeの起動チェック
            Process[] apps = Process.GetProcessesByName("VOICEROID");
            if (apps.Length < 1)
            {
                Console.WriteLine("プロセスに" + voiceroidNames[selectedIndex] + "のVOICEROID.exeがありません. " + voiceroidNames[selectedIndex] + "を起動してください.");
                return;
            }
            //VOICEROID.exeのプロセス取得
            AutomationElement ae = null;
            foreach (Process app in apps)
            {
                AutomationElement rootHandle = AutomationElement.FromHandle(app.MainWindowHandle);
                foreach(string voiceroidName in voiceroidNames) {
                    string name = rootHandle.Current.Name;
                    if (name.CompareTo(voiceroidNames[selectedIndex]) == 0 || name.CompareTo(voiceroidNames[selectedIndex]+"*") == 0) ae = rootHandle;
                }
            }
            //起動しているVOICEROID.exeと指定されたキャラクターのVOICEROID.exeが一致しなかった時
            if(ae == null) {
                string mergeName = "";
                for (int i = 0; i < simpleNames.Length; i++) {
                    mergeName = mergeName + simpleNames[i];
                    if (i < simpleNames.Length - 1)
                        mergeName = mergeName + ", ";
                }
                Console.WriteLine("引数に指定された名前のVOICEROIDが起動していません. 他の名前を指定するか, 指定した名前のVOICEROID.exeを起動してください: " + mergeName);
                return;
            }
            Console.Clear();
            //ウィンドウにフォーカスをあわせる
            ae.SetFocus();

            //テキストボックス、再生ボタン、停止ボタンのGUIコントロール取得
            AutomationElement txtForm = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtMain", PropertyConditionFlags.IgnoreCase));
            IntPtr txtFormHandle = IntPtr.Zero;
            try {
                txtFormHandle = (IntPtr)txtForm.Current.NativeWindowHandle;
            }
            catch (NullReferenceException e) {
                //ハンドルが取得できなかった場合、ウィンドウが見つかっていない
                Console.WriteLine(voiceroidNames[selectedIndex] + "のウィンドウが取得できませんでした. 最小化されているか, ほかのプロセスによってブロックされています.");
                return;
            }
            //テキストボックスのハンドルを取得
            IntPtr txtControl = FindWindowEx(txtFormHandle, IntPtr.Zero, null, null);
            //再生ボタンのハンドルを取得
            AutomationElement btnPlay = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "btnPlay", PropertyConditionFlags.IgnoreCase));
            IntPtr btnControl = (IntPtr)btnPlay.Current.NativeWindowHandle;
            //停止ボタンのハンドルを取得
            AutomationElement btnStop = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "btnStop", PropertyConditionFlags.IgnoreCase));
            IntPtr stpControl = (IntPtr)btnStop.Current.NativeWindowHandle;

            //音量、速度、高さ、抑揚のテキストボックスのコントロールを取得
            AutomationElement txtVol = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtVolume", PropertyConditionFlags.IgnoreCase));
            AutomationElement txtSpd = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtSpeed", PropertyConditionFlags.IgnoreCase));
            AutomationElement txtPit = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtPitch", PropertyConditionFlags.IgnoreCase));
            AutomationElement txtEmp = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtEmphasis", PropertyConditionFlags.IgnoreCase));

            //音声効果の画面が表示されていない時の処理
            if (txtVol == null || txtSpd == null || txtPit == null || txtEmp == null) {
                Console.WriteLine("音声効果の画面を展開しています...");
                Thread.Sleep(100);

                //音声チューニングのタブを取得
                AutomationElementCollection tabs = ae.FindAll(TreeScope.Descendants,
                    new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "タブ項目", PropertyConditionFlags.IgnoreCase));

                //音声チューニングのタブが取得できない時の処理
                if (tabs.Count < 1) {
                    AutomationElementCollection menues = ae.FindAll(TreeScope.Descendants,
                        new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "メニュー項目", PropertyConditionFlags.IgnoreCase));

                    //音声チューニングのウィンドウを表示する
                    foreach (AutomationElement menu in menues) {
                        if (menu.Current.Name.CompareTo("音声チューニング(T)") == 0) {
                            object ipShowTuning;
                            if (menu.TryGetCurrentPattern(InvokePattern.Pattern, out ipShowTuning)) {
                                ((InvokePattern)ipShowTuning).Invoke();
                                Thread.Sleep(1000);
                            }
                        }
                    }

                    //再度音声チューニング
                    tabs = ae.FindAll(TreeScope.Descendants,
                    new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "タブ項目", PropertyConditionFlags.IgnoreCase));
                }

                //音声効果のタブを探す
                foreach (AutomationElement tab in tabs) {
                    if (tab.Current.Name.CompareTo("音声効果") == 0) {
                        object ipShowSoundEffect;
                        if (tab.TryGetCurrentPattern(SelectionItemPattern.Pattern, out ipShowSoundEffect)) {
                            ((SelectionItemPattern)ipShowSoundEffect).Select();
                            Thread.Sleep(1000);
                        }
                    }
                }

                //再度、音量、速度、高さ、抑揚のテキストボックスのコントロールを取得
                txtVol = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtVolume", PropertyConditionFlags.IgnoreCase));
                txtSpd = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtSpeed", PropertyConditionFlags.IgnoreCase));
                txtPit = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtPitch", PropertyConditionFlags.IgnoreCase));
                txtEmp = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtEmphasis", PropertyConditionFlags.IgnoreCase));
            }

            //再度、音量、速度、高さ、抑揚のハンドルを取得
            IntPtr txtVolControl = (IntPtr)txtVol.Current.NativeWindowHandle;
            IntPtr txtSpdControl = (IntPtr)txtSpd.Current.NativeWindowHandle;
            IntPtr txtPitControl = (IntPtr)txtPit.Current.NativeWindowHandle;
            IntPtr txtEmpControl = (IntPtr)txtEmp.Current.NativeWindowHandle;

            //InvokePattern ipBtnPlay = (InvokePattern)btnPlay.GetCurrentPattern(InvokePattern.Pattern);
            //ValuePattern vpTxtVol = (ValuePattern)txtVol.GetCurrentPattern(ValuePattern.Pattern);
            //ValuePattern vpTxtSpd = (ValuePattern)txtSpd.GetCurrentPattern(ValuePattern.Pattern);
            //ValuePattern vpTxtPit = (ValuePattern)txtPit.GetCurrentPattern(ValuePattern.Pattern);
            //ValuePattern vpTxtEmp = (ValuePattern)txtEmp.GetCurrentPattern(ValuePattern.Pattern);

            string btnName = btnPlay.Current.Name;
            string message = "";
            Console.WriteLine("[voiceroid_talker" +selectedSimple + "]のサーバーを開始しています...");

            //メインループ
            while (true) {
                string clientMessage;
                string[] messages;
                string messageVol = "1.0";
                string messageSpd = "1.0";
                string messagePit = "1.0";
                string messageEmp = "1.0";
                //通信セッションの開始
                try
                {
                    using (NamedPipeServerStream server = new NamedPipeServerStream("voiceroid_talker" + selectedSimple))
                    {
                        Console.WriteLine("クライアントからのメッセージを待っています...");
                        server.WaitForConnection();

                        byte[] buffer = new byte[1024];
                        server.Read(buffer, 0, buffer.Length);
                        string messageRaw = UnicodeEncoding.Unicode.GetString(buffer);
                        clientMessage = messageRaw.Trim('\0');
                        //通信メッセージの内容をパースする
                        messages = clientMessage.Split(';');
                        if (messages.Length == 1)
                        {
                            message = clientMessage;
                            if (message.CompareTo("exit") == 0) break;
                        }
                        else
                        {
                            message = messages[0];
                        }
                        //音量のパラメータを取得する
                        if (messages.Length >= 2)
                        {
                            float val = 0.0f;
                            if (float.TryParse(messages[1], out val)) messageVol = val.ToString();
                        }
                        //速度のパラメータを取得する
                        if (messages.Length >= 3)
                        {
                            float val = 0.0f;
                            if (float.TryParse(messages[2], out val)) messageSpd = val.ToString();
                        }
                        //高さのパラメータを取得する
                        if (messages.Length >= 4)
                        {
                            float val = 0.0f;
                            if (float.TryParse(messages[3], out val)) messagePit = val.ToString();
                        }
                        //抑揚のパラメータを取得する
                        if (messages.Length >= 5)
                        {
                            float val = 0.0f;
                            if (float.TryParse(messages[4], out val)) messageEmp = val.ToString();
                        }

                        //音量、速度、高さ、抑揚のテキストボックスに値を入力
                        SendMessage(txtVolControl, WM_SETTEXT, IntPtr.Zero, messageVol);
                        PostMessage(txtVolControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null);

                        SendMessage(txtSpdControl, WM_SETTEXT, IntPtr.Zero, messageSpd);
                        PostMessage(txtSpdControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null);

                        SendMessage(txtPitControl, WM_SETTEXT, IntPtr.Zero, messagePit);
                        PostMessage(txtPitControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null);

                        SendMessage(txtEmpControl, WM_SETTEXT, IntPtr.Zero, messageEmp);
                        PostMessage(txtEmpControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null);

                        Thread.Sleep(10);

                        //テキストボックスにメッセージを入れ、再生する
                        SendMessage(txtControl, WM_SETTEXT, IntPtr.Zero, message);
                        PostMessage(stpControl, WM_CLICK, IntPtr.Zero, null);
                        PostMessage(btnControl, WM_CLICK, IntPtr.Zero, null);

                        //ipBtnPlay.Invoke();
                        Thread.Sleep(100);

                        //レスポンス用メッセージをクライアントに送信
                        byte[] response = UnicodeEncoding.Unicode.GetBytes("OK");
                        server.Write(response, 0, 2);

                        //セッションを終了する
                        server.Close();
                    }
                } catch(IOException e) {
                    //セッション作成時にエラーが発生した場合
                    Console.WriteLine("通信セッションの作成に失敗しました. 他のサーバーによって, 同名のセッションが開始されている可能性があります.");
                    break;
                }
            }
        }
Exemplo n.º 30
0
        public void DoEncode(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            string passStr = Processing.GetResourceString("vp8_pass");
            string status = Processing.GetResourceString("vp8_encoding_status");
            string progressFormat = Processing.GetResourceString("vp8_encoding_progress");

            //progress vars
            DateTime startTime = DateTime.Now;
            TimeSpan remaining = new TimeSpan(0, 0, 0);
            // end progress

            VP8Profile encProfile = (VP8Profile)_jobInfo.VideoProfile;

            if (!_jobInfo.EncodingProfile.Deinterlace && _jobInfo.VideoStream.Interlaced)
                _jobInfo.VideoStream.Interlaced = false;

            Size resizeTo = VideoHelper.GetTargetSize(_jobInfo);

            if (string.IsNullOrEmpty(_jobInfo.AviSynthScript))
                GenerateAviSynthScript(resizeTo);

            string inputFile = _jobInfo.AviSynthScript;
            string outFile =
                Processing.CreateTempFile(
                    string.IsNullOrEmpty(_jobInfo.TempOutput) ? _jobInfo.JobName : _jobInfo.TempOutput, "encoded.webm");

            _frameCount = _jobInfo.VideoStream.FrameCount;

            int targetBitrate = 0;
            if (_jobInfo.EncodingProfile.TargetFileSize > 0)
                targetBitrate = Processing.CalculateVideoBitrate(_jobInfo);

            int encodeMode = encProfile.EncodingMode;
            string pass = string.Empty;
            if (encodeMode == 1)
                pass = string.Format(" {1} {0:0}; ", _jobInfo.StreamId, passStr);

            _bw.ReportProgress(-10, status + pass.Replace("; ", string.Empty));
            _bw.ReportProgress(0, status);

            string argument = VP8CommandLineGenerator.Generate(encProfile,
                                                                targetBitrate,
                                                                resizeTo.Width,
                                                                resizeTo.Height,
                                                                _jobInfo.StreamId,
                                                                _jobInfo.VideoStream.FrameRateEnumerator,
                                                                _jobInfo.VideoStream.FrameRateDenominator,
                                                                outFile);

            string localExecutable = Path.Combine(AppSettings.ToolsPath, Executable);

            Regex frameInformation = new Regex(@"^.*Pass\s\d\/\d frame \s*\d*\/(\d*).*$",
                                               RegexOptions.Singleline | RegexOptions.Multiline);

            using (Process encoder = new Process(),
                           decoder = FfMpeg.GenerateDecodeProcess(inputFile))
            {
                ProcessStartInfo parameter = new ProcessStartInfo(localExecutable)
                    {
                        WorkingDirectory = AppSettings.DemuxLocation,
                        Arguments = argument,
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardError = true,
                        RedirectStandardInput = true
                    };
                encoder.StartInfo = parameter;

                encoder.ErrorDataReceived += (outputSender, outputEvent) =>
                    {
                        string line = outputEvent.Data;

                        if (string.IsNullOrEmpty(line)) return;

                        Match result = frameInformation.Match(line);

                        // ReSharper disable AccessToModifiedClosure
                        TimeSpan eta = DateTime.Now.Subtract(startTime);
                        // ReSharper restore AccessToModifiedClosure
                        long secRemaining = 0;

                        if (result.Success)
                        {
                            long current;
                            Int64.TryParse(result.Groups[1].Value, NumberStyles.Number,
                                           AppSettings.CInfo, out current);
                            long framesRemaining = _frameCount - current;
                            float fps = 0f;
                            if (eta.Seconds != 0)
                            {
                                //Frames per Second
                                double codingFPS = Math.Round(current/eta.TotalSeconds, 2);

                                if (codingFPS > 1)
                                {
                                    secRemaining = framesRemaining/(int) codingFPS;
                                    fps = (float) codingFPS;
                                }
                                else
                                    secRemaining = 0;
                            }

                            if (secRemaining > 0)
                                remaining = new TimeSpan(0, 0, (int) secRemaining);

                            DateTime ticks = new DateTime(eta.Ticks);

                            string progress = string.Format(progressFormat,
                                                            current, _frameCount,
                                                            fps,
                                                            remaining, ticks, pass);
                            _bw.ReportProgress((int) (((float) current/_frameCount)*100),
                                               progress);
                        }
                        else
                        {
                            Log.InfoFormat("vpxenc: {0:s}", line);
                        }
                    };

                Log.InfoFormat("start parameter: vpxenc {0:s}", argument);

                bool started;
                bool decStarted;
                try
                {
                    started = encoder.Start();
                }
                catch (Exception ex)
                {
                    started = false;
                    Log.ErrorFormat("vpxenc exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                NamedPipeServerStream decodePipe = new NamedPipeServerStream(AppSettings.DecodeNamedPipeName,
                                                                             PipeDirection.In, 1,
                                                                             PipeTransmissionMode.Byte, PipeOptions.None);

                try
                {
                    decStarted = decoder.Start();
                }
                catch (Exception ex)
                {
                    decStarted = false;
                    Log.ErrorFormat("avconv exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                startTime = DateTime.Now;

                if (started && decStarted)
                {
                    encoder.PriorityClass = AppSettings.GetProcessPriority();
                    encoder.BeginErrorReadLine();
                    decoder.PriorityClass = AppSettings.GetProcessPriority();
                    decoder.BeginErrorReadLine();

                    Thread pipeReadThread = new Thread(() =>
                        {
                            try
                            {
                                ReadThreadStart(decodePipe, encoder);
                            }
                            catch (Exception ex)
                            {
                                Log.Error(ex);
                            }
                        });
                    pipeReadThread.Start();
                    pipeReadThread.Priority = ThreadPriority.BelowNormal;
                    encoder.Exited += (o, args) => pipeReadThread.Abort();

                    while (!encoder.HasExited)
                    {
                        if (_bw.CancellationPending)
                        {
                            encoder.Kill();
                            decoder.Kill();
                        }
                        Thread.Sleep(200);
                    }

                    encoder.WaitForExit(10000);
                    encoder.CancelErrorRead();

                    if (decodePipe.IsConnected)
                        try
                        {
                            decodePipe.Disconnect();
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                        }

                    try
                    {
                        decodePipe.Close();
                        decodePipe.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                    }

                    decoder.WaitForExit(10000);
                    decoder.CancelErrorRead();

                    _jobInfo.ExitCode = encoder.ExitCode;
                    Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);
                }
            }

            if (_jobInfo.ExitCode == 0)
            {
                if ((encProfile.EncodingMode == 1 && _jobInfo.StreamId == 2) ||
                    encProfile.EncodingMode == 0)
                {
                    _jobInfo.VideoStream.Encoded = true;
                    _jobInfo.VideoStream.IsRawStream = false;

                    _jobInfo.TempFiles.Add(_jobInfo.VideoStream.TempFile);
                    _jobInfo.VideoStream.TempFile = outFile;

                    try
                    {
                        _jobInfo.MediaInfo = Processing.GetMediaInfo(_jobInfo.VideoStream.TempFile);
                    }
                    catch (TimeoutException ex)
                    {
                        Log.Error(ex);
                    }
                    _jobInfo.VideoStream = VideoHelper.GetStreamInfo(_jobInfo.MediaInfo, _jobInfo.VideoStream, _jobInfo.EncodingProfile.OutFormat == OutputType.OutputBluRay);

                    string statsFile = Processing.CreateTempFile(outFile, "stats");
                    _jobInfo.TempFiles.Add(statsFile);
                    _jobInfo.TempFiles.Add(_jobInfo.AviSynthScript);
                    _jobInfo.TempFiles.Add(_jobInfo.FfIndexFile);
                    _jobInfo.TempFiles.Add(_jobInfo.AviSynthStereoConfig);
                }
            }

            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;
            e.Result = _jobInfo;
        }