Exemplo n.º 1
0
        /// <summary>
        /// Returns current BitmaapSource scaled below the given dimensions
        /// WILL NOT store if it has to build it on the fly
        /// </summary>
        public BitmapSource BitmapSourceScaledToBelow(int width, int height)
        {
            try
            {
                ByteArrayBitmap bab;
                if (this._bitmap != null)
                {
                    bab = this._bitmap;
                }
                else
                {
                    bab = TryToDecodeEncodedData();
                    if (bab == null)
                    {
                        return(null);
                    }
                }

                return(bab.ToBitmapSourceScaledToBelow(width, height));
            }
            catch (Exception er)
            {
                DebugMessageLogger.LogError(er);
                return(null);
            }
        }
Exemplo n.º 2
0
        public bool ZipAsync(string[] files, string outputFile, ZipAsyncCallback callback)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("a -tzip \"{0}\"", outputFile);
                foreach (string file in files)
                {
                    sb.AppendFormat(" \"{0}\"", file);
                }

                _ZipAsyncCallback = callback;

                DebugMessageLogger.LogEventLevel("Running: {0} {1}", 0, exeLoc, sb.ToString());
                ProcessStartInfo info = new ProcessStartInfo(exeLoc, sb.ToString());
                info.RedirectStandardOutput = true;
                info.CreateNoWindow         = true;
                info.UseShellExecute        = false;
                _ZipProcess = Process.Start(info);
                _reader     = _ZipProcess.StandardOutput;


                _ZipAsyncProcessCommandlineReader      = new Thread(new ThreadStart(ProcessOutputReader));
                _ZipAsyncProcessCommandlineReader.Name = "Z7a.exe process commandline reader";
                _ZipAsyncProcessCommandlineReader.Start();

                return(true);
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(false);
        }
Exemplo n.º 3
0
        private ByteArrayBitmap TryToDecodeEncodedData()
        {
            try
            {
                if (this.EncodedData == null)
                {
                    return(null);
                }

                BitmapDecoder decoder;
                using (MemoryStream memoryStream = new MemoryStream(this.EncodedData))
                    decoder = BitmapDecoder.Create(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                BitmapFrame bitmapFrame = decoder.Frames[0];
                return(new ByteArrayBitmap(bitmapFrame));

                string[] mimeTypes = decoder.CodecInfo.MimeTypes.Split(',');
                if (mimeTypes.Length > 0)
                {
                    this.EncodedDataContentType = new ContentType(mimeTypes[0]);
                }
                // log access for drop on age calc
                _lastDecodedDataAccess = DateTime.Now;

                TrySetWidthHeight();
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
                return(null);
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// immediately logs exception, including DateTime.Now timestamp, if the level of logging is high enough
 /// </summary>
 /// <param name="e"></param>
 public static void LogError(Exception e, int logLevel)
 {
     if (logLevel <= ErrorLogLevel)
     {
         DebugMessageLogger.LogError(e, null, logLevel);
     }
 }
Exemplo n.º 5
0
        public static void LogMemAndLinenumber()
        {
            StackFrame st        = new StackFrame(1, true);
            float      privateMB = Process.GetCurrentProcess().PrivateMemorySize64 / 1000000f;

            DebugMessageLogger.LogEvent("Memory Use {0}mb at {1}", privateMB, st);
        }
        public static int CountJpegsFrames(string filename)
        {
            int count = 0;

            try
            {
                int     batchsize         = 1000;
                int     linelimit         = 0;
                byte?[] jpegHeaderpattern =
                    new byte?[] { 0x69, 0x6D, 0x61, 0x67, 0x65, 0x2F, 0x6A, 0x70, 0x65, 0x67 };
                //new byte?[] { 0x43, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x2D, 0x6C, 0x65, 0x6E, 0x67, 0x74, 0x68, 0x3A };
                //new byte?[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46 };
                //new byte?[]{0x2D, 0x2D, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x62, 0x6F, 0x75, 0x6E, 0x64, 0x61, 0x72, 0x79};
                //new byte?[] { 0xFF, null, 0xFF, null };
                byte[] buffer = new byte[batchsize];
                using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open, FileAccess.Read)))
                {
                    while (br.BaseStream.Length > br.BaseStream.Position)
                    {
                        int datastart = ByteArrayUtils.IndexOf(buffer, jpegHeaderpattern, linelimit, batchsize);
                        if (datastart != -1)
                        {
                            count++;
                        }
                        Array.Copy(br.ReadBytes(batchsize), buffer, batchsize);
                    }
                }
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }
            return(count);
        }
Exemplo n.º 7
0
        public bool ZipFolder(string folder, string outputFile)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("a -tzip \"{0}\"", outputFile);
                sb.AppendFormat(" \"{0}\"", folder);

                //_ZipAsyncCallback = callback;

                DebugMessageLogger.LogEventLevel("Running: {0} {1}", 0, exeLoc, sb.ToString());
                ProcessStartInfo info = new ProcessStartInfo(exeLoc, sb.ToString());
                info.RedirectStandardOutput = true;
                info.CreateNoWindow         = true;
                info.UseShellExecute        = false;
                _ZipProcess = Process.Start(info);
                _reader     = _ZipProcess.StandardOutput;

                ProcessOutputReader();

                return(true);
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(false);
        }
Exemplo n.º 8
0
        private void ProcessOutputReader()
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                while (_continueReading && !_reader.EndOfStream)
                {
                    try
                    {
                        char[] block = new char[100];
                        _reader.ReadBlock(block, 0, 100);
                        string currentblock = new string(block);
                        //string line = previousblock + currentblock;
                        if (currentblock != null)
                        {
                            sb.AppendFormat("{0}", currentblock);
                        }
                    }
                    catch (Exception ee)
                    {
                        DebugMessageLogger.LogError(ee);
                    }
                }
            }
            catch (Exception eee)
            {
                DebugMessageLogger.LogError(eee);
            }

            if (_ZipAsyncCallback != null)
            {
                _ZipAsyncCallback(sb.ToString());
            }
        }
Exemplo n.º 9
0
        public void Save(string path, System.Drawing.Imaging.ImageFormat format)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(this._CompressedData))
                {
                    Bitmap bmp = new Bitmap(ms);

                    bmp.Save(path, format);

                    //Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                    //System.Drawing.Imaging.BitmapData bmpData =
                    //    bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                    //    bmp.PixelFormat);

                    //// Get the address of the first line.
                    //IntPtr ptr = bmpData.Scan0;

                    //// Declare an array to hold the bytes of the bitmap.
                    //int bytes = bmpData.Stride * bmp.Height;

                    //System.Runtime.InteropServices.Marshal.Copy(Data, 0, ptr, bytes);

                    //// Unlock the bits.
                    //bmp.UnlockBits(bmpData);
                }
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }
        }
        public static string InsertLinebreaks(string text, int lineCharLength, char[] breakat)
        {
            try
            {
                if (String.IsNullOrEmpty(text))
                {
                    return("");
                }

                if (text.Length <= lineCharLength)
                {
                    return(text);
                }

                int        searchBack    = 5;
                int        searchForward = 5;
                List <int> breakPos      = new List <int>();

                for (int i = lineCharLength; i < text.Length; i += lineCharLength)
                {
                    //word wrap code.
                    int pos = text.IndexOfAny(breakat, i - searchBack, searchForward);
                    if (pos == -1)
                    {
                        pos = i;
                    }
                    breakPos.Add(pos);
                }
                breakPos.Add(text.Length);

                string[] lines = new string[breakPos.Count];
                int      prev  = 0;
                for (int i = 0; i < breakPos.Count; i++)
                {
                    lines[i] = text.Substring(prev, breakPos[i] - prev).TrimStart(' ', '\t');
                    prev     = breakPos[i];
                }

                string output = lines[0];
                if (lines.Length > 1)
                {
                    for (int i = 1; i < lines.Length; i++)
                    {
                        output += "\n" + lines[i];
                    }
                }

                return(output);
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(text);
        }
        /// <summary>
        /// This method looks for the index at the end of the frame packet. This should be in the format DateTime.Int
        /// following a final "--videoboundary"
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="stampA"></param>
        /// <param name="stampB"></param>
        /// <returns></returns>
        public static List <KeyValuePair <DateTime, int> > GetTimeStampsFromFrameIndex(byte[] buffer)
        {
            List <KeyValuePair <DateTime, int> > times = new List <KeyValuePair <DateTime, int> >();
            long utcmask       = ((long)DateTimeKind.Utc << 62);
            long localantimask = ~((long)DateTimeKind.Local << 62);

            long unspmask = ~((long)3 << 62);

            try
            {
                ASCIIEncoding encoder    = new ASCIIEncoding();
                string        stamp      = "--videoboundary--";
                byte[]        stampbytes = encoder.GetBytes(stamp);

                int index_of_index = -1;
                int pos            = buffer.Length;

                while (index_of_index == -1 && pos > 0)
                {
                    pos           -= 5000;
                    index_of_index = ByteArrayUtils.IndexOf(buffer, stampbytes, pos, buffer.Length - pos);
                }
                if (index_of_index == -1)
                {
                    throw new IOException("Invalid buffer");
                }

                pos = index_of_index + stampbytes.Length;
                while (pos < buffer.Length - 12)
                {
                    long bytes = BitConverter.ToInt64(buffer, pos);
                    //bytes = bytes | utcmask;
                    //bytes = bytes & localantimask;
                    bytes = bytes & unspmask;
                    DateTime time = DateTime.FromBinary(bytes);

                    //this fixes the timezone issue
                    time = ChangeDateTimeKind(time, DateTimeKind.Utc);

                    int bytepos = BitConverter.ToInt32(buffer, pos + 8);

                    //sometimes there are blank bytes at the end of the file. Don't record these as index entries.
                    //if (bytepos > 0)
                    times.Add(new KeyValuePair <DateTime, int>(time, bytepos));

                    pos += 12;
                }
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(times);
        }
Exemplo n.º 12
0
 public static void StopDiagnosticMode()
 {
     try
     {
         _recordMemUsageRegularly = false;
         _diagnosticMemoryThread.Join();
     }
     catch (Exception ee)
     {
         DebugMessageLogger.LogError(ee);
     }
 }
Exemplo n.º 13
0
        public string[] ZipFolder(string folder, string outputFile, int MaxSizeMB)
        {
            string[] list = new string[0];

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("a -tzip \"{0}\" -v{1}m", outputFile, MaxSizeMB);
                sb.AppendFormat(" \"{0}\"", folder);

                //_ZipAsyncCallback = callback;

                DebugMessageLogger.LogEventLevel("Running: {0} {1}", 0, exeLoc, sb.ToString());
                ProcessStartInfo info = new ProcessStartInfo(exeLoc, sb.ToString());
                info.RedirectStandardOutput = true;
                info.CreateNoWindow         = true;
                info.UseShellExecute        = false;
                _ZipProcess = Process.Start(info);
                _reader     = _ZipProcess.StandardOutput;

                ProcessOutputReader();

                //find all files in the format outputFile.???
                var        d     = new DirectoryInfo(Path.GetDirectoryName(outputFile));
                FileInfo[] infos = d.GetFiles(Path.GetFileName(outputFile) + ".*");

                list = new string[infos.Length];

                if (infos.Length == 1)
                {
                    File.Move(infos[0].FullName, outputFile);
                    list[0] = outputFile;
                }
                else
                {
                    for (int i = 0; i < infos.Length; i++)
                    {
                        list[i] = infos[i].FullName;
                    }
                }

                DebugMessageLogger.LogEvent("Z7Wrapper - Zip Folder {0} to {1} Files of limit {2}MB", folder, list.Length, MaxSizeMB);

                return(list);
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(list);
        }
Exemplo n.º 14
0
        public static string VersionTo2CharCode(Version ver)
        {
            try
            {
                return(string.Format("{0}{1}", ConvIntToLowerCase(ver.Build), ConvIntToLowerCase(ver.Revision)));
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return("-");
        }
        public static bool GetDimensionsOfImageFromJpegData(byte[] jpegdata, out int width, out int height)
        {
            bool success = false;

            width  = 0;
            height = 0;
            int loc = 0;

            try
            {
                int trys = 0;
                while (success == false && loc != -1 && loc < 2000 && trys < 20)
                {
                    loc = ByteArrayUtils.IndexOf(jpegdata, new byte[] { 0xFF, 0xC0 }, loc, 2000);

                    if (loc > 0)
                    {
                        byte[] heightbyte = new byte[] { jpegdata[loc + 6], jpegdata[loc + 5] }; //make BigEndian
                        byte[] widthbyte  = new byte[] { jpegdata[loc + 8], jpegdata[loc + 7] };

                        height = BitConverter.ToInt16(heightbyte, 0);

                        width = BitConverter.ToInt16(widthbyte, 0);

                        if (height > 0 && height < 65535 &&
                            width > 0 && width < 65535)
                        {
                            success = true;
                        }
                        else
                        {
                            success = false;
                            loc    += 2;
                            trys++;
                        }
                    }
                }

                if (success == false)
                {
                    DebugMessageLogger.LogEvent("Failed to recover good height ({0}) and width ({1}) from jpeg data. Tried {2} times", width, height, trys);
                }
            }
            catch (Exception ee)
            {
                success = false;
                DebugMessageLogger.LogError(ee);
            }

            return(success);
        }
Exemplo n.º 16
0
 public void UnZip(string file, string outputfolder)
 {
     try
     {
         ProcessStartInfo info = new ProcessStartInfo(exeLoc, string.Format("e {0} {1}", file, outputfolder));
         // info.RedirectStandardOutput = true;
         //info.CreateNoWindow = true;
         // info.UseShellExecute = false;
         _ZipProcess = Process.Start(info);
         _ZipProcess.WaitForExit(4000);
     }
     catch (Exception ee)
     {
         DebugMessageLogger.LogError(ee);
     }
 }
Exemplo n.º 17
0
 public static void LogProcessOutput(Process proc, string name)
 {
     try
     {
         LogEvent(String.Format("{0} Started", name));
         while (!proc.StandardOutput.EndOfStream)
         {
             LogEvent(String.Format("{0} Command Line: {1}", name, proc.StandardOutput.ReadLine()));
         }
         LogEvent(String.Format("{0} Ended", name));
     }
     catch (Exception ee)
     {
         DebugMessageLogger.LogError(ee);
     }
 }
Exemplo n.º 18
0
        public static void LogTeamviewerID()
        {
            try
            {
                var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
                    @"SOFTWARE\Wow6432Node\TeamViewer");

                foreach (var subkeyname in key.GetSubKeyNames())
                {
                    var subkey   = key.OpenSubKey(subkeyname);
                    var clientID = subkey.GetValue("ClientID");
                    DebugMessageLogger.LogEvent("Teamviewer {0} Client ID: {1}", subkeyname, clientID);
                }
            }
            catch (Exception ee)
            {
            }
        }
Exemplo n.º 19
0
        public static void StartDiagnosticMode()
        {
            try
            {
                _recordMemUsageRegularly = false;
                try
                {
                    if (_diagnosticMemoryThread != null)
                    {
                        _diagnosticMemoryThread.Abort();
                    }
                }
                catch (Exception eeee)
                {
                }
                _recordMemUsageRegularly = true;

                _diagnosticMemoryThread = new Thread(new ThreadStart(() =>
                {
                    try
                    {
                        while (_recordMemUsageRegularly)
                        {
                            long totmem     = GC.GetTotalMemory(true);
                            float privateMB = Process.GetCurrentProcess().PrivateMemorySize64 / 1000000f;
                            DebugMessageLogger.LogEvent("Diagnostic Mode: Private Bytes Usage: {0} MB, GC: {1} MB",
                                                        privateMB.ToString("n"),
                                                        (totmem / 1000000f).ToString("n"));

                            Kinesense.Interfaces.Threading.ThreadSleepMonitor.Sleep(10000);
                        }
                    }
                    catch (Exception eee)
                    {
                        DebugMessageLogger.LogError(eee);
                    }
                }));
                _diagnosticMemoryThread.Start();
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }
        }
Exemplo n.º 20
0
        protected byte[] Decompress()
        {
            byte[] data = null;
            try
            {
                BitmapDecoder decoder;
                using (MemoryStream memoryStream = new MemoryStream(_CompressedData))
                    decoder = BitmapDecoder.Create(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                BitmapFrame bitmapFrame = decoder.Frames[0];

                data = new ByteArrayBitmap(bitmapFrame).Data;
                //bitmapFrame.CopyPixels(data, this.Stride, 0);
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }
            return(data);
        }
Exemplo n.º 21
0
        private void TryToDecodeEncodedDataTo_bitmap()
        {
            try
            {
                lock (_disposelock)
                {
                    if (Disposed)
                    {
                        return;
                    }

                    using (MemoryStream memoryStream = new MemoryStream(this.EncodedData))
                    {
                        System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(memoryStream);
                        _bitmap = ByteArrayBitmap.FromBitmapForce4bpp(bmp);
                    }

                    //this was the way it was done in 2.5 and below
                    //BitmapDecoder decoder;
                    //using (MemoryStream memoryStream = new MemoryStream(this.EncodedData))
                    //    decoder = BitmapDecoder.Create(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                    //BitmapFrame bitmapFrame = decoder.Frames[0];
                    //_bitmap = new ByteArrayBitmap(bitmapFrame);

                    //string[] mimeTypes = decoder.CodecInfo.MimeTypes.Split(',');
                    //if (mimeTypes.Length > 0)
                    //   this.EncodedDataContentType = new ContentType(mimeTypes[0]);
                    // log access for drop on age calc

                    this.EncodedDataContentType = new ContentType("image/jpeg");
                    _lastDecodedDataAccess      = DateTime.Now;

                    TrySetWidthHeight();
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("No Bitmap and No EncodedData: {0}.{1}", DBTime, DBTime.Millisecond));
                DebugMessageLogger.LogError(ee);
                _bitmap = null;
            }
        }
Exemplo n.º 22
0
 public void Rotate(System.Drawing.RotateFlipType rotate)
 {
     try
     {
         System.Drawing.Bitmap B = this.Bitmap.ToBitmap();
         B.RotateFlip(rotate);
         using (MemoryStream memoryStream = new MemoryStream())
         {
             B.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
             B.Dispose();
             memoryStream.Seek(0, SeekOrigin.Begin);
             byte[] data = new byte[memoryStream.Length];
             memoryStream.Read(data, 0, (int)memoryStream.Length);
             _bitmap = new ByteArrayBitmap(data);
         }
     }
     catch (Exception ee)
     {
         DebugMessageLogger.LogError(ee);
     }
 }
Exemplo n.º 23
0
        public static void RunCleanup(TimeSpan olderThan)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    Thread.CurrentThread.Name = "Run Cleanup";
                    DateTime now = DateTime.Now;
                    DebugMessageLogger.LogEvent("Looking for log files older than {0} ago", olderThan);

                    List <string> paths = new List <string>();
                    paths.Add(LogsFolder);
                    foreach (var dir in Directory.GetDirectories(LogsFolder))
                    {
                        if (!dir.Contains("CommonViewingLogs"))    //dont delete viewing logs
                        {
                            paths.Add(dir);
                        }
                    }

                    foreach (var dir in paths)
                    {
                        foreach (var file in Directory.GetFiles(dir, "*.log"))
                        {
                            TimeSpan howold = now - new FileInfo(file).LastWriteTime;
                            if (howold > olderThan)
                            {
                                DebugMessageLogger.LogEvent("Deleting file {0} which is {1} days old", file, howold.Days);
                                File.Delete(file);
                            }
                        }
                    }
                }
                catch (Exception ee)
                {
                    DebugMessageLogger.LogError(ee);
                }
            });
        }
Exemplo n.º 24
0
        protected byte[] Compress(byte[] data)
        {
            byte[] encodedData = null;
            try
            {
                var encoder = new JpegBitmapEncoderFactory(JpegBitmapEncoderFactory.DefaultJpegQuality).GetBitmapEncoder();

                var bitmapSource = BitmapSource.Create(this.Width, this.Height, 96, 96, this.Format, null, data, this.Stride);
                bitmapSource.Freeze();

                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                using (MemoryStream imageMemoryStream = new MemoryStream())
                {
                    encoder.Save(imageMemoryStream);
                    encodedData = imageMemoryStream.ToArray();
                }
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(encodedData);
        }
Exemplo n.º 25
0
        public BitmapSource GetImageFromEncodedData()
        {
            BitmapSource bmp = null;

            try
            {
                BitmapDecoder decoder;
                using (MemoryStream memoryStream = new MemoryStream(this.EncodedData))
                    decoder = BitmapDecoder.Create(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

                BitmapFrame bitmapFrame = decoder.Frames[0];

                bmp = bitmapFrame;

                //this prevents big memory spikes on playback of HD video.
                //if(_countGCs++ % 5 == 0)
                //  GC.Collect();
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }
            return(bmp);
        }
Exemplo n.º 26
0
 public static void LogClick()
 {
     DebugMessageLogger.LogEvent("--USER CLICK--- {0}", new StackFrame(1, true));
 }
        /// <summary>
        /// This method looks for the index at the end of the frame packet. This should be in the format DateTime.Int
        /// following a final "--videoboundary"
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="stampA"></param>
        /// <param name="stampB"></param>
        /// <returns></returns>
        public static List <KeyValuePair <DateTime, int> > GetTimeStampsFromFrameIndex(byte[] buffer, DateTime start, TimeSpan duration)
        {
            List <KeyValuePair <DateTime, int> > times = new List <KeyValuePair <DateTime, int> >();
            long utcmask       = ((long)DateTimeKind.Utc << 62);
            long localantimask = ~((long)DateTimeKind.Local << 62);

            DateTime end = start + duration;

            //this is because the gob start time from the db can be slightly off the first frame time
            DateTime startLimit = start.AddSeconds(-120);
            DateTime endLimit   = end.AddSeconds(120);
            TimeSpan?offset     = null;

            //long unspmask = ~((long)3 << 62);

            try
            {
                ASCIIEncoding encoder    = new ASCIIEncoding();
                string        stamp      = "--videoboundary--";
                byte[]        stampbytes = encoder.GetBytes(stamp);

                int index_of_index = -1;
                int pos            = buffer.Length;

                while (index_of_index == -1 && pos > 0)
                {
                    pos           -= 5000;
                    index_of_index = ByteArrayUtils.IndexOf(buffer, stampbytes, pos, buffer.Length - pos);
                }
                if (index_of_index == -1)
                {
                    throw new IOException("Invalid buffer");
                }

                pos = index_of_index + stampbytes.Length;
                while (pos < buffer.Length - 12)
                {
                    long bytes = BitConverter.ToInt64(buffer, pos);
                    bytes = bytes | utcmask;
                    bytes = bytes & localantimask;
                    //bytes = bytes & unspmask;
                    DateTime time = DateTime.FromBinary(bytes);

                    //this fixes the timezone issue
                    //time = ChangeDateTimeKind(time, DateTimeKind.Utc);

                    //rationality check, for timezone and daylight savings problems
                    if (time < startLimit || time > endLimit)
                    {
                        if (offset.HasValue == false)
                        {
                            long roundedticks = (long)((time.Ticks / 10000) * 10000);
                            long diff         = time.Ticks - roundedticks;
                            if (diff > 5000)  ///to unround the number (workaround for a bug on some pcs)
                            {
                                roundedticks += 10000;
                            }
                            DateTime roundedTime = new DateTime(roundedticks);
                            //assume first frame
                            offset = start - roundedTime;

                            DebugMessageLogger.LogEvent("Time is off in this Frame Packet - adjusting by {0}", offset);
                        }
                        time = time + offset.Value;
                    }

                    int bytepos = BitConverter.ToInt32(buffer, pos + 8);

                    //sometimes there are blank bytes at the end of the file. Don't record these as index entries.
                    //if (bytepos > 0)
                    times.Add(new KeyValuePair <DateTime, int>(time, bytepos));

                    pos += 12;
                }
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(times);
        }
Exemplo n.º 28
0
        private static void ConvertExceptionToText(Exception e, string extra, int logLevel, string threadSignature)
        {
            try
            {
                //make sure log is in english
                Thread.CurrentThread.CurrentCulture = _logCulture;

                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("\r\n\r\n{0} [{1}] [{2}] {3}\r\n", DateTime.Now.ToString(TimeStampFormat), _instanceID, logLevel.ToString(), threadSignature);

                Exception printException = e;
                while (printException != null)
                {
                    sb.AppendFormat("{0}\r\n", printException);
                    sb.AppendFormat("Source: {0}\r\n", printException.Source);
                    sb.AppendFormat("HasInnerException = {0}\r\n", (printException.InnerException != null));
                    printException = printException.InnerException;
                }

                if (!String.IsNullOrEmpty(extra))
                {
                    sb.AppendFormat("ExtraInfo: {0}\r\n", extra);
                }

                sb.Append("\r\n\r\n");

                string message = sb.ToString();

                if (message != previousMessage)
                {
                    if (repeatcount > 1)
                    {
                        WriteToFile(string.Format("\r\nPrevious message written {0} times\r\n", repeatcount));
                    }

                    previousMessage = message;
                    repeatcount     = 0;
                    WriteToFile(message);
                }
                else
                {
                    repeatcount++;
                }

                exceptionCount++;

                if (exceptionCount % 10 == 0)
                {
                    long totmem = 0;
                    Task t      = Task.Factory.StartNew(
                        () =>
                    {
                        Thread.CurrentThread.Name = "Log Memory Use";
                        try
                        {
                            totmem          = GC.GetTotalMemory(true);
                            float privateMB = Process.GetCurrentProcess().PrivateMemorySize64 / 1000000f;
                            DebugMessageLogger.LogEvent("Exception count: {0} Private Bytes Usage: {1} MB, GC: {2} MB",
                                                        exceptionCount,
                                                        privateMB.ToString("n"),
                                                        (totmem / 1000000f).ToString("n"));
                        }
                        catch (Exception eeex)
                        {
                        }
                    }
                        );
                    //t.Wait(200);

                    //Calculate Memoryusage

                    //if (exceptionCount % 50 == 0)
                    //{
                    //    if ((DateTime.Now - _LastHDDCheckTime).TotalSeconds > 300)
                    //    {
                    //        _LastHDDCheckTime = DateTime.Now;
                    //        // check DB HDD
                    //        Task.Factory.StartNew(() =>
                    //            {
                    //                try
                    //                {
                    //                    long res = Useful.CheckHDDSize.HowMuchDBSpaceLeft();

                    //                    if (res != -1 && (res / (1 << 30)) < 1)
                    //                    {
                    //                        LogEventLevel("################## WARNING < 1 GB DB Space Available ####################", 0);
                    //                    }
                    //                    if (CheckHDDSize.DBDrive != null)
                    //                        LogEventLevel("Database Drive " + CheckHDDSize.DBDrive.RootDirectory + " has " + (res / (1024 * 1024)).ToString() + "Mb space left", 0);
                    //                }
                    //                catch (Exception er)
                    //                {
                    //                    Kinesense.Interfaces.DebugMessageLogger.LogError(er);
                    //                }

                    //            });

                    //        // Check temp HDD
                    //        Task.Factory.StartNew(() =>
                    //        {
                    //            try
                    //            {
                    //                long res = Useful.CheckHDDSize.HowMuchTEMPSpaceLeft();

                    //                if (res != -1 && (res / (1 << 30)) < 1)
                    //                {
                    //                    LogEventLevel("################## WARNING < 1 GB DB Space Available ####################", 0);
                    //                }
                    //                if (CheckHDDSize.TEMPDrive != null)
                    //                    LogEventLevel("Temp Drive " + CheckHDDSize.TEMPDrive.RootDirectory + " has " + (res / (1024 * 1024)).ToString() + "Mb space left", 0);
                    //            }
                    //            catch (Exception er)
                    //            {
                    //                Kinesense.Interfaces.DebugMessageLogger.LogError(er);
                    //            }

                    //        });
                    //    }
                    //}
                }
                else if (e is System.OutOfMemoryException ||
                         (e.InnerException != null && e.InnerException is System.OutOfMemoryException))
                {
                    if ((DateTime.Now - _MostRecentMemoryTest).TotalSeconds > 60)
                    {
                        long totmem = 0;
                        Task t      = Task.Factory.StartNew(() =>
                        {
                            totmem          = GC.GetTotalMemory(true);
                            float privateMB = Process.GetCurrentProcess().PrivateMemorySize64 / 1000000f;
                            DebugMessageLogger.LogEvent("OutOfMemoryException Private Bytes Usage: {0} MB, GC: {1} MB",
                                                        privateMB.ToString("n"),
                                                        (totmem / 1000000f).ToString("n"));
                        });
                        t.Wait(200);
                        _MostRecentMemoryTest = DateTime.Now;
                    }
                    //Calculate Memoryusage
                }
            }
            catch (Exception ee)
            {
                //System.Windows.MessageBox.Show(ee.Message);
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = _currentculture;
            }
        }