Beispiel #1
0
        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 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 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 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 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 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);
     }
 }
Beispiel #7
0
 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);
     }
 }
Beispiel #8
0
 public static Action WrapAction(Action action)
 {
     return(new Action(() =>
     {
         try
         {
             action.Invoke();
         }
         catch (Exception ee)
         {
             DebugMessageLogger.LogError(ee);
         }
     }));
 }
Beispiel #9
0
 public static void Do(Dispatcher dispatcher, Action act)
 {
     dispatcher.BeginInvoke(new Action(() =>
     {
         try
         {
             act.Invoke();
             act = null;
         }
         catch (Exception ee)
         {
             DebugMessageLogger.LogError(ee);
         }
     }));
 }
Beispiel #10
0
        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);
        }
Beispiel #11
0
 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);
     }
 }
Beispiel #12
0
        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);
            });
        }
Beispiel #13
0
        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();
        }
Beispiel #14
0
        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 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);
        }
Beispiel #16
0
 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);
     }
 }
        /// <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);
        }
Beispiel #18
0
        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);
        }