private void bw_DoWork(object sender, DoWorkEventArgs e) { try { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "StatParserUI"; } logger.Info("Updating player stats"); BackgroundWorker worker = sender as BackgroundWorker; // Update all stats playerItemDao.ClearAllItemStats(); IList <PlayerItem> items = playerItemDao.ListAll(); worker.ReportProgress(Math.Max(100, items.Count), 1); int total = 0; playerItemDao.UpdateAllItemStats(items, (p) => { worker.ReportProgress(total++, 0); }); logger.Info("Updated item stats"); } catch (Exception ex) { logger.Fatal(ex.Message); logger.Fatal(ex.StackTrace); ExceptionReporter.ReportException(ex); throw; } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "InjectionHelper"; } try { BackgroundWorker worker = sender as BackgroundWorker; while (!worker.CancellationPending) { if (!File.Exists("DllInjector64.exe") || !File.Exists("DllInjector32.exe")) { new AvastedWarning().ShowDialog(); Logger.Fatal("Shutting down injection helper. End user has been avasted and IA is now inoperational until reinstalled."); return; } else { Process(worker, e.Argument as RunArguments); } } } catch (Exception ex) { Logger.Fatal(ex.Message); Logger.Fatal(ex.StackTrace); ExceptionReporter.ReportException(ex); throw; } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { try { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "Backup"; Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); } ExceptionReporter.EnableLogUnhandledOnThread(); BackgroundWorker worker = sender as BackgroundWorker; ICloudBackup b = e.Argument as ICloudBackup; while (!worker.CancellationPending) { Thread.Sleep(10); b.Update(); } } catch (Exception ex) { logger.Fatal(ex.Message); logger.Fatal(ex.StackTrace); ExceptionReporter.ReportException(ex); throw; } }
private static ISessionFactory CreateLegacySessionFactory(string file) { try { var legacyConnectionString = string.Format("Data Source = {0};Version=3", file); var configuration = new Configuration(); configuration.Configure(); configuration.SetProperty("connection.connection_string", legacyConnectionString); configuration.AddAssembly(Assembly.GetExecutingAssembly()); try { new SchemaUpdate(configuration).Execute(true, true); return(configuration.BuildSessionFactory()); } catch (Exception ex) { logger.Warn(ex.Message); logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex); throw; } } catch (System.Reflection.TargetInvocationException ex) { logger.Warn(ex.Message); logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex.InnerException); ExceptionReporter.ReportException(ex, "[Outer Exception]", true); throw; } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "BackupServiceWorker"; } try { Logger.Debug("Backup service started, waiting for 10 seconds before initializing.."); Thread.Sleep(15000); Logger.Debug("Backup initializing.."); } catch (Exception ex) { Logger.Error(ex.Message); Logger.Error(ex.StackTrace); ExceptionReporter.ReportException(ex); } BackgroundWorker worker = sender as BackgroundWorker; while (!worker.CancellationPending) { try { Thread.Sleep(1000); _backupService.Execute(); } catch (Exception ex) { Logger.Error(ex.Message); Logger.Error(ex.StackTrace); ExceptionReporter.ReportException(ex); } } }
/// <summary> /// Write the GD Stash file /// </summary> /// <param name="filename"></param> /// <param name="stash"></param> /// <returns></returns> private bool SafelyWriteStash(string filename, Stash stash) { try { var tempName = $"{filename}.ia"; // Store the stash file in a temporary location var dataBuffer = new DataBuffer(); stash.Write(dataBuffer); DataBuffer.WriteBytesToDisk(tempName, dataBuffer.Data); // Get the current backup number var backupNumber = _settings.GetLocal().BackupNumber; _settings.GetLocal().BackupNumber = (backupNumber + 1) % 100; // Back up the existing stash and replace with new stash file var backupLocation = Path.Combine(GlobalPaths.BackupLocation, $"transfer.{backupNumber:00}.gs_"); File.Copy(filename, backupLocation, true); File.Copy(tempName, filename, true); // Delete the temporary file if (File.Exists(tempName)) { File.Delete(tempName); } return(true); } catch (UnauthorizedAccessException ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex, "SafelyWriteDatabase"); return(false); } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "TransferStashWorker"; Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); } ExceptionReporter.EnableLogUnhandledOnThread(); BackgroundWorker worker = sender as BackgroundWorker; while (!worker.CancellationPending) { try { Thread.Sleep(1000); } catch (ThreadInterruptedException) { } // Nothing queued for looting if (_queuedTransferFiles.Count == 0) { continue; } List <UserFeedback> feedback; try { var(isLootable, lootableFeedback) = _transferStashService.IsTransferStashLootable(); if (isLootable) { feedback = Execute(); } else { feedback = lootableFeedback; } } catch (NullReferenceException ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); feedback = UserFeedback.FromTagSingleton("iatag_feedback_unable_to_loot_stash"); } catch (IOException ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); Logger.Info("Exception not reported, IOExceptions are bound to happen."); feedback = UserFeedback.FromTagSingleton("iatag_feedback_unable_to_loot_stash"); } catch (Exception ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex, "EmptyPageX??"); feedback = UserFeedback.FromTagSingleton("iatag_feedback_unable_to_loot_stash"); } _feedbackService.Print(feedback); } }
private static string Post(string postData, string URL) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); if (request == null) { Logger.Warn("Could not create HttpWebRequest"); return(null); } var encoding = new UTF8Encoding(); byte[] data = encoding.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; try { using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } // threshold using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { Logger.Info("Failed to upload buddy item data."); return(null); } string result = new StreamReader(response.GetResponseStream()).ReadToEnd(); return(result); } } catch (WebException ex) { if (ex.Status != WebExceptionStatus.NameResolutionFailure && ex.Status != WebExceptionStatus.Timeout) { Logger.Warn(ex.Message); } else { Logger.Info("Could not resolve DNS for backup server, delaying upload."); } } catch (IOException ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); } catch (Exception ex) { Logger.Error(ex.Message); Logger.Error(ex.StackTrace); ExceptionReporter.ReportException(ex); } return(null); }
public override void Run() { int failures = 0; Log.Info(reduce + " Thread started: " + GetName()); try { while (!stopped && !Sharpen.Thread.CurrentThread().IsInterrupted()) { try { int numNewMaps = GetMapCompletionEvents(); failures = 0; if (numNewMaps > 0) { Log.Info(reduce + ": " + "Got " + numNewMaps + " new map-outputs"); } Log.Debug("GetMapEventsThread about to sleep for " + SleepTime); if (!Sharpen.Thread.CurrentThread().IsInterrupted()) { Sharpen.Thread.Sleep(SleepTime); } } catch (Exception) { Log.Info("EventFetcher is interrupted.. Returning"); return; } catch (IOException ie) { Log.Info("Exception in getting events", ie); // check to see whether to abort if (++failures >= MaxRetries) { throw new IOException("too many failures downloading events", ie); } // sleep for a bit if (!Sharpen.Thread.CurrentThread().IsInterrupted()) { Sharpen.Thread.Sleep(RetryPeriod); } } } } catch (Exception) { return; } catch (Exception t) { exceptionReporter.ReportException(t); return; } }
private static IntPtr InjectXBit(string injector, string exe, string dll) { Logger.Info($"Running {injector}..."); if (File.Exists(injector)) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = injector; startInfo.Arguments = $"-t 1 \"{exe}\" \"{dll}\""; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; Process processTemp = new Process(); processTemp.StartInfo = startInfo; processTemp.EnableRaisingEvents = true; try { int timeout = 1000; processTemp.Start(); processTemp.WaitForExit(timeout); if (!processTemp.HasExited) { Logger.Warn($"Injector did not finish in {timeout}ms, discarding result"); return(IntPtr.Zero); } while (!processTemp.StandardOutput.EndOfStream) { string output = processTemp.StandardOutput.ReadLine(); if (processTemp.ExitCode != 0) { Logger.Warn($"Injector returned status code {processTemp.ExitCode} with error: {output}"); return(IntPtr.Zero); } else { Logger.Info("Injection successful, storing mock point due to pointer space being outside of 32bit range."); return(new IntPtr(0xBADF00D)); } } } catch (Exception ex) { Logger.Warn($"Exception while attempting to verify injection.. {ex.Message}", ex); ExceptionReporter.ReportException(ex); } } else { Logger.Warn($"Could not find {injector}, unable to inject into Grim Dawn."); } return(IntPtr.Zero); }
private void Execute(BackgroundWorker worker, DoWorkEventArgs args) { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "ParserUI"; } try { ParsingUiBackgroundWorkerArgument arg = args.Argument as ParsingUiBackgroundWorkerArgument; if (!string.IsNullOrEmpty(arg.Path) && Directory.Exists(arg.Path)) { if (arg.TagsOnly) { _arzParser.LoadArcTags(arg.Path, arg.ExpansionOnlyMod); } else { _arzParser.LoadArzDb(arg.Path, arg.LocalizationFile, arg.ExpansionOnlyMod); if (!arg.ExpansionOnlyMod && Directory.Exists(Path.Combine(arg.Path, "gdx1"))) { _arzParser.LoadArzDb(Path.Combine(arg.Path, "gdx1"), arg.LocalizationFile, true); } } } else { Logger.Warn("Could not find the Grim Dawn install location"); } } catch (UnauthorizedAccessException ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); Logger.Warn("Access denied trying to read a file. This may happen if Grim Dawn is currently running."); MessageBox.Show(string.Format("Access denied while parsing Grim Dawn\n\nEnsure that Grim Dawn is not currently running.", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (IOException ex) { MessageBox.Show($"{ex.Message}\n\nPerhaps Grim Dawn is running?", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex); throw; } }
private void SyncUp() { var items = _playerItemDao.GetUnsynchronizedItems(); if (items.Count > 0) { int numRemaining = items.Count; Logger.Info($"There are {numRemaining} items remaining to be synchronized to azure"); while (numRemaining > 0) { int numTaken = Math.Min(items.Count, 100); var batch = items .Skip(items.Count - numRemaining) .Take(numTaken) .Select(ItemConverter.ToUpload) .ToList(); Logger.Info($"Synchronizing {numTaken} items to azure"); try { var mapping = _azureSyncService.Save(batch); _playerItemDao.SetAzureIds(mapping.Items); if (mapping.IsClosed) { _azurePartitionDao.Save(new AzurePartition { Id = mapping.Partition, IsActive = false }); Logger.Debug($"Storing partition {mapping.Partition} as closed."); } numRemaining -= numTaken; } catch (AggregateException ex) { Logger.Warn(ex.Message, ex); return; } catch (WebException ex) { Logger.Warn(ex.Message, ex); return; } catch (Exception ex) { ExceptionReporter.ReportException(ex, "SyncUp"); return; } } Logger.Info("Upload complete"); OnUploadComplete?.Invoke(this, null); } }
/// <summary> /// Attempting to run a second copy of the program /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void singleInstance_ArgumentsReceived(object _, ArgumentsReceivedEventArgs e) { try { if (_mw != null) { _mw.Invoke((MethodInvoker) delegate { _mw.notifyIcon1_MouseDoubleClick(null, null); }); _mw.Invoke((MethodInvoker) delegate { _mw.Activate(); }); } } catch (Exception ex) { ExceptionReporter.ReportException(ex, "singleInstance_ArgumentsReceived"); } }
public static string GetProcessPath(uint pid) { try { Process proc = Process.GetProcessById((int)pid); return(proc.MainModule.FileName.ToString()); } catch (Exception ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex, "GetProcessPath"); return(string.Empty); } }
private void SyncDown(BuddySubscription subscription) { try { Logger.Debug("Checking buddy cloud for new items.."); // Fetching the known IDs will allow us to skip the items we just uploaded. A massive issue if you just logged on and have 10,000 items for download. var knownItems = _buddyItemDao.GetOnlineIds(subscription); var sync = Get(subscription); // Skip items we've already have var items = sync.Items .Where(item => !knownItems.Contains(item.Id)) .Select(item => ToBuddyItem(subscription, item)) .ToList(); // Store items in batches, to prevent IA just freezing up if we happen to get 10-20,000 items. var batches = BatchUtil.ToBatches <BuddyItem>(items); foreach (var batch in batches) { Logger.Debug($"Storing batch of {batch.Count} items"); _buddyItemDao.Save(subscription, batch); } _buddyItemDao.UpdateNames(items); // Delete items that no longer exist _buddyItemDao.Delete(subscription, sync.Removed); // Store timestamp to db subscription.LastSyncTimestamp = sync.Timestamp; _subscriptionRepo.Update(subscription); Logger.Debug($"Fetched {items.Count} items, new timestamp is {sync.Timestamp}"); } catch (AggregateException ex) { Logger.Warn(ex.Message, ex); return; } catch (WebException ex) { Logger.Warn(ex.Message, ex); return; } catch (Exception ex) { ExceptionReporter.ReportException(ex, "SyncDown"); Logger.Warn(ex); return; } }
/// <summary> /// Download items from online sync /// </summary> /// <returns>True if there are additional items to be downloaded</returns> private bool SyncDown() { try { Logger.Debug("Checking cloud sync for new items.."); // Fetching the known IDs will allow us to skip the items we just uploaded. A massive issue if you just logged on and have 10,000 items for download. var knownItems = _playerItemDao.GetOnlineIds(); var deletedItems = _playerItemDao.GetItemsMarkedForOnlineDeletion(); var timestamp = _settings.GetPersistent().CloudUploadTimestamp; var sync = _cloudSyncService.Get(timestamp); // Skip items we've deleted locally var items = sync.Items .Where(item => deletedItems.All(deleted => deleted.Id != item.Id)) .Where(item => !knownItems.Contains(item.Id)) .Select(ItemConverter.ToPlayerItem) .ToList(); // Store items in batches, to prevent IA just freezing up if we happen to get 10-20,000 items. var batches = ToBatches(items); foreach (var batch in batches) { Logger.Debug($"Storing batch of {batch.Count} items"); _playerItemDao.Save(batch); } _playerItemDao.Delete(sync.Removed); _settings.GetPersistent().CloudUploadTimestamp = sync.Timestamp; Logger.Debug($"Updated/Merged in {items.Count} items, new timestamp is {sync.Timestamp}"); return(sync.IsPartial); } catch (AggregateException ex) { Logger.Warn(ex.Message, ex); return(false); } catch (WebException ex) { Logger.Warn(ex.Message, ex); return(false); } catch (Exception ex) { ExceptionReporter.ReportException(ex, "SyncDown"); Logger.Warn(ex); return(false); } }
/// <summary> /// Attempting to run a second copy of the program /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void singleInstance_ArgumentsReceived(object _, ArgumentsReceivedEventArgs e) { try { if (_mw != null) { Action <string[]> restoreWindow = arguments => { _mw.WindowState = FormWindowState.Normal; _mw.Activate(); }; _mw.Invoke(restoreWindow); } } catch (Exception ex) { ExceptionReporter.ReportException(ex, "singleInstance_ArgumentsReceived"); } }
public static bool VerifyInjection(long pid, string dll) { FixRegistryNagOnListDlls(); Logger.Info("Running Listdlls..."); if (File.Exists("Listdlls.exe")) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "Listdlls.exe"; startInfo.Arguments = $"{pid}"; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; Process processTemp = new Process(); processTemp.StartInfo = startInfo; processTemp.EnableRaisingEvents = true; try { string spid = pid.ToString(); processTemp.Start(); processTemp.WaitForExit(3000); List <string> output = new List <string>(); while (!processTemp.StandardOutput.EndOfStream) { string line = processTemp.StandardOutput.ReadLine(); output.Add(line); if (line.Contains(dll)) { return(true); } } } catch (Exception ex) { Logger.Warn("Exception while attempting to verify injection.. " + ex.Message + ex.StackTrace); ExceptionReporter.ReportException(ex); } } else { Logger.Warn("Could not find Listdlls.exe, unable to verify successful injection."); } return(false); }
private bool StoreItemsToDatabase(ICollection <Item> items, string mod, bool isHardcore) { // Convert the items var playerItems = items.Select(item => TransferStashService.Map(item, mod, isHardcore)).ToList(); try { _playerItemDao.Save(playerItems); } catch (Exception ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex, "StoreItems"); return(false); } return(true); }
/// <summary> /// Write the GD Stash file /// </summary> /// <param name="filename"></param> /// <param name="stash"></param> /// <returns></returns> public bool SafelyWriteStash(string filename, Stash stash) { try { var tempName = $"{filename}-{DateTime.UtcNow.ToTimestamp()}.ia"; // Store the stash file in a temporary location var dataBuffer = new DataBuffer(); stash.Write(dataBuffer); DataBuffer.WriteBytesToDisk(tempName, dataBuffer.Data); // Get the current backup number var backupNumber = _settings.GetLocal().BackupNumber; _settings.GetLocal().BackupNumber = (backupNumber + 1) % 1000; // Back up the existing stash and replace with new stash file var backupLocation = Path.Combine(GlobalPaths.BackupLocation, $"transfer.{backupNumber:00}.gs_"); File.Copy(filename, backupLocation, true); File.Copy(tempName, filename, true); Logger.Info($"The previous stash file has been backed up as {backupLocation}"); // Delete the temporary file if (File.Exists(tempName)) { File.Delete(tempName); } return(true); } catch (FileNotFoundException ex) { Logger.Warn("Could not locate the temporary stash file, this is usually caused by write protections, such as Windows 10 anti ransomware and similar issues denying IA permission to write to files."); Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex, "SafelyWriteDatabase"); _helpService.ShowHelp(HelpService.HelpType.WindowsAntiRansomwareIssue); return(false); } catch (UnauthorizedAccessException ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex, "SafelyWriteDatabase"); return(false); } }
/// <summary> /// Upgrade any settings if required /// This happens for just about every compile /// </summary> private static bool UpgradeSettings() { try { if (Properties.Settings.Default.CallUpgrade) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.CallUpgrade = false; Logger.Info("Settings upgraded.."); return(true); } } catch (Exception ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex); } return(false); }
public bool Delete(List <AzureItemDeletionDto> items) { try { var json = JsonConvert.SerializeObject(items); return(_restService.Post(AzureUris.DeleteItemsUrl, json)); } catch (AggregateException ex) { Logger.Warn(ex.Message, ex); return(false); } catch (WebException ex) { Logger.Warn(ex.Message, ex); return(false); } catch (Exception ex) { ExceptionReporter.ReportException(ex, "AzureSyncService"); return(false); } }
private void Loop(object sender, DoWorkEventArgs e) { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "ItemSynchroniser"; } BackgroundWorker bw = sender as BackgroundWorker; try { while (!bw.CancellationPending) { try { Thread.Sleep(1); } catch (Exception) { } if (_authenticationDelay > DateTime.UtcNow) { continue; } if (DateTime.UtcNow >= _nextUpload) { Delete(); Upload(); } if (DateTime.UtcNow >= _nextDownload) { Download(); } } } // Hopefully these are just IO exceptions, time will tell. catch (Exception ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex); } }
public override void Run() { while (true) { IList <T> inputs = null; try { // Wait for notification to start the merge... lock (pendingToBeMerged) { while (pendingToBeMerged.Count <= 0) { Sharpen.Runtime.Wait(pendingToBeMerged); } // Pickup the inputs to merge. inputs = pendingToBeMerged.RemoveFirst(); } // Merge Merge(inputs); } catch (Exception) { numPending.Set(0); return; } catch (Exception t) { numPending.Set(0); reporter.ReportException(t); return; } finally { lock (this) { numPending.DecrementAndGet(); Sharpen.Runtime.NotifyAll(this); } } } }
/// <summary> /// Delete a player item and all its stats /// </summary> public override void Remove(PlayerItem obj) { long?onlineId = obj.OnlineId; using (ISession session = SessionCreator.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.CreateQuery($"DELETE FROM {nameof(PlayerItemStat)} WHERE {nameof(PlayerItemStat.PlayerItemId)} = :id") .SetParameter("id", obj.Id) .ExecuteUpdate(); session.CreateQuery($"DELETE FROM {nameof(PlayerItemRecord)} WHERE {nameof(PlayerItemRecord.PlayerItemId)} = :id") .SetParameter("id", obj.Id) .ExecuteUpdate(); session.Delete(obj); transaction.Commit(); } // Mark item for deletion from the online backup if (onlineId.HasValue) { try { using (ITransaction transaction = session.BeginTransaction()) { session.SaveOrUpdate(new DeletedPlayerItem { OID = onlineId.Value }); transaction.Commit(); } } catch (Exception ex) { Logger.Warn("Unable to mark item for deletion, duplication may occur"); Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex); } } } }
/// <summary> /// Upgrade any settings if required /// This happens for just about every compile /// </summary> private static void UpgradeSettings(IPlayerItemDao playerItemDao) { try { if (Properties.Settings.Default.CallUpgrade) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.CallUpgrade = false; Logger.Info("Settings upgraded.."); #if !DEBUG // If we don't also update item stats, a lot of whining will ensue. // This accounts for most database updates (new fields added that needs to get populated etc) UpdatingPlayerItemsScreen x = new UpdatingPlayerItemsScreen(playerItemDao); x.ShowDialog(); #endif } } catch (Exception ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex); } }
/// <summary> /// Store all the items /// ----UNTRUE?: If an item cannot be stored (missing record), it is returned so it can be re-written to stash. /// </summary> /// <param name="items"></param> /// <returns></returns> private List <PlayerItem> StoreItemsToDatabase(ICollection <Item> items, string mod, bool isHardcore, bool isExpansion1) { List <PlayerItem> playerItems = new List <PlayerItem>(); foreach (Item item in items) { PlayerItem newItem = Map(item, mod, isHardcore, isExpansion1); playerItems.Add(newItem); } try { _playerItemDao.Save(playerItems); } catch (Exception ex) { Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); ExceptionReporter.ReportException(ex, "StoreItems"); return(null); } return(playerItems); }
private void bw_DoWork(object sender, DoWorkEventArgs e) { try { BackgroundWorker worker = sender as BackgroundWorker; if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "InjectionHelper"; } while (!worker.CancellationPending) { process(worker, e.Argument as RunArguments); } } catch (Exception ex) { Logger.Fatal(ex.Message); Logger.Fatal(ex.StackTrace); ExceptionReporter.ReportException(ex); throw; } }
private void bw_DoWork(object sender, DoWorkEventArgs e) { try { if (Thread.CurrentThread.Name == null) { Thread.CurrentThread.Name = "Backup"; } BackgroundWorker worker = sender as BackgroundWorker; ICloudBackup b = e.Argument as ICloudBackup; while (!worker.CancellationPending) { Thread.Sleep(10); b.Update(); } } catch (Exception ex) { logger.Fatal(ex.Message); logger.Fatal(ex.StackTrace); ExceptionReporter.ReportException(ex); throw; } }
private void SyncUp() { var items = _playerItemDao.GetUnsynchronizedItems(); var batches = ToBatches(items); foreach (var batch in batches) { Logger.Info($"Synchronizing batch with {batch.Count} items to cloud"); try { if (_cloudSyncService.Save(batch.Select(ItemConverter.ToUpload).ToList())) { // TODO: Hopefully all were stored? Logger.Info($"Upload successful, marking {batch.Count} as synchronized"); _playerItemDao.SetAsSynchronized(batch); } else { Logger.Warn($"Upload of {batch.Count} items unsuccessful"); } } catch (AggregateException ex) { Logger.Warn(ex.Message, ex); return; } catch (WebException ex) { Logger.Warn(ex.Message, ex); return; } catch (Exception ex) { ExceptionReporter.ReportException(ex, "SyncUp"); return; } } Logger.Info($"Upload complete ({items.Count} items)"); OnUploadComplete?.Invoke(this, null); }
public ExitCode Run(string[] arguments) { ExceptionReporter reporter = new ExceptionReporter(_console); Options options = new Options(); if (!options.ParseArguments(arguments)) { _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } ISpecificationRunListener mainListener = null; do { List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>(); var timingListener = new TimingRunListener(); listeners.Add(timingListener); if (options.TeamCityIntegration) { mainListener = new TeamCityReporter(_console.WriteLine, timingListener); } else { mainListener = new RunListener(_console, options.Silent, timingListener); } try { if (!String.IsNullOrEmpty(options.HtmlPath)) { if (IsHtmlPathValid(options.HtmlPath)) { listeners.Add(GetHtmlReportListener(options)); } else { _console.WriteLine("Invalid html path:" + options.HtmlPath); _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } } if (!String.IsNullOrEmpty(options.XmlPath)) { if (IsHtmlPathValid(options.XmlPath)) { listeners.Add(GetXmlReportListener(options)); } else { _console.WriteLine("Invalid xml path:" + options.XmlPath); _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } } listeners.Add(mainListener); if (options.AssemblyFiles.Count == 0) { _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } _console.WriteLine("Files Count: {0} Name: {1}", options.AssemblyFiles.Count, options.AssemblyFiles.Count > 0?options.AssemblyFiles[options.AssemblyFiles.Count-1]:"none"); bool runXap = options.AssemblyFiles.Count > 0 && options.AssemblyFiles[options.AssemblyFiles.Count-1].EndsWith(".xap", StringComparison.OrdinalIgnoreCase); if (!options.WcfListen && !runXap) { listeners.Add(new AssemblyLocationAwareListener()); var listener = new AggregateRunListener(listeners); ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions()); List<Assembly> assemblies = new List<Assembly>(); foreach (string assemblyName in options.AssemblyFiles) { if (!File.Exists(assemblyName)) { throw NewException.MissingAssembly(assemblyName); } Assembly assembly = Assembly.LoadFrom(assemblyName); assemblies.Add(assembly); } specificationRunner.RunAssemblies(assemblies); } else { var completionListener = new CompletionListener(); listeners.Add(completionListener); var listener = new AggregateRunListener(listeners); var proxy = new WcfRunnerProxy(listener); ServiceHost host = null; try { host = new ServiceHost(proxy); host.AddServiceEndpoint(typeof(ISpecificationRunListener), new BasicHttpBinding(), new Uri("http://localhost:5931/MSpecListener")); ((System.ServiceModel.Description.ServiceDebugBehavior)host.Description.Behaviors[typeof(System.ServiceModel.Description.ServiceDebugBehavior)]).IncludeExceptionDetailInFaults = true; var smb = new System.ServiceModel.Description.ServiceMetadataBehavior(); smb.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15; host.Description.Behaviors.Add(smb); host.AddServiceEndpoint(typeof(System.ServiceModel.Description.IMetadataExchange), System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:5931/MSpecListener/MEX"); host.Open(); _console.WriteLine("========================================================================="); _console.WriteLine("Waiting for test results via WCF at http://localhost:5931/MSpecListener"); if (runXap) { var xap = options.AssemblyFiles[options.AssemblyFiles.Count-1]; if (!File.Exists(xap)) { throw NewException.MissingAssembly(xap); } var runner = new Wp7DeviceRunner(true); runner.RunXap(xap); } completionListener.WaitForRunCompletion(); System.Threading.Thread.Sleep(1000); } finally { if (host != null && host.State != CommunicationState.Faulted) host.Close(); } } } catch (Exception ex) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); reporter.ReportException(ex); return ExitCode.Error; } } while (options.Loop); if (mainListener != null && mainListener is ISpecificationResultProvider) { var errorProvider = (ISpecificationResultProvider)mainListener; if (errorProvider.FailureOccured) { Console.WriteLine("Generic failure occurred, no idea what this is"); return ExitCode.Failure; } } return ExitCode.Success; }
public ExitCode Run(string[] arguments) { ExceptionReporter reporter = new ExceptionReporter(_console); Options options = new Options(); if (!options.ParseArguments(arguments)) { _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>(); var runListener = new RunListener(_console, options.Silent); try { if (!String.IsNullOrEmpty(options.HtmlPath)) { if (IsHtmlPathValid(options.HtmlPath)) { listeners.Add(GetHtmlReportListener(options)); } else { _console.WriteLine("Invalid html path:" + options.HtmlPath); _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } } listeners.Add(runListener); if (options.AssemblyFiles.Count == 0) { _console.WriteLine(Resources.UsageStatement); return ExitCode.Failure; } var listener = new AggregateRunListener(listeners); ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions()); List<Assembly> assemblies = new List<Assembly>(); foreach (string assemblyName in options.AssemblyFiles) { if (!File.Exists(assemblyName)) { throw NewException.MissingAssembly(assemblyName); } Assembly assembly = Assembly.LoadFrom(assemblyName); assemblies.Add(assembly); } specificationRunner.RunAssemblies(assemblies); } catch(Exception ex) { reporter.ReportException(ex); return ExitCode.Error; } if (runListener.FailureOccured) { return ExitCode.Failure; } return ExitCode.Success; }
public ExitCode Run(string[] arguments) { ExceptionReporter reporter = new ExceptionReporter(_console); Options options = new Options(); if (!options.ParseArguments(arguments)) { _console.WriteLine(Options.Usage()); return ExitCode.Failure; } List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>(); var timingListener = new TimingRunListener(); listeners.Add(timingListener); listeners.Add(new AssemblyLocationAwareListener()); ISpecificationRunListener mainListener; if (options.TeamCityIntegration) { mainListener = new TeamCityReporter(_console.WriteLine, timingListener); } else { mainListener = new RunListener(_console, options.Silent, timingListener); } try { if (!String.IsNullOrEmpty(options.HtmlPath)) { if (IsHtmlPathValid(options.HtmlPath)) { listeners.Add(GetHtmlReportListener(options)); } else { _console.WriteLine("Invalid html path:" + options.HtmlPath); _console.WriteLine(Options.Usage()); return ExitCode.Failure; } } if (!String.IsNullOrEmpty(options.XmlPath)) { if (IsHtmlPathValid(options.XmlPath)) { listeners.Add(GetXmlReportListener(options, timingListener)); } else { _console.WriteLine("Invalid xml path:" + options.XmlPath); _console.WriteLine(Options.Usage()); return ExitCode.Failure; } } listeners.Add(mainListener); if (options.AssemblyFiles.Count == 0) { _console.WriteLine(Options.Usage()); return ExitCode.Failure; } var listener = new AggregateRunListener(listeners); ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions()); List<Assembly> assemblies = new List<Assembly>(); foreach (string assemblyName in options.AssemblyFiles) { if (!File.Exists(assemblyName)) { throw NewException.MissingAssembly(assemblyName); } Assembly assembly = Assembly.LoadFrom(assemblyName); assemblies.Add(assembly); } specificationRunner.RunAssemblies(assemblies); } catch (Exception ex) { reporter.ReportException(ex); return ExitCode.Error; } if (mainListener is ISpecificationResultProvider) { var errorProvider = (ISpecificationResultProvider)mainListener; if (errorProvider.FailureOccurred) { return ExitCode.Failure; } } return ExitCode.Success; }
public ExitCode Run(string[] arguments) { ExceptionReporter reporter = new ExceptionReporter(_console); Options options = new Options(); if (!options.ParseArguments(arguments)) { _console.WriteLine(Options.Usage()); return ExitCode.Failure; } List<ISpecificationRunListener> listeners = new List<ISpecificationRunListener>(); var timingListener = new TimingRunListener(); listeners.Add(timingListener); listeners.Add(new AssemblyLocationAwareListener()); ISpecificationRunListener mainListener; if (options.TeamCityIntegration || Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") != null) { mainListener = new TeamCityReporter(_console.WriteLine, timingListener); } else if(options.TerseOutput) { mainListener = new TerseSpecFormatter(Console.Write, timingListener); } else { mainListener = new RunListener(_console, options.Silent, timingListener); } try { if (!String.IsNullOrEmpty(options.HtmlPath)) { if (IsHtmlPathValid(options.HtmlPath)) { listeners.Add(GetHtmlReportListener(options)); } else { _console.WriteLine("Invalid html path:" + options.HtmlPath); _console.WriteLine(Options.Usage()); return ExitCode.Failure; } } if (!String.IsNullOrEmpty(options.XmlPath)) { if (IsHtmlPathValid(options.XmlPath)) { listeners.Add(GetXmlReportListener(options, timingListener)); } else { _console.WriteLine("Invalid xml path:" + options.XmlPath); _console.WriteLine(Options.Usage()); return ExitCode.Failure; } } listeners.Add(mainListener); if (options.AssemblyFiles.Count == 0) { _console.WriteLine(Options.Usage()); return ExitCode.Failure; } var listener = new AggregateRunListener(listeners); ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions()); List<Assembly> assemblies = new List<Assembly>(); foreach (string assemblyName in options.AssemblyFiles) { if (!File.Exists(assemblyName)) { throw NewException.MissingAssembly(assemblyName); } Assembly assembly = Assembly.LoadFrom(assemblyName); assemblies.Add(assembly); } if (options.WaitForDebugger) { WaitForDebugger(); if (Debugger.IsAttached == false) { _console.WriteLine("Fatal error: Timeout while waiting for debugger to attach"); return ExitCode.Failure; } } specificationRunner.RunAssemblies(assemblies); } catch (Exception ex) { reporter.ReportException(ex); return ExitCode.Error; } if (mainListener is ISpecificationResultProvider) { var errorProvider = (ISpecificationResultProvider)mainListener; if (errorProvider.FailureOccurred) { return ExitCode.Failure; } } return ExitCode.Success; }
public ExitCode Run(string[] arguments) { ExceptionReporter reporter = new ExceptionReporter(_console); Options options = new Options(); if (!options.ParseArguments(arguments)) { _console.WriteLine(Options.Usage()); return ExitCode.Failure; } var timer = new TimingRunListener(); var listeners = new List<ISpecificationRunListener> { timer }; ISpecificationRunListener mainListener; if (options.TeamCityIntegration || (!options.DisableTeamCityAutodetection && Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") != null)) { mainListener = new TeamCityReporter(_console.WriteLine, timer); } else { mainListener = new RunListener(_console, DetermineOutput(options, _console), timer); } try { if (!String.IsNullOrEmpty(options.HtmlPath)) { if (IsHtmlPathValid(options.HtmlPath)) { listeners.Add(GetHtmlReportListener(options)); } else { _console.WriteLine("Invalid html path: {0}", options.HtmlPath); _console.WriteLine(Options.Usage()); return ExitCode.Failure; } } if (!String.IsNullOrEmpty(options.XmlPath)) { if (IsHtmlPathValid(options.XmlPath)) { listeners.Add(GetXmlReportListener(options, timer)); } else { _console.WriteLine("Invalid xml path: {0}", options.XmlPath); _console.WriteLine(Options.Usage()); return ExitCode.Failure; } } listeners.Add(mainListener); if (options.AssemblyFiles.Count == 0) { _console.WriteLine(Options.Usage()); return ExitCode.Failure; } var listener = new AggregateRunListener(listeners); ISpecificationRunner specificationRunner = new AppDomainRunner(listener, options.GetRunOptions()); List<Assembly> assemblies = new List<Assembly>(); foreach (string assemblyName in options.AssemblyFiles) { if (!File.Exists(assemblyName)) { throw NewException.MissingAssembly(assemblyName); } var excludedAssemblies = new[] { "Machine.Specifications.dll", "Machine.Specifications.Clr4.dll" }; if (excludedAssemblies.Any(x => Path.GetFileName(assemblyName) == x)) { _console.WriteLine("Warning: Excluded {0} from the test run because the file name matches either of these: {1}", assemblyName, String.Join(", ", excludedAssemblies)); continue; } Assembly assembly = Assembly.LoadFrom(assemblyName); assemblies.Add(assembly); } if (options.WaitForDebugger) { WaitForDebugger(); if (Debugger.IsAttached == false) { _console.WriteLine("Fatal error: Timeout while waiting for debugger to attach"); return ExitCode.Failure; } } specificationRunner.RunAssemblies(assemblies); } catch (Exception ex) { reporter.ReportException(ex); return ExitCode.Error; } if (mainListener is ISpecificationResultProvider) { var errorProvider = (ISpecificationResultProvider)mainListener; if (errorProvider.FailureOccurred) { return ExitCode.Failure; } } return ExitCode.Success; }