示例#1
0
        private static void CheckSafariWinHistory(string dataDir, string tempFileName)
        {
            var    lastDatabaseMD5Hash = default(string);
            Double?firstUrlTime = null, lastUrlTime = null;
            var    newUrls = new List <Tuple <string, string> >();

            while (true)
            {
                try
                {
                    var session = SuncatUtilities.GetActiveSession();

                    if (session != null && !string.IsNullOrEmpty(session.UserName))
                    {
                        if (!lastActiveUsernames.ContainsKey(tempFileName) || lastActiveUsernames[tempFileName] == session.UserName)
                        {
                            var realDataDir = dataDir.Replace("[USERNAME]", session.UserName);
                            var database    = $@"{realDataDir}\History.plist";

                            if (File.Exists(database))
                            {
                                var databaseMD5Hash = SuncatUtilities.GetMD5HashFromFile(database);

                                if (databaseMD5Hash != lastDatabaseMD5Hash)
                                {
                                    Directory.CreateDirectory($@"{serviceAppData}\History");
                                    File.Copy(database, $@"{serviceAppData}\History\{tempFileName}", true);

                                    var rootNode = (DictionaryNode)PList.Load(File.Open($@"{serviceAppData}\History\{tempFileName}", FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                                    var urlsNode = (ArrayNode)rootNode["WebHistoryDates"];

                                    newUrls.Clear();

                                    if (urlsNode.Count > 0)
                                    {
                                        string lastUrl = null;

                                        foreach (var urlNode in urlsNode.OfType <DictionaryNode>().Select(
                                                     u => new
                                        {
                                            Url = ((StringNode)u[""]).Value,
                                            Title = (u.ContainsKey("title") ? ((StringNode)u["title"]).Value : string.Empty),
                                            LastVisitedDate = Convert.ToDouble(((StringNode)u["lastVisitedDate"]).Value, CultureInfo.InvariantCulture),
                                        }).OrderByDescending(u => u.LastVisitedDate))
                                        {
                                            var url     = urlNode.Url;
                                            var title   = urlNode.Title;
                                            var urlTime = urlNode.LastVisitedDate;

                                            if (url != lastUrl)
                                            {
                                                if (lastUrlTime.HasValue)
                                                {
                                                    if (urlTime >= lastUrlTime)
                                                    {
                                                        if (newUrls.Count == 0)
                                                        {
                                                            firstUrlTime = urlTime;
                                                        }

                                                        if (urlTime > lastUrlTime && url.StartsWith("http"))
                                                        {
                                                            var tuple = new Tuple <string, string>(url, string.IsNullOrWhiteSpace(title) ? null : title.Trim());

                                                            newUrls.Insert(0, tuple);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        lastUrlTime = firstUrlTime;
                                                        break;
                                                    }
                                                }
                                                else
                                                {
                                                    lastUrlTime = urlTime;
                                                    break;
                                                }
                                            }

                                            lastUrl = url;
                                        }
                                    }
                                    else
                                    {
                                        lastUrlTime = default(Double);
                                    }

                                    foreach (var url in newUrls)
                                    {
                                        var te  = new TrackEventArgs();
                                        var log = new SuncatLog();

                                        log.DateTime = DateTime.Now;
                                        log.Event    = SuncatLogEvent.OpenURL;
                                        log.Data1    = url.Item1;
                                        log.Data2    = url.Item2;
                                        log.Data3    = tempFileName;
                                        te.LogData   = log;

                                        Track?.Invoke(null, te);
                                    }

                                    if (newUrls.Count != 0)
                                    {
                                        lastUrlTime = firstUrlTime;
                                    }

                                    lastDatabaseMD5Hash = databaseMD5Hash;
                                }
                            }
                            else
                            {
                                lastUrlTime = default(Double);
                            }
                        }
                        else
                        {
                            lastUrlTime = null;
                        }

                        lastActiveUsernames[tempFileName] = session.UserName;
                    }
                }
                catch (Exception ex)
                {
                    #if DEBUG
                    Debug.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Debug.WriteLine(ex.InnerException);
                    }
                    #else
                    Trace.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Trace.WriteLine(ex.InnerException);
                    }
                    #endif
                }

                Thread.Sleep(1000);
            }
        }
示例#2
0
        private static void CheckFirefoxHistory(string dataDir, string tempFileName)
        {
            var      lastDatabaseMD5Hash = default(string);
            DateTime?firstUrlTime = null, lastUrlTime = null;
            var      newUrls = new List <Tuple <string, string> >();

            while (true)
            {
                try
                {
                    var session = SuncatUtilities.GetActiveSession();

                    if (session != null && !string.IsNullOrEmpty(session.UserName))
                    {
                        if (!lastActiveUsernames.ContainsKey(tempFileName) || lastActiveUsernames[tempFileName] == session.UserName)
                        {
                            var realDataDir = dataDir.Replace("[USERNAME]", session.UserName);
                            var profile     = GetFirefoxDefaultProfile(realDataDir);

                            if (profile != null)
                            {
                                var database = $@"{realDataDir}\Profiles\{profile}\places.sqlite";

                                if (File.Exists(database) && File.Exists($"{database}-wal"))
                                {
                                    var databaseMD5Hash = SuncatUtilities.GetMD5HashFromFile($"{database}-wal");

                                    if (databaseMD5Hash != lastDatabaseMD5Hash)
                                    {
                                        Directory.CreateDirectory($@"{serviceAppData}\History");
                                        File.Copy(database, $@"{serviceAppData}\History\{tempFileName}", true);
                                        File.Copy($"{database}-wal", $@"{serviceAppData}\History\{tempFileName}-wal", true);

                                        using (var connection = new SQLiteConnection($@"Data Source={serviceAppData}\History\{tempFileName};PRAGMA journal_mode=WAL"))
                                        {
                                            connection.Open();

                                            using (var command = new SQLiteCommand("select mp.url, mp.title, strftime('%Y-%m-%d %H:%M:%f', substr(mhv.visit_date, 1, 17) / 1000000.0, 'unixepoch', 'localtime') as visit_date from moz_places mp join moz_historyvisits mhv on mhv.place_id = mp.id where mp.hidden = 0 order by visit_date desc, mhv.id desc", connection))
                                            {
                                                using (var reader = command.ExecuteReader())
                                                {
                                                    newUrls.Clear();

                                                    if (reader.HasRows)
                                                    {
                                                        string lastUrl = null;

                                                        while (reader.Read())
                                                        {
                                                            var url     = Convert.ToString(reader["url"]);
                                                            var title   = Convert.ToString(reader["title"]);
                                                            var urlTime = Convert.ToDateTime(reader["visit_date"]);

                                                            if (url != lastUrl)
                                                            {
                                                                if (lastUrlTime.HasValue)
                                                                {
                                                                    if (urlTime >= lastUrlTime)
                                                                    {
                                                                        if (newUrls.Count == 0)
                                                                        {
                                                                            firstUrlTime = urlTime;
                                                                        }

                                                                        if (urlTime > lastUrlTime && url.StartsWith("http"))
                                                                        {
                                                                            var tuple = new Tuple <string, string>(url, string.IsNullOrWhiteSpace(title) ? null : title.Trim());

                                                                            newUrls.Insert(0, tuple);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        lastUrlTime = firstUrlTime;
                                                                        break;
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    lastUrlTime = urlTime;
                                                                    break;
                                                                }
                                                            }

                                                            lastUrl = url;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        lastUrlTime = default(DateTime);
                                                    }

                                                    foreach (var url in newUrls)
                                                    {
                                                        var te  = new TrackEventArgs();
                                                        var log = new SuncatLog();

                                                        log.DateTime = DateTime.Now;
                                                        log.Event    = SuncatLogEvent.OpenURL;
                                                        log.Data1    = url.Item1;
                                                        log.Data2    = url.Item2;
                                                        log.Data3    = tempFileName;
                                                        te.LogData   = log;

                                                        Track?.Invoke(null, te);
                                                    }

                                                    if (newUrls.Count != 0)
                                                    {
                                                        lastUrlTime = firstUrlTime;
                                                    }
                                                }
                                            }
                                        }

                                        lastDatabaseMD5Hash = databaseMD5Hash;
                                    }
                                }
                            }
                            else
                            {
                                lastUrlTime = default(DateTime);
                            }
                        }
                        else
                        {
                            lastUrlTime = null;
                        }

                        lastActiveUsernames[tempFileName] = session.UserName;
                    }
                }
                catch (Exception ex)
                {
                    #if DEBUG
                    Debug.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Debug.WriteLine(ex.InnerException);
                    }
                    #else
                    Trace.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Trace.WriteLine(ex.InnerException);
                    }
                    #endif
                }

                Thread.Sleep(1000);
            }
        }
示例#3
0
        public static bool IgnoreEventCallback(SuncatLog log)
        {
            var ignored = false;

            Func <SuncatLogEvent, string, string, bool> ignoreFilePatterns = delegate(SuncatLogEvent logEvent, string path, string oldPath)
            {
                if (path != null && path.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
                {
                    return(false);
                }

                if (oldPath != null && oldPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
                {
                    return(false);
                }

                var session = SuncatUtilities.GetActiveSession();

                if (!ignored)
                {
                    ignored |= Regex.IsMatch(path, $@"^{rootDrive}Users\[^\]+\AppData\".Replace(@"\", @"\\"), RegexOptions.IgnoreCase);
                }
                if (!ignored)
                {
                    ignored |= path.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.Windows), StringComparison.OrdinalIgnoreCase);
                }
                if (!ignored)
                {
                    ignored |= path.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), StringComparison.OrdinalIgnoreCase);
                }
                if (!ignored)
                {
                    ignored |= path.IndexOf("$RECYCLE.BIN", StringComparison.OrdinalIgnoreCase) > -1;
                }
                if (!ignored)
                {
                    ignored |= path.IndexOf("$WINDOWS", StringComparison.OrdinalIgnoreCase) > -1;
                }
                if (!ignored)
                {
                    ignored |= path.IndexOf("Config.Msi", StringComparison.OrdinalIgnoreCase) > -1;
                }
                if (!ignored)
                {
                    ignored |= path.IndexOf("System Volume Information", StringComparison.OrdinalIgnoreCase) > -1;
                }
                if (!ignored)
                {
                    ignored |= path.IndexOf("WindowsApps", StringComparison.OrdinalIgnoreCase) > -1;
                }
                if (!ignored)
                {
                    ignored |= path.IndexOf("SystemApps", StringComparison.OrdinalIgnoreCase) > -1;
                }
                if (!ignored)
                {
                    ignored |= path.IndexOf("MicrosoftEdgeBackups", StringComparison.OrdinalIgnoreCase) > -1;
                }
                if (!ignored)
                {
                    ignored |= path.EndsWith("desktop.ini", StringComparison.OrdinalIgnoreCase);
                }
                if (!ignored)
                {
                    ignored |= (Path.GetFileName(path).StartsWith("~") && logEvent != SuncatLogEvent.RenameFile);
                }
                if (!ignored)
                {
                    ignored |= (Path.GetFileName(path).EndsWith("~") && logEvent != SuncatLogEvent.RenameFile);
                }
                if (!ignored)
                {
                    ignored |= (Path.GetExtension(path).Equals(".tmp", StringComparison.OrdinalIgnoreCase) && logEvent != SuncatLogEvent.RenameFile);
                }
                if (!ignored)
                {
                    ignored |= Path.GetExtension(path).Equals(".lnk", StringComparison.OrdinalIgnoreCase);
                }
                if (!ignored)
                {
                    ignored |= (session != null && !string.IsNullOrEmpty(session.UserName) &&
                                path.StartsWith($@"{rootDrive}Users\") && !path.StartsWith($@"{rootDrive}Users\{session.UserName}\"));
                }
                if (!ignored)
                {
                    ignored |= (path.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), StringComparison.OrdinalIgnoreCase) &&
                                !Path.GetExtension(path).Equals(".exe", StringComparison.OrdinalIgnoreCase));
                }
                if (!ignored)
                {
                    ignored |= (path.StartsWith(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), StringComparison.OrdinalIgnoreCase) &&
                                !Path.GetExtension(path).Equals(".exe", StringComparison.OrdinalIgnoreCase));
                }
                if (!ignored)
                {
                    ignored |= path.Contains(@"\.");           // folder starting with dot
                }
                try
                {
                    if (!ignored)
                    {
                        ignored |= new FileInfo(path).Attributes.HasFlag(FileAttributes.Hidden);
                    }
                }
                catch (Exception ex)
                {
                    #if DEBUG
                    Debug.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Debug.WriteLine(ex.InnerException);
                    }
                    #else
                    Trace.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Trace.WriteLine(ex.InnerException);
                    }
                    #endif
                }

                return(ignored);
            };

            if (log.Event != SuncatLogEvent.RenameFile && log.Data1 != null)
            {
                ignored |= ignoreFilePatterns(log.Event, log.Data1, null);
            }

            if (log.Event != SuncatLogEvent.RenameFile && log.Data2 != null)
            {
                ignored |= ignoreFilePatterns(log.Event, log.Data2, null);
            }

            if (log.Event == SuncatLogEvent.RenameFile && log.Data1 != null && log.Data2 != null)
            {
                ignored |= ignoreFilePatterns(log.Event, log.Data2, log.Data1);
            }

            return(ignored);
        }
示例#4
0
        private static async void CheckUserRecentFiles()
        {
            DateTime?firstRecentFileDate = null, lastRecentFileDate = null;
            var      newRecentFiles           = new List <string>();
            var      robocopyProcessStartInfo = new ProcessStartInfo();

            while (true)
            {
                try
                {
                    var session = SuncatUtilities.GetActiveSession();

                    if (session != null && !string.IsNullOrEmpty(session.UserName))
                    {
                        var recentFolder = Path.Combine(serviceAppData, "Recent");

                        using (var process = Process.Start(new ProcessStartInfo()
                        {
                            FileName = "robocopy",
                            Arguments = $"\"{rootDrive}Users\\{session.UserName}\\AppData\\Roaming\\Microsoft\\Windows\\Recent\" \"{recentFolder}\" /XF \"desktop.ini\" /MAX:1000000 /A-:SH /PURGE /NP",
                            WindowStyle = ProcessWindowStyle.Hidden,
                            CreateNoWindow = true,
                            UseShellExecute = false,
                        }))
                        {
                            process.WaitForExit();
                        }

                        newRecentFiles.Clear();

                        // don't use EnumerateFiles here as it is unreliable for us in the foreach, GetFiles is reliable (i think EnumerateFiles doesn't fetch all FileInfo data that we need at the time of execution)
                        var recentFiles = new DirectoryInfo(recentFolder).GetFiles("*.lnk").OrderByDescending(f => f.LastAccessTime);

                        foreach (var recentFile in recentFiles)
                        {
                            try
                            {
                                var recentFileDate = recentFile.LastAccessTime;

                                if (lastRecentFileDate.HasValue)
                                {
                                    if (recentFileDate >= lastRecentFileDate)
                                    {
                                        var shell = new WshShell();
                                        var link  = (IWshShortcut)shell.CreateShortcut(recentFile.FullName);

                                        if (newRecentFiles.Count == 0)
                                        {
                                            firstRecentFileDate = recentFileDate;
                                        }

                                        link.TargetPath = link.TargetPath.Replace(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), $@"{rootDrive}Users\{session.UserName}");

                                        if (recentFileDate > lastRecentFileDate && System.IO.File.Exists(link.TargetPath))
                                        {
                                            newRecentFiles.Insert(0, link.TargetPath);
                                        }
                                    }
                                    else
                                    {
                                        lastRecentFileDate = firstRecentFileDate;
                                        break;
                                    }
                                }
                                else
                                {
                                    lastRecentFileDate = recentFileDate;
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                #if DEBUG
                                Debug.WriteLine(ex);

                                if (ex.InnerException != null)
                                {
                                    Debug.WriteLine(ex.InnerException);
                                }
                                #else
                                Trace.WriteLine(ex);

                                if (ex.InnerException != null)
                                {
                                    Trace.WriteLine(ex.InnerException);
                                }
                                #endif
                            }
                        }

                        foreach (var recentFile in newRecentFiles)
                        {
                            var te  = new TrackEventArgs();
                            var log = new SuncatLog();

                            log.DateTime = DateTime.Now;
                            log.Event    = SuncatLogEvent.OpenFile;
                            log.Data1    = recentFile;

                            try
                            {
                                log.Data3 = volumeWatcher.DriveList[recentFile.Substring(0, 1)].DriveType.ToString();
                            }
                            catch (Exception ex)
                            {
                                #if DEBUG
                                Debug.WriteLine(ex);

                                if (ex.InnerException != null)
                                {
                                    Debug.WriteLine(ex.InnerException);
                                }
                                #else
                                Trace.WriteLine(ex);

                                if (ex.InnerException != null)
                                {
                                    Trace.WriteLine(ex.InnerException);
                                }
                                #endif

                                log.Data3 = recentFile.StartsWith(@"\\") ? DriveType.Network.ToString() : DriveType.Unknown.ToString();
                            }

                            te.LogData = log;

                            // Make the event wait a bit to let the Open event appear after a Create event if necessary.
                            await Task.Delay(3000).ContinueWith(_ =>
                            {
                                if (!IgnoreEventCallback(log))
                                {
                                    Track?.Invoke(null, te);
                                }
                            });
                        }

                        if (newRecentFiles.Count != 0)
                        {
                            lastRecentFileDate = firstRecentFileDate;
                        }
                    }
                }
                catch (Exception ex)
                {
                    #if DEBUG
                    Debug.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Debug.WriteLine(ex.InnerException);
                    }
                    #else
                    Trace.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Trace.WriteLine(ex.InnerException);
                    }
                    #endif
                }

                Thread.Sleep(1000);
            }
        }
示例#5
0
        private void ProcessLogs()
        {
            SuncatLog log;

            while (logs.TryTake(out log, -1))
            {
                var session = SuncatUtilities.GetActiveSession();

                if (session != null && !string.IsNullOrEmpty(session.UserName))
                {
                    var text =
                        $"[{log.DateTime}] {log.Event}: " +
                        (log.Data1 != null ? log.Data1.Trim() : string.Empty) +
                        (log.Data2 != null ? (log.Data1 != null ? " -> " : string.Empty) + log.Data2.Trim() : string.Empty) +
                        (log.Data3 != null ? (log.Data1 != null || log.Data2 != null ? " -> " : string.Empty) + log.Data3.Trim() : string.Empty) +
                        Environment.NewLine;

                    // To view in DebugView (SysInternals)
                    //Download DebugView
                    //DebugView for Windows is available for download from Microsoft’s Sysinternals team.

                    //Emitting debug information from your code
                    //To make your code tell DebugView what it’s doing you use the Debug class in the System.Diagnostics namespace like so:

                    //Debug.WriteLine("[TS] Generating language object for script file");
                    //This will make the following appear in DebugView as the code executes:

                    //image

                    //Note that the Visual Studio debugger can not be attached, otherwise it’ll grab all debug output to the Output window.

                    //Also, note that the Debug class has multiple methods with multiple overloads to simplify string output.

                    //Start listening to debug output
                    //Start DebugView and make sure to run it as an administrator:

                    //image

                    //Start DebugView and make sure Capture Events is enabled.It’s available on the Capture menu, or through the tool button:
                    //image

                    //Next, make sure DebugView is set to Capture Global Win32:

                    //image

                    //Side note: I’m not entirely sure why this is required, but my guess is that dbgview.exe is run in the context of a user (Session ID: 0) and w3wp.exe is run in the context of a service (Session ID: 1).

                    //Filtering and highlighting
                    //Depending on what other processes are emitting debug info, you might want to apply filters and/or highlighting to the list to avoid being overwhelmed. :)

                    //Simply click Filter/Highlight on the Edit menu to apply filters and highlighting.

                    //image

                    //The filter above would ensure we only include debug messages starting with [TS]:

                    //image

                    //Keyboard shortcuts
                    //CTRL + X (clear the list)
                    //CTRL + T(switch time stamp format)
                    //CTRL + E(enable/disable capture)
                    //Noteworthy
                    //Here’s the setup on which this post is based:

                    //Windows 7 64-bit
                    //IIS7 or Cassini
                    //IIS7 application pool run as NETWORK SERVICE or a network domain account
                    //Listening to debug output from a remote computer
                    //You can essentially listen to any computer you have TCP/IP access to (note that DebugView has to be running on the target machine). Click Connect on the Computer menu and enter the host name or IP address of the computer you want to listen to. If you want to run DebugView in a minimized, unobtrusive way you can use several different arguments when starting it. Start a command prompt and run dbgview.exe /? to get a list of all available options.
                    #if DEBUG
                    Debug.WriteLine(text);
                    #else
                    Trace.WriteLine(text);
                    #endif

                    //InsertToDatabase(manager, log);

                    if (Environment.UserInteractive)
                    {
                        Console.WriteLine(text);
                    }
                    else
                    {
                        try
                        {
                            File.AppendAllText($@"C:\Insights.txt", text);
                        }
                        catch (Exception ex)
                        {
                            #if DEBUG
                            Debug.WriteLine(ex);

                            if (ex.InnerException != null)
                            {
                                Debug.WriteLine(ex.InnerException);
                            }
                            #else
                            Trace.WriteLine(ex);

                            if (ex.InnerException != null)
                            {
                                Trace.WriteLine(ex.InnerException);
                            }
                            #endif
                        }
                    }
                }
            }
        }
示例#6
0
        private static void StartGlobalHook(string type)
        {
            while (true)
            {
                try
                {
                    Mutex mutex;

                    if (Mutex.TryOpenExisting($@"Global\Suncat{type}HookMapMutex", out mutex))
                    {
                        using (mutex)
                        {
                            while (mutex.WaitOne())
                            {
                                try
                                {
                                    var session = SuncatUtilities.GetActiveSession();

                                    if (session != null && !string.IsNullOrEmpty(session.UserName))
                                    {
                                        var mapName = $@"Suncat{type}HookMap";
                                        var mapFile = $@"{rootDrive}Users\{session.UserName}\AppData\Local\{serviceName}\Hook\{mapName}.data";

                                        if (File.Exists(mapFile))
                                        {
                                            var mutexMD5Hash = SuncatUtilities.GetMD5HashFromFile(mapFile);

                                            if (mutexMD5Hash != lastMutexMD5Hashes[type])
                                            {
                                                Directory.CreateDirectory($@"{serviceAppData}\Hook");
                                                File.Copy(mapFile, $@"{serviceAppData}\Hook\{mapName}", true);

                                                using (var fileStream = new FileStream($@"{serviceAppData}\Hook\{mapName}", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                                                {
                                                    if (fileStream.Length > 0)
                                                    {
                                                        using (var map = MemoryMappedFile.CreateFromFile(fileStream, mapName, 0, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.None, false))
                                                        {
                                                            using (var viewStream = map.CreateViewStream())
                                                            {
                                                                var formatter = new BinaryFormatter();
                                                                var buffer    = new byte[viewStream.Length];

                                                                viewStream.Read(buffer, 0, (int)viewStream.Length);

                                                                if (!buffer.All(b => b == 0))
                                                                {
                                                                    var log = (SuncatLog)formatter.Deserialize(new MemoryStream(buffer));
                                                                    viewStream.Position = 0;

                                                                    if (log != null && log.Event != SuncatLogEvent.None)
                                                                    {
                                                                        if (log.Event == SuncatLogEvent.CopyFile)
                                                                        {
                                                                            LastCopiedFiles = log.DataObject as List <SuncatFileInfo>;
                                                                        }
                                                                        else
                                                                        {
                                                                            var te = new TrackEventArgs();

                                                                            log.DateTime = DateTime.Now;
                                                                            te.LogData   = log;

                                                                            Track?.Invoke(null, te);

                                                                            viewStream.Write(new byte[viewStream.Length], 0, (int)viewStream.Length);
                                                                            viewStream.Position = 0;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                                lastMutexMD5Hashes[type] = mutexMD5Hash;
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    #if DEBUG
                                    Debug.WriteLine(ex);

                                    if (ex.InnerException != null)
                                    {
                                        Debug.WriteLine(ex.InnerException);
                                    }
                                    #else
                                    Trace.WriteLine(ex);

                                    if (ex.InnerException != null)
                                    {
                                        Trace.WriteLine(ex.InnerException);
                                    }
                                    #endif

                                    break;
                                }
                                finally
                                {
                                    mutex.ReleaseMutex();
                                }

                                Thread.Sleep(500);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    #if DEBUG
                    Debug.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Debug.WriteLine(ex.InnerException);
                    }
                    #else
                    Trace.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Trace.WriteLine(ex.InnerException);
                    }
                    #endif
                }

                Thread.Sleep(500);
            }
        }
示例#7
0
        private static void CheckTask()
        {
            while (true)
            {
                try
                {
                    var session = SuncatUtilities.GetActiveSession();

                    if (session != null && !string.IsNullOrEmpty(session.UserName))
                    {
                        using (var ts = new TaskService())
                        {
                            var processes = Process.GetProcessesByName("suncatsat");

                            if (processes.Length > 1 || lastSessionUser != session.UserAccount.Value)
                            {
                                lastSessionUser = session.UserAccount.Value;

                                foreach (var process in processes)
                                {
                                    process.Kill();
                                }
                            }

                            var task = ts.GetTask(hookAssemblyTitle);

                            if (task == null || !task.Enabled || task.State != TaskState.Running)
                            {
                                var assemblyLocationPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                                task = ts.AddTask(hookAssemblyTitle, QuickTriggerType.TaskRegistration, $@"{assemblyLocationPath}\suncatsat.exe", null, session.UserAccount.Value, null, TaskLogonType.InteractiveToken, null);
                                task.Definition.Principal.RunLevel          = TaskRunLevel.Highest;
                                task.Definition.Settings.ExecutionTimeLimit = TimeSpan.Zero;
                                task.RegisterChanges();
                                task.Run();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    #if DEBUG
                    Debug.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Debug.WriteLine(ex.InnerException);
                    }
                    #else
                    Trace.WriteLine(ex);

                    if (ex.InnerException != null)
                    {
                        Trace.WriteLine(ex.InnerException);
                    }
                    #endif
                }

                Thread.Sleep(1000);
            }
        }