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(); } }
public void Run() { while (true) { NamedPipeServerStream pipeStream = null; try { pipeStream = new NamedPipeServerStream(ConnectionName, PipeDirection.InOut, -1, PipeTransmissionMode.Message); pipeStream.WaitForConnection(); if (_stop) return; // Spawn a new thread for each request and continue waiting var t = new Thread(ProcessClientThread); t.Start(pipeStream); } catch (Exception) { if (pipeStream != null) pipeStream.Dispose(); throw; } } // ReSharper disable once FunctionNeverReturns }
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(); }
// 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(); }
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(); }
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); }
static void Main(string[] args) { // Create a name pipe NamedPipeServerStream pipeStream = null; try { pipeStream = new NamedPipeServerStream(LogManager.ConnectionName, PipeDirection.InOut, 1, PipeTransmissionMode.Message); Console.WriteLine("Log Monitor started: " + pipeStream.GetHashCode()); // Wait for a connection pipeStream.WaitForConnection(); Console.WriteLine("Connection established"); using (StreamReader sr = new StreamReader(pipeStream)) { pipeStream = null; string temp; // We read a line from the pipe and print it together with the current time while ((temp = sr.ReadLine()) != null) { Console.WriteLine(temp); } } } finally { if (pipeStream != null) { pipeStream.Dispose(); } } Console.WriteLine("Connection lost"); Console.WriteLine("Press <ENTER> to quit"); Console.ReadLine(); }
public void StartPipeServer() { serverStream = new NamedPipeServerStream("zjlrcpipe", PipeDirection.InOut, 10, PipeTransmissionMode.Message, PipeOptions.None); serverStream.ReadMode = PipeTransmissionMode.Message; Byte[] bytes = new Byte[1024]; UTF8Encoding encoding = new UTF8Encoding(); int numBytes; while (running) { serverStream.WaitForConnection(); string message = ""; do { numBytes = serverStream.Read(bytes, 0, bytes.Length); message += encoding.GetString(bytes, 0, numBytes); } while (!serverStream.IsMessageComplete); string[] pas = message.Split('|'); if (null != pas && pas.Length >= 3) { if (!(pas[0] == "exit" && pas[1] == "exit" && pas[2] == "exit")) main.Dispatcher.Invoke(main.searchLrcByZLP, pas[0], pas[1], pas[2]); else running = false; } serverStream.Disconnect(); } serverStream.Dispose(); }
public void StartListen(NamedPipeServerStream pipeServer) { if (_stopListen) { if (pipeServer != null) pipeServer.Dispose(); return; } try { if (pipeServer == null) { pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, NumberOfPipeInst, PipeTransmissionMode.Byte, PipeOptions.WriteThrough | PipeOptions.Asynchronous); } pipeServer.BeginWaitForConnection(OnConnectToClient, pipeServer); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
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; }
static string ReadPythonPipe(NamedPipeServerStream server) { //Reading var br = new BinaryReader(server); var bw = new BinaryWriter(server); while (true) { try { var len = (int)br.ReadUInt32(); // Read string length //Console.WriteLine("Length: {0}", len.ToString()); 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); //for (int i=0; i<data.Length; i++) //{ // return data[i]; //} //char[] data = str.ToCharArray; string data = str; return data; } catch (EndOfStreamException) { break; // When client disconnects } } Console.WriteLine("Client disconnected."); server.Close(); server.Dispose(); //char[] empty = null; string empty = null; return empty; }
private void AddUser(string firstname, string lastname, string username, string password, string confirmPass) { string pattern = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.* ).{8,15}$"; //asks the database if the username exists already if (password != confirmPass) { MessageBox.Show("Passwords do not match"); } else if (!Regex.IsMatch(password, pattern)) { MessageBox.Show(password); MessageBox.Show("Password must be between 8-15 characters and must contain at least one uppercase letter, one lowercase letter, one number and no special characters besides space"); } //Password must be at least 8 characters long else if (password.Length < 8) { MessageBox.Show("Password must be at least 8 characters long"); } else if (username == null || username.Length < 2 || username.Length > 15) { MessageBox.Show("Username missing or too short"); } else if (firstname == null || firstname.Length < 2) { MessageBox.Show("First name missing or too short"); } else if (lastname == null || lastname.Length < 2) { MessageBox.Show("Last name missing or too short"); } else { this.Hide(); Random rnd = new Random(); int uid = rnd.Next(10000000, 99999999); string UID = uid.ToString(); string hashed_password = sha256(password); string information_string = "register#" + UID + "#" + firstname + "#" + lastname + "#" + username + "#" + hashed_password; //send python all the information for registration var server = new NamedPipeServerStream("Communicate"); server.WaitForConnection(); var br = new BinaryReader(server); var bw = new BinaryWriter(server); send(bw, information_string); string message = recv(br); server.Close(); server.Dispose(); if (message == "Signed up") { MessageBox.Show("User Signed Up"); } else if (message == "username exists") { this.Show(); MessageBox.Show("Username already exists"); } } }
void pipeWorker_DoWork(object sender, DoWorkEventArgs e) { try { var server = new NamedPipeServerStream("alotPipe"); updateStatus("Waiting for connection from alot.py..."); server.WaitForConnection(); updateStatus(""); var br = new BinaryReader(server); var bw = new BinaryWriter(server); while (true) { try { var len = (int)br.ReadUInt32(); var msg = new string(br.ReadChars(len)); //write received message to file (for debugging purposes) StreamWriter file = new StreamWriter(Application.StartupPath + "\\last received message.txt"); file.WriteLine(msg); file.Close(); processMsg(msg); } catch (EndOfStreamException) { break; } } server.Close(); server.Dispose(); } catch (Exception exc) { MessageBox.Show("Exception in pipeWorker_DoWork(): " + exc.Message); } }
void sendFeedbackToAlot(string feedback) { try { var server = new NamedPipeServerStream("alotPipeFeedback"); server.WaitForConnection(); var bw = new BinaryWriter(server); if (feedback == "True") bw.Write(true); else bw.Write(feedback); server.Close(); server.Dispose(); } catch (Exception exc) { MessageBox.Show("Error while sending feedback!" + Environment.NewLine + exc.Message + Environment.NewLine + Environment.NewLine + "Trying again..."); sendFeedbackToAlot(feedback); } }
public void PipeReader() { // Open the named pipe. 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); while (true) { try { var len = (int)br.ReadUInt32(); // Read string length if (len == 0) continue; var str = new string(br.ReadChars(len)); // Read string string[] ips = str.Split(';'); this.dataArray = ips; dele invokeDELE = new dele(this.updateDataGrid); this.Invoke(invokeDELE); //Console.WriteLine("Read: " + str); } catch (EndOfStreamException) { break; // When client disconnects } } MessageBox.Show("Engine has disconnected"); server.Close(); server.Dispose(); }
private void StopDesktopApplication(NamedPipeServerStream pipeStream, Thread dtThread) { UTF8Encoding encoding = new UTF8Encoding(); string message1 = "TestSuite Run Completed"; Byte[] bytes; bytes = encoding.GetBytes(message1); pipeStream.Write(bytes, 0, bytes.Length); pipeStream.Dispose(); if (dtThread != null) { dtThread.Abort(); } }
private void ProcessClientThread(NamedPipeServerStream pipeStream) { try { if (this.RequestReieved != null) //has event subscribers { var args = new PipeClientConnectionEventArgs(pipeStream); RequestReieved(this, args); } } catch (Exception e) { _log.Error("ProcessClientThread error: {0}", e.ToString().Flatten()); } finally { if (pipeStream.IsConnected) pipeStream.Close(); pipeStream.Dispose(); } }
public void PipeReader() { // Open the named pipe. var server = new NamedPipeServerStream("Data"); //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 if (len == 0) continue; var str = new string(br.ReadChars(len)); // Read string string[] clients = str.Split(';'); this._names = new List<string>(); this._dataArray = new List<string[]>(); for (int i = 0; i < clients.Length; i++) { string name = clients[i].Split('%')[0]; this._names.Add(name); string[] dates = (clients[i].Split('%')[1]).Split(','); this._dataArray.Add(dates); } dele invokeDELE = new dele(this.updateDataGrid); this.Invoke(invokeDELE); //Console.WriteLine("Read: " + str); } catch (EndOfStreamException) { break; // When client disconnects } } MessageBox.Show("Engine has disconnected"); server.Close(); server.Dispose(); }
public async Task NamedPipeViaFileStream_AllDataCopied(bool useAsync, int writeSize, int numWrites) { long totalLength = writeSize * numWrites; var expectedData = new byte[totalLength]; new Random(42).NextBytes(expectedData); var results = new MemoryStream(); var pipeOptions = useAsync ? PipeOptions.Asynchronous : PipeOptions.None; string name = Guid.NewGuid().ToString("N"); using (var server = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, pipeOptions)) { Task serverTask = Task.Run(async () => { await server.WaitForConnectionAsync(); for (int i = 0; i < numWrites; i++) { await server.WriteAsync(expectedData, i * writeSize, writeSize); } server.Dispose(); }); Assert.True(WaitNamedPipeW(@"\\.\pipe\" + name, -1)); using (SafeFileHandle clientHandle = CreateFileW(@"\\.\pipe\" + name, GENERIC_READ, FileShare.None, IntPtr.Zero, FileMode.Open, (int)pipeOptions, IntPtr.Zero)) using (var client = new FileStream(clientHandle, FileAccess.Read, bufferSize: 3, isAsync: useAsync)) { Task copyTask = client.CopyToAsync(results, (int)totalLength); await await Task.WhenAny(serverTask, copyTask); await copyTask; } } byte[] actualData = results.ToArray(); Assert.Equal(expectedData.Length, actualData.Length); Assert.Equal<byte>(expectedData, actualData); }
void PipeThread() { NamedPipeServerStream pipeServer = null; try { pipeServer = new NamedPipeServerStream("NowPlayingTunes", PipeDirection.InOut); StreamString stream = new StreamString(pipeServer); pipeServer.WaitForConnection(); //When Connected if (Song.getLatestSong() != null) { String TweetText = getTweetText(); Core.iTunesClass latestsong = Song.getLatestSong(); String sendtext = Core.Replace.ReplaceText(TweetText, latestsong); stream.WriteString(sendtext); } pipeServer.Close(); pipeServer.Dispose(); } catch (Exception ex) { Debug.WriteLine("[PluginSystem] ERROR"); Debug.WriteLine(ex.ToString()); } finally { if (pipeServer != null) { if (pipeServer.IsConnected) { pipeServer.Dispose(); } } } //Remake thread StartThread(); }
public void DoEncode(object sender, DoWorkEventArgs e) { _bw = (BackgroundWorker)sender; string passStr = Processing.GetResourceString("x264_pass"); string status = Processing.GetResourceString("x264_encoding_status"); string progressFormat = Processing.GetResourceString("x264_encoding_progress"); //progress vars DateTime startTime = DateTime.Now; TimeSpan remaining = new TimeSpan(0, 0, 0); // end progress bool use64BitEncoder = AppSettings.Use64BitEncoders && AppSettings.X26464Installed && Environment.Is64BitOperatingSystem; X264Profile encProfile = (X264Profile)_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.264"); int targetBitrate = 0; if (_jobInfo.EncodingProfile.TargetFileSize > 0) targetBitrate = Processing.CalculateVideoBitrate(_jobInfo); int encodeMode = encProfile.EncodingMode; string pass = string.Empty; if ((encodeMode == 2) || (encodeMode == 3)) pass = string.Format(" {1} {0:0}; ", _jobInfo.StreamId, passStr); _frameCount = _jobInfo.VideoStream.FrameCount; _bw.ReportProgress(-10, status + pass.Replace("; ", string.Empty)); _bw.ReportProgress(0, status); string argument = X264CommandLineGenerator.Generate(encProfile, targetBitrate, resizeTo.Width, resizeTo.Height, _jobInfo.StreamId, _jobInfo.VideoStream.FrameRateEnumerator, _jobInfo.VideoStream.FrameRateDenominator, _jobInfo.EncodingProfile.StereoType, _jobInfo.VideoStream.PicSize, // check if we use 64 bit version //use64BitEncoder ? "-" : inputFile, "-", outFile); string localExecutable = Path.Combine(AppSettings.ToolsPath, use64BitEncoder ? Executable64 : Executable); Regex frameInformation = new Regex(@"^\D?([\d]+).*frames: ([\d\.]+) fps, ([\d\.]+).*$", RegexOptions.Singleline | RegexOptions.Multiline); Regex fullFrameInformation = new Regex(@"^\[[\d\.]+?%\] ([\d]+?)/([\d]+?) frames, ([\d\.]+?) fps, ([\d\.]+?) kb/s.*$", RegexOptions.Singleline | RegexOptions.Multiline); using (Process encoder = new Process()) { ProcessStartInfo parameter = new ProcessStartInfo(localExecutable) { WorkingDirectory = AppSettings.DemuxLocation, Arguments = argument, CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true, RedirectStandardInput = use64BitEncoder }; encoder.StartInfo = parameter; encoder.ErrorDataReceived += (outputSender, outputEvent) => { string line = outputEvent.Data; if (string.IsNullOrEmpty(line)) return; Match frameMatch = frameInformation.Match(line); Match fullFrameMatch = fullFrameInformation.Match(line); TimeSpan eta = DateTime.Now.Subtract(startTime); long current; long framesRemaining; long secRemaining = 0; float encBitrate; float fps; DateTime ticks; double codingFPS; if (frameMatch.Success) { Int64.TryParse(frameMatch.Groups[1].Value, NumberStyles.Number, AppSettings.CInfo, out current); framesRemaining = _frameCount - current; if (eta.Seconds != 0) { //Frames per Second codingFPS = Math.Round(current/eta.TotalSeconds, 2); if (codingFPS > 1) secRemaining = framesRemaining/(int) codingFPS; else secRemaining = 0; } if (secRemaining > 0) remaining = new TimeSpan(0, 0, (int) secRemaining); ticks = new DateTime(eta.Ticks); Single.TryParse(frameMatch.Groups[2].Value, NumberStyles.Number, AppSettings.CInfo, out fps); Single.TryParse(frameMatch.Groups[3].Value, NumberStyles.Number, AppSettings.CInfo, out encBitrate); string progress = string.Format(progressFormat, current, _frameCount, fps, encBitrate, remaining, ticks, pass); _bw.ReportProgress((int) (((float) current/_frameCount)*100), progress); } else if (fullFrameMatch.Success) { Int64.TryParse(fullFrameMatch.Groups[1].Value, NumberStyles.Number, AppSettings.CInfo, out current); Int64.TryParse(fullFrameMatch.Groups[2].Value, NumberStyles.Number, AppSettings.CInfo, out _frameCount); framesRemaining = _frameCount - current; if (eta.Seconds != 0) { //Frames per Second codingFPS = Math.Round(current/eta.TotalSeconds, 2); if (codingFPS > 1) secRemaining = framesRemaining/(int) codingFPS; else secRemaining = 0; } if (secRemaining > 0) remaining = new TimeSpan(0, 0, (int) secRemaining); ticks = new DateTime(eta.Ticks); Single.TryParse(fullFrameMatch.Groups[3].Value, NumberStyles.Number, AppSettings.CInfo, out fps); Single.TryParse(fullFrameMatch.Groups[4].Value, NumberStyles.Number, AppSettings.CInfo, out encBitrate); string progress = string.Format(progressFormat, current, _frameCount, fps, encBitrate, remaining, ticks, pass); _bw.ReportProgress((int) (((float) current/_frameCount)*100), progress); } else { Log.InfoFormat("x264: {0:s}", line); } }; Log.InfoFormat("start parameter: x264 {0:s}", argument); bool started; bool decStarted; NamedPipeServerStream decodePipe = new NamedPipeServerStream(AppSettings.DecodeNamedPipeName, PipeDirection.InOut, 3, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); decodePipe.BeginWaitForConnection(decoderConnected, null); Process decoder = FfMpeg.GenerateDecodeProcess(inputFile); try { decStarted = decoder.Start(); } catch (Exception ex) { decStarted = false; Log.ErrorFormat("avconv exception: {0}", ex); _jobInfo.ExitCode = -1; } try { started = encoder.Start(); } catch (Exception ex) { started = false; Log.ErrorFormat("x264 encoder 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; decoder.Exited += (o, args) => { try { decodePipe.Disconnect(); decodePipe.Close(); decodePipe.Dispose(); } catch (Exception ex) { Log.Error(ex); } }; encoder.Exited += (o, args) => pipeReadThread.Abort(); while (!encoder.HasExited && !decoder.HasExited) { if (_bw.CancellationPending) { encoder.Kill(); decoder.Kill(); } Thread.Sleep(200); } encoder.WaitForExit(10000); encoder.CancelErrorRead(); decoder.WaitForExit(10000); decoder.CancelErrorRead(); _jobInfo.ExitCode = encoder.ExitCode; Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode); } } if (_jobInfo.ExitCode == 0) { if ((encProfile.EncodingMode == 2 && _jobInfo.StreamId == 2) || (encProfile.EncodingMode == 3 && _jobInfo.StreamId == 3) || (encProfile.EncodingMode < 2 || _jobInfo.StreamId > 3)) { _jobInfo.VideoStream.Encoded = true; _jobInfo.VideoStream.IsRawStream = true; _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); _jobInfo.TempFiles.Add(Path.Combine(AppSettings.DemuxLocation, "x264_2pass.log")); _jobInfo.TempFiles.Add(Path.Combine(AppSettings.DemuxLocation, "x264_2pass.log.mbtree")); _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; }
//need to continue!!!! private void browse2unlock_Click(object sender, EventArgs e) { OpenFileDialog Unlocker = new OpenFileDialog(); Unlocker.ShowDialog(); Unlocker.InitialDirectory = @"C:\"; Unlocker.Title = "Browse Files to Unlock"; string file_to_unlock = Unlocker.FileName; string uid = this.my_uid; // need to get the current user uid string information_string = "Unlock#" + uid + "#" + file_to_unlock; var server = new NamedPipeServerStream("Communicate"); server.WaitForConnection(); var br = new BinaryReader(server); var bw = new BinaryWriter(server); send(bw, information_string); string message = recv(br); message = message + recv(br); if (message == "File Unlocked") { MessageBox.Show(message); } else if (message == "The specified user is not allowed to open the file") { MessageBox.Show(message); } else if (message == "path error, can only unlock .cb files") { MessageBox.Show(message); } server.Close(); server.Dispose(); }
//public void new_form_image(MemoryStream ms) //{ // Form form2 = new Form(); // //this.SuspendLayout(); // // // // Form2 // // // form2.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); // form2.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; // form2.AutoScroll = true; // form2.ClientSize = new System.Drawing.Size(866, 461); // form2.Name = "form2"; // form2.Text = "form2"; // form2.ResumeLayout(false); // PictureBox pictureBox1 = new PictureBox(); // Image x = Image.FromStream(ms); // form2.BackgroundImage = x; // form2.Show(); //} public void PipeReader() { // Open the named pipe. var server = new NamedPipeServerStream("Data"); var Respond = new NamedPipeServerStream("Respond"); //Console.WriteLine("Waiting for connection..."); server.WaitForConnection(); Respond.WaitForConnection(); //Console.WriteLine("Connected."); var br = new BinaryReader(server); var bw = new BinaryWriter(Respond); //var bw = new BinaryWriter(server); Semaphore semaphoreObject = new Semaphore(3, 4); while (true) { try { string str=Getting_Info(semaphoreObject, br, bw); if (str.StartsWith("IMAGE")) { string tempSTR = (string)(str.Substring(6)); byte[] byteArrayIn = new byte[Int32.Parse(str.Substring(6))]; byteArrayIn = Getting_Image(semaphoreObject, br, bw, Int32.Parse(str.Substring(6))); if (this.InvokeRequired) { this.Invoke((MethodInvoker)delegate { length = byteArrayIn.Length.ToString(); }); } MemoryStream ms = new MemoryStream(byteArrayIn); Image.FromStream(ms).Save("C:\\Users\\User\\Desktop\\IMAGE_IN_GUI.jpg"); } else { string[] ClientAndPr = str.Split(','); int n = index; bool exist = false; for (int i = 0; i < clients.Count; i++) if (clients[i][0].Text == ClientAndPr[0]) { dele2 invokeDELE2 = new dele2(this.removeC); this.Invoke(invokeDELE2, i); n = i; index -= 1; exist = true; break; } index++; if (!exist) clients.Add(new Label[ClientAndPr.Length]); else clients[n] = new Label[ClientAndPr.Length]; dele invokeDELE = new dele(this.addC); this.Invoke(invokeDELE, ClientAndPr, n); } //Console.WriteLine("Read: " + str); } catch(Exception e) { MessageBox.Show(e.ToString()); } } MessageBox.Show("Engine has disconnected"); server.Close(); server.Dispose(); }
/* *METHOD : btn_submit_Click * *DESCRIPTION : used to send the new question to the service when submit clicked * *PARAMETERS : object sender: Object relaying information on where the event call came from * EventArgs e: Object that contains data about the event * *RETURNS : void * */ private void btn_submit_Click(object sender, EventArgs e) { if (txtbx_server.Text.Length > 0 && txtbx_name.Text.Length > 0) { try { userName = txtbx_name.Text; serverName = txtbx_server.Text; //set up the named pipe security PipeSecurity ps = new PipeSecurity(); System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow); ps.AddAccessRule(par); //connect to service client = new NamedPipeClientStream(serverName, "ServiceOutgoing");//add server name client.Connect(30); output = new StreamWriter(client); //tell ther service this computers name output.WriteLine(Environment.MachineName); output.Flush(); server = new NamedPipeServerStream("UserOutgoing", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps); server.WaitForConnection(); input = new StreamReader(server); //get namedPipe Name pipeName = input.ReadLine(); server.Disconnect(); server.Dispose(); Close(); } catch (Exception) { MessageBox.Show("Failed to connect to Server", "Error"); } } }
private static void ProcessConnectionCore(NamedPipeServerStream stream) { Debug.Assert(stream.IsConnected); try { var reader = new ClientReader(stream); var action = reader.ReadString(); var assemblyFileName = reader.ReadString(); switch (action) { case Constants.ActionDiscover: Discover(stream, assemblyFileName); break; case Constants.ActionRunAll: RunAll(stream, assemblyFileName); break; case Constants.ActionRunSpecific: RunSpecific(stream, assemblyFileName); break; default: Debug.Fail($"Invalid action {action}"); break; } } catch (Exception ex) { // Happens during a rude disconnect by the client Console.WriteLine(ex.Message); } finally { stream.Dispose(); } }
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"); }