// ProcessHttpRequest is the async handler for new http requests // This function should do what it needs to do and then exit public static void ProcessHttpRequest(IAsyncResult result) { RequestProcessor rp = null; try // (IAsyncResult)result will be invalid if we've killed the listener { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); // Call EndGetContext to complete the asynchronous operation. // Obtain a response object. HttpListenerResponse response = context.Response; // Create a new request processor rp = new RequestProcessor(context); rp.Run(); } catch (System.ObjectDisposedException) { // Do nothing } catch (Exception ex) { Functions.WriteLineToLogFile("Process HttpRequest Exception:"); Functions.WriteExceptionToLogFile(ex); } finally { if (rp != null) { rp.Dispose(); rp = null; } } }
protected void WebRequestCallback(IAsyncResult result) { if (myHttpListener == null) { return; } if (!Active) { return; } try { // Get out the context object HttpListenerContext context = myHttpListener.EndGetContext(result); // *** Immediately set up the next context myHttpListener.BeginGetContext(new AsyncCallback(WebRequestCallback), myHttpListener); RequestProcessor rp = new RequestProcessor(context); rp.UserAgentConnected += new EventHandler <MessageEventArgs>(rp_UserAgentConnected); rp.Run(); rp.Dispose(); rp = null; // done //RPStackSizeChanged(this, new GenericEventArgs<int>(--numberOfRequestProcessors)); } catch (Exception ex) { Functions.WriteLineToLogFile("Exception thrown processing web server request: "); Functions.WriteExceptionToLogFile(ex); } return; }
static void tempMCData_DebugReport(object sender, DebugReportEventArgs e) { // Copied from errorhandler bool logReport = false; if (e.Severity < 10) { if (Settings.Default.DebugAdvanced) { logReport = true; } } if (e.Severity >= 10) { logReport = true; } if (logReport) { Functions.WriteLineToLogFile(e.DebugText); if (e.ThrownException != null) { Functions.WriteExceptionToLogFile(e.ThrownException); } } }
void Object_DebugReport(object sender, DebugReportEventArgs e) { bool logReport = false; if (e.Severity < 10) { if (Settings.Default.DebugAdvanced) { logReport = true; } } if (e.Severity >= 10) { logReport = true; } if (logReport) { Functions.WriteLineToLogFile(e.DebugText); if (e.ThrownException != null) { Functions.WriteExceptionToLogFile(e.ThrownException); } } }
public static void LoadActiveThemeSettings() { string xmlsettings = FileCache.ReadSkinTextFile("settings.xml"); StringReader sr = new StringReader(xmlsettings); XmlReader xr = XmlReader.Create(sr); try { xr.MoveToContent(); while (xr.Read()) { if (xr.Name == "epgtimespan") { EPGManager.TimespanMinutes = xr.ReadElementContentAsInt(); } if (xr.Name == "epgzoomfactor") { EPGManager.EPGScaleFactor = xr.ReadElementContentAsDouble(); } } } catch (Exception e) { Functions.WriteLineToLogFile("Error loading active theme settings:"); Functions.WriteExceptionToLogFile(e); } xr.Close(); sr.Close(); xmlsettings = ""; }
public static string ZipString(string inString) { if (string.IsNullOrEmpty(inString)) return ""; try { if (Settings.Default.DebugServer) Functions.WriteLineToLogFile("Zipping up string of length " + inString.Length + ". Begins:" + inString.Substring(0, 5) + "|Ends:" + inString.Substring(inString.Length - 5)); byte[] buffer = Encoding.UTF8.GetBytes(inString); MemoryStream ms = new MemoryStream(); // Write from buffer => memorystream using (Ionic.Zlib.ZlibStream Zip = new Ionic.Zlib.ZlibStream(ms, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestCompression, true)) { Zip.Write(buffer, 0, buffer.Length); } // Read from memorystream into byte array compressed[] ms.Position = 0; MemoryStream outStream = new MemoryStream(); byte[] compressed = new byte[ms.Length - 1]; ms.Read(compressed, 0, compressed.Length); ms.Close(); return Convert.ToBase64String(compressed); } catch (Exception ex) { Functions.WriteLineToLogFile("ZipHelper: Error zipping string:"); Functions.WriteExceptionToLogFile(ex); } return ""; }
void ipHelper_QueryExternalIPAsync_Completed(object sender, Network.IPHelper.GetExternalIPEventArgs e) { if (e.HasChanged) { Functions.WriteLineToLogFile("DNSHelper: External IP address changed..."); // Update DynDNS DynDnsUpdateResult result = DynDnsUpdateResult.LocalError; try { result = NotifyDynDNS(e.IP); Functions.WriteLineToLogFile("DNSHelper: Notify Dyndns result: " + result.ToString()); } catch (Exception ex) { Functions.WriteLineToLogFile("DNSHelper: Could not notify DynDNS: "); Functions.WriteExceptionToLogFile(ex); } } else { if (Settings.Default.DebugAdvanced) { Functions.WriteLineToLogFile("DNSHelper: External IP address has NOT changed."); } } }
// stop the processing thread public void Stop() { try { if (httpListener != null) { // check if we're listening for a request if (httpListener.IsListening) { // tell the processing thread to exit exitFlag.Set(); // stop listening and kill everything that may be in the queue try { httpListener.Abort(); } catch { } } } } catch { } try { bool foo = Initialization.Default.UnInitialize(); } catch (Exception ex) { Functions.WriteLineToLogFile("Webserver: Error uninitialising:"); Functions.WriteExceptionToLogFile(ex); } }
bool ChangeUrlReservation(int port, string path, bool add, out string txtResult) { // ADD USER ACCOUNT //NTAccount act; SecurityIdentifier sid; try { sid = new SecurityIdentifier("S-1-1-0"); // Everyone } catch (Exception ex) { txtResult = "Couldn't create security identifier for 'Everyone':" + ex.Message; Functions.WriteLineToLogFile("URLReserver: Couldn't create security identifier for 'Everyone':"); Functions.WriteExceptionToLogFile(ex); return(false); } string urlRequired = "http://+:" + port.ToString() + path; Functions.WriteLineToLogFile("URLReserver: Reserving Url " + urlRequired); try { UrlReservation rev = new UrlReservation(urlRequired); Functions.WriteLineToLogFile("URLReserver: Created reservation object."); rev.AddSecurityIdentifier(sid); Functions.WriteLineToLogFile("URLReserver: Added security identifier."); if (add) { Functions.WriteLineToLogFile("URLReserver: Trying to reserve Url..."); rev.Create(); Functions.WriteLineToLogFile("URLReserver: Reserved Url OK."); } else { Functions.WriteLineToLogFile("URLReserver: Trying to remove Url..."); rev.Delete(); Functions.WriteLineToLogFile("URLReserver: Removed Url OK."); } } catch (Exception ex) { txtResult = "Couldn't make reservation object or couldn't add SID: " + ex.Message; Functions.WriteExceptionToLogFile(ex); return(false); } txtResult = "OK"; return(true); }
public WTVStreamingVideoResult StartStreamer(WTVStreamingVideoRequest strq) { int newStreamerID = -1; // Too many streamers? if (mediaStreamers.Count > MAXIMUM_STREAMERS) { Functions.WriteLineToLogFile("DSStreamingManager: too many streamers (" + mediaStreamers.Count.ToString() + " streamers are running, which is above the maximum of " + MAXIMUM_STREAMERS.ToString() + ")"); return(new WTVStreamingVideoResult(DSStreamResultCodes.ErrorTooManyStreamers)); } // For now, some overrides and assumptions if (!File.Exists(strq.FileName)) { Functions.WriteLineToLogFile("WebSvc Start Streaming FAIL: File not found: " + strq.FileName); return(new WTVStreamingVideoResult(DSStreamResultCodes.ErrorFileNotFound)); } try { DSStreamer mediaStreamer = new DSStreamer(); mediaStreamer = new FatAttitude.WTVTranscoder.DSStreamer(); mediaStreamer.Finished += new EventHandler <DSTranscoderBase.ConversionEndedEventArgs>(mediaStreamer_Finished); mediaStreamer.ConversionCompleted += new EventHandler(mediaStreamer_ConversionCompleted); mediaStreamer.DebugMessageGenerated += new EventHandler <DSTranscoderBase.DebugMessageEventArgs>(mediaStreamer_DebugMessageGenerated); Functions.WriteLineToLogFile("DSStreamingManager: DSStreamer object created."); // Which port should we use? int portToTry = GetNextFreePort(); // Try streaming (Async) Functions.WriteLineToLogFileIfSetting(Settings.Default.DebugStreaming, "DSStreamingManager: Attempting to stream using port " + portToTry.ToString()); WTVStreamingVideoResult streamResult = mediaStreamer.StreamWithFileAndPort(strq, portToTry, false, true); if (streamResult.ResultCode == DSStreamResultCodes.OK) { // Add to local streamers newStreamerID = AddNewStreamer(mediaStreamer); mediaStreamer.ID = newStreamerID; // Add streamer ID to result code too streamResult.StreamerID = newStreamerID.ToString(); } // Return return(streamResult); } catch (Exception e) { Functions.WriteLineToLogFile("Exception setting up mediaStreaming object:"); Functions.WriteExceptionToLogFile(e); return(new WTVStreamingVideoResult(DSStreamResultCodes.ErrorExceptionOccurred, "Error setting up mediastreaming object: " + e.Message + " (see server log for more details)")); } }
void RecTV_DebugReport(object sender, DebugReportEventArgs e) { if (!Settings.Default.DebugRecTV) { return; } Functions.WriteLineToLogFile(e.DebugText); if (e.ThrownException != null) { Functions.WriteExceptionToLogFile(e.ThrownException); } }
private static void RecoveryOptions(String Options) { // sc failure [servicename] reset= 0 actions= restart/60000 //Note that you need to include service name in quotation marks, if it contains spaces. bool isRunning; ServiceController svcRP = null; try { svcRP = new ServiceController("Remote Potato Service"); isRunning = (svcRP.Status == ServiceControllerStatus.Running); if (!isRunning) { svcRP.Start(); svcRP.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); } int exitCode; using (var process = new Process()) { var startInfo = process.StartInfo; startInfo.FileName = "sc"; startInfo.WindowStyle = ProcessWindowStyle.Hidden; // tell Windows that the service should restart if it fails startInfo.Arguments = Options; process.Start(); process.WaitForExit(); exitCode = process.ExitCode; process.Close(); } if (exitCode != 0) { throw new InvalidOperationException(); } } catch (Exception ex) { Functions.WriteLineToLogFile("Service: Could not start or stop service:"); Functions.WriteExceptionToLogFile(ex); return; } finally { svcRP = null; } }
public static void LaunchProcessInUserSpace(string cmdName, string Args) { try { // DO IT string commandLine = cmdName + " " + Args; StartProcessInSession(1, commandLine); } catch (Exception ex) { Functions.WriteLineToLogFile("ProcessLaunchHelper: Exception:"); Functions.WriteExceptionToLogFile(ex); } }
public static void SetBlankPasswordLimitOnMachine(bool limitBlankPasswords) { try { RegistryKey rkLimitBlankPassUse = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Lsa\\", true); int setValue = limitBlankPasswords ? 1 : 0; rkLimitBlankPassUse.SetValue("LimitBlankPasswordUse", setValue); } catch (Exception e) { Functions.WriteLineToLogFile("Error setting LimitBlankPasswordUse registry value"); Functions.WriteExceptionToLogFile(e); } }
public void StartServer(int usePort) { if (Active) { return; } if (myHttpListener == null) { myHttpListener = new HttpListener(); } try { // Start listening myHttpListener.Prefixes.Clear(); myHttpListener.Prefixes.Add("http://+:" + Settings.Default.Port.ToString() + "/"); if (Settings.Default.RequirePassword) { myHttpListener.AuthenticationSchemes = AuthenticationSchemes.Basic; } // Try to make active myHttpListener.Start(); IAsyncResult result = myHttpListener.BeginGetContext(new AsyncCallback(WebRequestCallback), myHttpListener); // Now we're active Active = true; ServerStatusChange(this, new MessageEventArgs("Server is running (v" + Functions.VersionText + ")")); spoolMessage("Web Server listening on port " + usePort.ToString()); } catch (Exception e) { myHttpListener = null; Functions.WriteLineToLogFile("Webserver: Could not start:"); Functions.WriteExceptionToLogFile(e); ServerStatusChange(this, new MessageEventArgs("Server is stopped (v" + Functions.VersionText + ")")); if (e.Message.ToLower().Contains("denied")) { if (AccessDenied != null) { AccessDenied(this, new EventArgs()); } } } }
void mediaStreamer_DebugMessageGenerated(object sender, DSTranscoderBase.DebugMessageEventArgs e) { if (!Settings.Default.DebugBasic) { return; } if ((e.Severity < 10) && (!Settings.Default.DebugStreaming)) { return; // ignore non-severe unless advanced debug is on } Functions.WriteLineToLogFile("Video Streamer: " + e.DebugMessage); if (e.HasException) { Functions.WriteExceptionToLogFile(e.InnerException); } }
public static bool ResizePicture(byte[] inputData, Size size, out byte[] outputData, bool allowGrowth) { outputData = new byte[] {}; try { Image imgLogo = ByteArrayToImage(inputData); Image imgLogoResized = resizeImage(imgLogo, size, allowGrowth); outputData = ImageToByteArray(imgLogoResized); return(true); } catch (Exception ex) { Functions.WriteLineToLogFile("Error resizing image: "); Functions.WriteExceptionToLogFile(ex); return(false); } }
public static string EncodeToBase64(string strToEncode, Encoding _encoding) { string returnValue = ""; try { byte[] encodedData = _encoding.GetBytes(strToEncode); returnValue = Convert.ToBase64String(encodedData); } catch (Exception ex) { Functions.WriteLineToLogFile("Couldn't encode base64 string " + strToEncode); Functions.WriteExceptionToLogFile(ex); } return(returnValue); }
public static List <TVService> ChannelListFromString(string txtChannelList) { List <TVService> theChannels = new List <TVService>(); try { XmlSerializer serializer = new XmlSerializer(theChannels.GetType()); StringReader sr = new StringReader(txtChannelList); theChannels = (List <TVService>)serializer.Deserialize(sr); } catch (Exception e) { Functions.WriteLineToLogFile("Error de-serialising channel list:"); Functions.WriteExceptionToLogFile(e); } return(theChannels); }
// Events I can raise //public static event EventHandler<CommonEPG.DebugReportEventArgs> DebugReport; // Constructor / Init static GuideInfo() { // Init variables CachedScheduleRequests = new List <ScheduleRequest>(); _cachedScheduledEventNames = new Dictionary <string, string>(); try { es = new EventSchedule(); EventScheduleExists = true; } catch (Exception e) { EventScheduleExists = false; Functions.WriteExceptionToLogFile(e); } }
public static bool WriteTextFileToDisk(string filePath, string txtContent) { filePath = ConvertRelativePathToAbsolute(filePath); try { TextWriter tw = new StreamWriter(filePath); tw.Write(txtContent); tw.Close(); return(true); } catch (Exception e) { Functions.WriteLineToLogFile("Could not write file " + filePath + " to disk:"); Functions.WriteExceptionToLogFile(e); return(false); } }
public static string DecodeFromBase64(string encodedData, Encoding _encoding) { string returnValue = ""; try { byte[] encodedDataAsBytes = Convert.FromBase64String(encodedData); returnValue = _encoding.GetString(encodedDataAsBytes); } catch (Exception ex) { Functions.WriteLineToLogFile("Couldn't decode base64 string " + encodedData); Functions.WriteExceptionToLogFile(ex); } return(returnValue); }
public static List <string> StringListFromXML(string theXML) { List <string> output = new List <string>(); XmlSerializer serializer = new XmlSerializer(output.GetType()); StringReader sr = new StringReader(theXML); try { return((List <string>)serializer.Deserialize(sr)); } catch (Exception ex) { Functions.WriteLineToLogFile("Could not deserialise list of strings."); Functions.WriteExceptionToLogFile(ex); } return(output); }
static bool StartorStopRemotePotatoService(bool start) { // Services bool isRunning; ServiceController svcRP = null; try { svcRP = new ServiceController("Remote Potato Service"); isRunning = (svcRP.Status == ServiceControllerStatus.Running); if (start) { if (!isRunning) { svcRP.Start(); svcRP.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); return(svcRP.Status == ServiceControllerStatus.Running); // return false if didn't start } } else { if (isRunning) { svcRP.Stop(); svcRP.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); return(svcRP.Status == ServiceControllerStatus.Stopped); // return false if didn't stop } } } catch (Exception ex) { Functions.WriteLineToLogFile("Service: Could not start or stop service:"); Functions.WriteExceptionToLogFile(ex); return(false); } finally { svcRP = null; } return(false); }
public byte[] ThumbnailForWMPItemAsByte(string WMPMatchAttribute, string itemID, bool useFolderArtIfFound, Thumbnail_Sizes size, out string MimeType) { Bitmap bmp = ThumbnailForWMPItem(WMPMatchAttribute, itemID, useFolderArtIfFound, size, out MimeType); if (bmp == null) { return(null); } try { byte[] bytes = (byte[])TypeDescriptor.GetConverter(bmp).ConvertTo(bmp, typeof(byte[])); return(bytes); } catch (Exception ex) { Functions.WriteLineToLogFile("Exception converting WMP item thumbnail to bytes:"); Functions.WriteExceptionToLogFile(ex); } return(null); }
void RemoveStreamer(DSStreamer ms) { if (ms != null) { CleanupDSStreamerFiles(ms); mediaStreamers.Remove(ms.ID); try { ms.Dispose(); ms = null; } catch (Exception ex) { Functions.WriteLineToLogFile("Couldn't dispose DSStreamer:"); Functions.WriteExceptionToLogFile(ex); } } // Power options SetPowerOptions(); }
public static bool CreateZipFileFromFiles(List<string> inputFiles, string outputFile) { try { using (ZipFile zip = new ZipFile()) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; zip.FlattenFoldersOnExtract = true; zip.AddFiles(inputFiles, false, ""); zip.Save(outputFile); } } catch (Exception ex) { Functions.WriteLineToLogFile("Could not create zip file."); Functions.WriteExceptionToLogFile(ex); return false; } return true; }
public static string ReadTextFileFromDisk(string filePath) { filePath = ConvertRelativePathToAbsolute(filePath); string input; try { StreamReader sr; sr = File.OpenText(filePath); input = sr.ReadToEnd(); sr.Close(); return(input); } catch (Exception e) { Functions.WriteLineToLogFile("Could not read file " + filePath + " from disk:"); Functions.WriteExceptionToLogFile(e); } return(""); }
public static bool ResizePicture(string inputFilename, Size size, out byte[] outputData, ImageFormat format, bool allowGrowth) { outputData = new byte[] { }; try { Image imgLogo = Image.FromFile(inputFilename); Image imgLogoResized = resizeImage(imgLogo, size, allowGrowth); outputData = ImageToByteArray(imgLogoResized, format); return(true); } catch (FileNotFoundException) { Functions.WriteLineToLogFile("Error resizing image " + inputFilename + ": File Not Found"); return(false); } catch (Exception ex) { Functions.WriteLineToLogFile("Error resizing image " + inputFilename + ":"); Functions.WriteExceptionToLogFile(ex); return(false); } }
/// <summary> /// Store a keyed dictionary of scheduled events, keyed by name and start time /// </summary> /// <param name="_startWindow"></param> /// <param name="_endWindow"></param> /// <param name="_state"></param> /// <returns></returns> public static bool CacheRedDotRecordingsForDateRange(DateTime _startWindow, DateTime _endWindow, ScheduleEventStates _state) { if (!EventScheduleExists) { return(false); } _cachedScheduledEventNames.Clear(); ICollection <ScheduleEvent> events = es.GetScheduleEvents(_startWindow, _endWindow, _state); foreach (ScheduleEvent se in events) { try { _cachedScheduledEventNames.Add(se.ToKey(), se.Id); } catch (Exception ex) { Functions.WriteLineToLogFile("Error adding scheduled event to cached list:"); Functions.WriteExceptionToLogFile(ex); } // in case of duplicates etc } return(true); }