public static string GetErrorText(int code) { string rtn = "failed to retrieve text for error " + code.ToString(); try { ProcessStartInfo info = new ProcessStartInfo("net", "helpmsg " + code.ToString()); info.RedirectStandardOutput = true; info.CreateNoWindow = true; info.UseShellExecute = false; Process p = Process.Start(info); StringBuilder sb = new StringBuilder(); while (!p.StandardOutput.EndOfStream) { sb.Append(p.StandardOutput.ReadToEnd()); } rtn = sb.ToString().Replace('\n', ' ').Replace('\r', ' '); } catch (Exception ee) { DebugMessageLogger.LogError(ee); } return(rtn); }
public static System.Windows.Controls.Image DeserializeControlsImageFromHexString(string hex) { try { if (string.IsNullOrEmpty(hex)) { return(null); } int numberOfChars = hex.Length; byte[] jpgdata = new byte[numberOfChars / 2]; for (int i = 0; i < numberOfChars; i += 2) { jpgdata[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); } BitmapDecoder decoder; using (MemoryStream memoryStream = new MemoryStream(jpgdata)) decoder = BitmapDecoder.Create(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); BitmapSource bitmapsource = decoder.Frames[0]; System.Windows.Controls.Image img = new System.Windows.Controls.Image() { Source = bitmapsource }; return(img); } catch (Exception ee) { DebugMessageLogger.LogError(ee); } return(null); }
public static string GetPublicIP() { String direction = "?"; DebugMessageLogger.LogEvent("Requesting External IP Address from http://checkip.dyndns.org/"); try { WebRequest request = WebRequest.Create("http://checkip.dyndns.org/"); using (WebResponse response = request.GetResponse()) using (StreamReader stream = new StreamReader(response.GetResponseStream())) { direction = stream.ReadToEnd(); } //Search for the ip in the html int first = direction.IndexOf("Address: ") + 9; int last = direction.LastIndexOf("</body>"); direction = direction.Substring(first, last - first); DebugMessageLogger.LogEvent("My IP is " + direction); } catch (Exception e) { DebugMessageLogger.LogError(e, "Failed to get IP address. Perhaps Computer is not online"); } return(direction); }
public static void LogSleepData() { //order by most sleep calls //List<string> data = new List<string>(); string data = ""; List <KeyValuePair <string, double> > myList = _sleepCounts.ToList(); myList.Sort( delegate(KeyValuePair <string, double> pair1, KeyValuePair <string, double> pair2) { return(pair1.Value.CompareTo(pair2.Value)); } ); foreach (var kvp in myList) { double tot = _sleepTotalTimes[kvp.Key]; string s = string.Format("SleepCount {0} TotalTime {1} at {2}\n", kvp.Value, tot, kvp.Key); data += s; } foreach (var kvp in _sleephistogram) { data += string.Format("\n{0} - {1}", kvp.Key, kvp.Value); } DebugMessageLogger.LogEvent(data); }
public static void TestTicket(string sourcename, int queuelength, ref bool stopGeneratingFrames) { // Video recording is now a single thread for all imports, and hence has a queue. // This code pauses the imports if the save queue grows beyond a set limit, as the save // queue eats ram. It is designed in a circular ticket system so no one source gets // undue prominence in the save system. // if (queuelength > 2) { DateTime queueEntry = DateTime.Now; DebugMessageLogger.LogEvent("ImportingVideoPlayer.GenerateFrames - Wait Requested Source={0}, Current Queue Length={1}", sourcename, queuelength); int ticket = VQueueTicket_getTicket(); while (!stopGeneratingFrames) { Kinesense.Interfaces.Threading.ThreadSleepMonitor.Sleep(1000); if (queuelength < 4 && VQueueTicket_checkTicket(ticket)) { break; } DebugMessageLogger.LogEventLevel(1, "ImportingVideoPlayer.GenerateFrames - Wait Continues Source={0}, Current Queue Length={1}, Ticket={2}, Been Queuing For {3} seconds", sourcename, queuelength, ticket, (DateTime.Now - queueEntry).TotalSeconds); } if (stopGeneratingFrames) { DebugMessageLogger.LogEventLevel(1, "ImportingVideoPlayer.GenerateFrames - Stop generating requested whilst in queue. Ticket={0} to be surrounded", ticket); VQueueTicket_surrenderTicket(ticket); } } }
public static bool TryDo(Action action, int millisecondsTimeout) { var exceptionHappened = false; var thread = new Thread(() => { try { action(); } catch (Exception ex) { exceptionHappened = true; DebugMessageLogger.LogError(ex); } }); thread.Start(); var completed = thread.Join(millisecondsTimeout); if (!completed || exceptionHappened) { thread.Abort(); return(false); } return(true); }
public byte[] TakeBuffer(int timeout_ms) { byte[] bf = null; int ticket = -1; int waitcount = 0; while (!_buffers.TryDequeue(out bf)) { System.Diagnostics.Debug.WriteLine("Waiting for Buffer {0}, wait count {1}", BufferSize, waitcount); if (ticket == -1) { lock (_countlock) { ticket = _ticketCount++; } } _waiting++; waitcount++; _event.WaitOne(timeout_ms); _waiting--; int diff = ticket - _usedTickets; if (diff > 0) { Kinesense.Interfaces.Threading.ThreadSleepMonitor.Sleep(diff); } if ((waitcount > 3 && BufferCount < MaxBuffers) || (waitcount > 10)) { BufferCount++; DebugMessageLogger.LogEvent("Waiting too long for buffer - making a new one of size {0} ({1}/{2})", this.BufferSize, this.BufferCount, this.MaxBuffers); bf = new byte[this.BufferSize]; break; } } if (ticket != -1) { lock (_countlock) { if (_usedTickets < ticket) { _usedTickets = ticket; } } } MostRecentUse = DateTime.Now; Array.Clear(bf, 0, bf.Length); return(bf); }
public void DropBuffers() { DebugMessageLogger.LogEvent("DropBuffers on {0} Dropping {1} Buffers", this.BufferSize, this.BufferCount); while (_buffers.Count > 0) { byte[] buf = null; _buffers.TryDequeue(out buf); buf = null; } GC.Collect(); }
public byte[] GetFrameData(DateTime time) { byte[] jpgBuffer = null; try { //parse header int pos = -1; if (!_timePosDictionary.TryGetValue(time, out pos)) { return(null); } //Read Frame Header: int linelimit = 0; //content Length string contentLengthString = ByteArrayUtils.GetPrefixedLine( _buffer, ContentLengthPrefix, pos, 400, Encoding.ASCII, out linelimit); //Hash code //string hashString = ByteArrayUtils.GetPrefixedLine( // _buffer, ContentHashPrefix, linelimit, 400, Encoding.ASCII, out linelimit); //string privatehashString = ByteArrayUtils.GetPrefixedLine( // _buffer, ContentPrivateHashPrefix, linelimit, 400, Encoding.ASCII, out linelimit); //use linelimit as start point to copy the jpeg data int contentLength = int.Parse(contentLengthString); //This should work always, but its possible that the bytes 0x00 and 0x10 could be different sometimes. //keep an eye out for weird behaviour. See http://www.garykessler.net/library/file_sigs.html // // Gerrr Mark // //byte[] jpegHeaderpattern = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46 }; byte?[] jpegHeaderpattern = new byte?[] { 0xFF, null, 0xFF, null }; int datastart = ByteArrayUtils.IndexOf(_buffer, jpegHeaderpattern, linelimit, 400); if (datastart == -1) { DebugMessageLogger.LogEvent("Search for jpeg header failed; MultipartVideoDecoder.GetAllFrames()"); } //return bytes jpgBuffer = new byte[contentLength]; Array.Copy(_buffer, datastart, jpgBuffer, 0, contentLength); } catch (Exception ee) { DebugMessageLogger.LogError(ee); } return(jpgBuffer); }
public byte[] ComputeEncodedDataHash(IHashAlgorithmFactory hashAlgorithmFactory, byte[] encodedData) { if (string.IsNullOrEmpty(this.HashAlgorithmName)) { this.HashAlgorithmName = "MD5"; DebugMessageLogger.LogEvent("Frame HashAlgorithmName not set!"); } HashAlgorithm hashAlgorithm = hashAlgorithmFactory.GetHashAlgorithm(this.HashAlgorithmName); return(hashAlgorithm != null?hashAlgorithm.ComputeHash(encodedData) : new byte[] { }); }
public static void SetDefault(string mode) { try { SuggestedAnalysisResolutionMode m = SuggestedAnalysisResolutionMode.Standard128; System.Enum.TryParse(mode, out m); Default = m; } catch (System.Exception ee) { DebugMessageLogger.LogError(ee); } }
public static void VQueueTicket_surrenderTicket(int ticket) { DebugMessageLogger.LogEventLevel("VideoReocorder - Ticket=" + ticket.ToString() + " to be surrended", 1); if (!VQueueTicket_checkTicket(ticket)) { DebugMessageLogger.LogEventLevel("VideoReocorder - Ticket=" + ticket.ToString() + " added to surrended list", 1); _vQueueTicket_surrendedTickets.Add(ticket); } else { DebugMessageLogger.LogEventLevel("VideoReocorder - Ticket=" + ticket.ToString() + " surrended and processed", 1); } }
public static void Do(Action act, string taskname) { try { System.Threading.Thread.CurrentThread.Name = taskname; act.Invoke(); act = null; } catch (Exception ee) { DebugMessageLogger.LogError(ee); } }
/// <summary> /// /// </summary> /// <param name="subName"></param> /// <param name="reason"></param> /// <returns></returns> public static int StartNewExtraLog(string subName, string reason) { try { int newLogNumber = GiveMeALogNumber; Kinesense.Interfaces.DebugMessageLogger.LogEventLevel("DebugMessageLogger_Extra - Starting extra log for [" + reason + "] with log number " + newLogNumber.ToString(), 1); bool GotLock = false; try { Monitor.TryEnter(ExtantLogs_Lock, 2000, ref GotLock); if (!GotLock) { DebugMessageLogger.LogEventLevel("DebugMessageLogger_Extra - Could not get Lock on ExtantLogs Dictionary", 1); return(-1); } LogData LD = new LogData(); LD.number = newLogNumber; LD.fullName = DebugMessageLogger.CurrentLogFile; LD.fullName = LD.fullName.Remove(LD.fullName.Length - 4, 4); LD.fullName = LD.fullName + "-EXTRA(" + newLogNumber.ToString("000") + ")-" + subName + ".log"; ExtantLogs.Add(newLogNumber, LD); WriteToFileWithTime("---------- LOG STARTED ----------" + " REASON: (" + reason + ")", LD.fullName); } catch (Exception ker) { Kinesense.Interfaces.DebugMessageLogger.LogError(ker); } finally { if (GotLock) { Monitor.Exit(ExtantLogs_Lock); } } return(newLogNumber); } catch (Exception ker) { Kinesense.Interfaces.DebugMessageLogger.LogError(ker); return(-1); } }
public static Action WrapAction(Action action) { return(new Action(() => { try { action.Invoke(); } catch (Exception ee) { DebugMessageLogger.LogError(ee); } })); }
public static void Do(Dispatcher dispatcher, Action act) { dispatcher.BeginInvoke(new Action(() => { try { act.Invoke(); act = null; } catch (Exception ee) { DebugMessageLogger.LogError(ee); } })); }
public byte[] GetBuffer(long length) { if (!BufferManagerOn) { return(new byte[length]); } byte[] buffer = null; if (Sizes.Count == 0) { PopulateSizes(); } try { if (length > _bufferSizeTestThreshold) { _countAllocations++; if (_countAllocations % _testMemoryFrequency == 0) { double d = this.ProcessMemoryLoad(); if (d > 50) { DebugMessageLogger.LogEvent("BufferManager. Process Memory Load is {0}%, introducing a short sleep", d); Kinesense.Interfaces.Threading.ThreadSleepMonitor.Sleep((int)d); } } } long size = GetClosestBuffer(length, BufferNeededFor.Allocation); buffer = _bufferManagers[size].TakeBuffer(50); //foreach(byte b in buffer) // if (b != 0) // { // } } catch (Exception ee) { DebugMessageLogger.LogError(ee); } return(buffer); }
void TestBuffersAndDropOldOnes() { try { foreach (var buf in _bufferManagers) { if ((DateTime.Now - buf.Value.MostRecentUse).TotalMinutes > 10) { buf.Value.DropBuffers(); } } } catch (Exception ee) { DebugMessageLogger.LogError(ee); } }
public static void DoTaskThenDispatch(Action act, string actionname, Dispatcher dispatcher, Action dispatchThisAction) { Task.Factory.StartNew(() => { try { System.Threading.Thread.CurrentThread.Name = actionname; act.Invoke(); act = null; } catch (Exception ee) { DebugMessageLogger.LogError(ee); } Do(dispatcher, dispatchThisAction); }); }
/// <summary> /// /// </summary> public static void EndAllRemainingLogs() { try { bool GotLock = false; List <int> keys = new List <int>(); DebugMessageLogger.LogEventLevel("DebugMessageLogger_Extra - Ending all remaining logs", 1); try { Monitor.TryEnter(ExtantLogs_Lock, 2000, ref GotLock); if (!GotLock) { DebugMessageLogger.LogEventLevel("DebugMessageLogger_Extra - Could not get Lock on ExtantLogs Dictionary", 1); return; } keys = new List <int>(ExtantLogs.Keys); DebugMessageLogger.LogEventLevel("DebugMessageLogger_Extra - Ending all remaining logs - " + keys.Count.ToString() + " found to end", 1); } catch (Exception ker) { Kinesense.Interfaces.DebugMessageLogger.LogError(ker); } finally { if (GotLock) { Monitor.Exit(ExtantLogs_Lock); } } foreach (int i in keys) { EndExtraLog(i); } } catch (Exception ker) { Kinesense.Interfaces.DebugMessageLogger.LogError(ker); } }
public static void DoImmediatelyAndWait(Dispatcher dispatcher, Action act) { AutoResetEvent ev = new AutoResetEvent(false); dispatcher.Invoke(new Action(() => { try { act.Invoke(); ev.Set(); act = null; } catch (Exception ee) { DebugMessageLogger.LogError(ee); } })); ev.WaitOne(); }
public static void DoTaskAndWait(Action act, string taskname) { AutoResetEvent ev = new AutoResetEvent(false); Task.Factory.StartNew(() => { try { System.Threading.Thread.CurrentThread.Name = taskname; act.Invoke(); ev.Set(); act = null; } catch (Exception ee) { DebugMessageLogger.LogError(ee); } }); ev.WaitOne(); }
public static void LogToExtraLog(int number, string ToLog) { try { bool GotLock = false; try { Monitor.TryEnter(ExtantLogs_Lock, 2000, ref GotLock); if (!GotLock) { DebugMessageLogger.LogEventLevel("DebugMessageLogger_Extra - Could not get Lock on ExtantLogs Dictionary", 1); return; } if (!ExtantLogs.ContainsKey(number)) { DebugMessageLogger.LogEventLevel("DebugMessageLogger_Extra - Could not find extra log number in ExtantLogs Dictionary - (" + number.ToString() + ")", 1); return; } WriteToFileWithTime(ToLog, ExtantLogs[number].fullName); } catch (Exception ker) { Kinesense.Interfaces.DebugMessageLogger.LogError(ker); } finally { if (GotLock) { Monitor.Exit(ExtantLogs_Lock); } } } catch (Exception ker) { Kinesense.Interfaces.DebugMessageLogger.LogError(ker); } }
public byte[] ConvertJpegDataToMJpegByteArray() { byte[] buffer = null; try { //sort by time, ascending _jpegDataIndex.Sort(new IndexEntryComparer()); using (MemoryStream memoryStream = new MemoryStream()) using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { foreach (KeyValuePair <DateTime, byte[]> kvp in _jpegDataIndex) { ///debug _countExported++; if (kvp.Value != null) { binaryWriter.Write( Encoding.ASCII.GetBytes( string.Format(DatabaseFramePacketWrapper.FrameHeaderFormat, kvp.Value.Length, kvp.Key))); binaryWriter.Write(kvp.Value); } //memoryStream.WriteTo(binaryWriter.BaseStream); } buffer = memoryStream.ToArray(); } } catch (OutOfMemoryException ee) { throw; } catch (Exception ee) { DebugMessageLogger.LogError(ee); } return(buffer); }
/// <summary> /// Gets the internal IP address /// </summary> /// <returns></returns> public static string GetLocalIP() { IPHostEntry host; string localIP = "?"; try { host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); } } } catch (Exception ee) { DebugMessageLogger.LogError(ee, "Failed to get IP address. Perhaps Computer is not online"); } return(localIP); }
public static void MonitorDo(Dispatcher dispatcher, Action act, object monitorObj, int timeout) { if (Monitor.TryEnter(monitorObj, timeout)) { AutoResetEvent ev = new AutoResetEvent(false); dispatcher.BeginInvoke(new Action(() => { try { act.Invoke(); act = null; ev.Set(); } catch (Exception ee) { DebugMessageLogger.LogError(ee); } })); ev.WaitOne(); Monitor.Exit(monitorObj); } }
public static bool TryDo <T>(Func <T> fun, int millisecondsTimeout, out T result) { var tResult = default(T); var exceptionHappened = false; var thread = new Thread(() => { try { tResult = fun(); } catch (ThreadAbortException ex) { exceptionHappened = true; DebugMessageLogger.LogEvent("SaveActionHelper TryDo Timeout"); DebugMessageLogger.LogError(ex); } catch (Exception ex) { exceptionHappened = true; DebugMessageLogger.LogError(ex); } }); thread.Start(); var completed = thread.Join(millisecondsTimeout); result = tResult; if (!completed || exceptionHappened) { thread.Abort(); return(false); } return(true); }
public static void Sleep(double ms) { #if DEBUG1 try { lock (_sleeploglock) { string stacktrace = new StackTrace().ToString(); if (!_sleepCounts.ContainsKey(stacktrace)) { _sleepCounts.Add(stacktrace, 1); } else { _sleepCounts[stacktrace]++; } if (!_sleepTotalTimes.ContainsKey(stacktrace)) { _sleepTotalTimes.Add(stacktrace, ms); } else { _sleepTotalTimes[stacktrace] += ms; } if (!_sleeplog.ContainsKey(stacktrace)) { _sleeplog.Add(stacktrace, new List <DateTime> { DateTime.Now }); } else { _sleeplog[stacktrace].Add(DateTime.Now); } _SleepCount++; if (_SleepCount % 1000 == 0) { LogSleepData(); } if (_sleephistogram.ContainsKey((int)ms)) { _sleephistogram[(int)ms]++; } else { _sleephistogram.Add((int)ms, 1); } } } catch (Exception ee) { DebugMessageLogger.LogError(ee); } #endif if (TurnOffSleeps) { return; } //if (ms <= 500) // return; Thread.Sleep((int)ms); }