/// <summary> /// Log写入 /// </summary> /// <param name="logBean"></param> public void WriteLog(MsgLevel level, string message) { switch (level) { case MsgLevel.Debug: basicLog?.Debug(message); break; case MsgLevel.Info: basicLog?.Info(message); break; case MsgLevel.Warn: basicLog?.Warn(message); break; case MsgLevel.Error: errLog?.Error(message); break; case MsgLevel.Fatal: errLog?.Fatal(message); break; } }
public void WriteLog(LogEnum name, LogLevel level, string logContent) { log = log4net.LogManager.GetLogger(name.ToString()); //log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); switch (level) { case LogLevel.DEBUG: log.Debug(logContent); break; case LogLevel.ERROR: log.Error(logContent); break; case LogLevel.FATAL: log.Fatal(logContent); break; case LogLevel.INFO: log.Info(logContent); break; case LogLevel.WARN: log.Warn(logContent); break; default: log.Debug(logContent); break; } }
public IEnumerable <OHLC> GetDataFromDate(string symbol, DateTime fromDate) { if (providers.ContainsKey(symbol)) { return(providers[symbol].GetDataFromDate(fromDate)); } else { logger?.Warn($@"No provider found for symbol [{(string.IsNullOrEmpty(symbol) ? "" : symbol)}]"); return(new OHLC[0]); } }
/// <summary> /// /// </summary> /// <param name="connection"></param> /// <param name="vm">The VM to export.</param> /// <param name="host">Used for filtering purposes. May be null.</param> private void Execute(IXenConnection connection, VM vm, Host host) { /* * These properties have not been copied over to the new save file dialog. * * dlg.AddExtension = true; * dlg.CheckPathExists = true; * dlg.CreatePrompt = false; * dlg.CheckFileExists = false; * dlg.OverwritePrompt = true; * dlg.ValidateNames = true;*/ string filename; bool verify; // Showing this dialog has the (undocumented) side effect of changing the working directory // to that of the file selected. This means a handle to the directory persists, making // it undeletable until the program exits, or the working dir moves on. So, save and // restore the working dir... String oldDir = ""; try { oldDir = Directory.GetCurrentDirectory(); while (true) { ExportVMDialog dlg = new ExportVMDialog(); dlg.DefaultExt = "xva"; dlg.Filter = Messages.MAINWINDOW_XVA_BLURB; dlg.Title = Messages.MAINWINDOW_XVA_TITLE; if (dlg.ShowDialog(Parent) != DialogResult.OK) { return; } filename = dlg.FileName; verify = dlg.Verify; // CA-12975: Warn the user if the export operation does not have enough disk space to // complete. This is an approximation only. Win32.DiskSpaceInfo diskSpaceInfo = null; try { diskSpaceInfo = Win32.GetDiskSpaceInfo(dlg.FileName); } catch (Exception exn) { log.Warn(exn, exn); } if (diskSpaceInfo == null) { // Could not determine free disk space. Carry on regardless. break; } else { ulong freeSpace = diskSpaceInfo.FreeBytesAvailable; decimal neededSpace = vm.GetRecommendedExportSpace(Properties.Settings.Default.ShowHiddenVMs); ulong spaceLeft = 100 * Util.BINARY_MEGA; // We want the user to be left with some disk space afterwards if (neededSpace >= freeSpace - spaceLeft) { string msg = string.Format(Messages.CONFIRM_EXPORT_NOT_ENOUGH_MEMORY, Util.DiskSizeString((long)neededSpace), Util.DiskSizeString((long)freeSpace), vm.Name()); DialogResult dr; using (var d = new WarningDialog(msg, new ThreeButtonDialog.TBDButton(Messages.CONTINUE_WITH_EXPORT, DialogResult.OK), new ThreeButtonDialog.TBDButton(Messages.CHOOSE_ANOTHER_DESTINATION, DialogResult.Retry), ThreeButtonDialog.ButtonCancel) { HelpNameSetter = "ExportVmDialogInsufficientDiskSpace" }) { dr = d.ShowDialog(Parent); } if (dr == DialogResult.Retry) { continue; } else if (dr == DialogResult.Cancel) { return; } } if (diskSpaceInfo.IsFAT && neededSpace > (4 * Util.BINARY_GIGA) - 1) { string msg = string.Format(Messages.CONFIRM_EXPORT_FAT, Util.DiskSizeString((long)neededSpace), Util.DiskSizeString(4 * Util.BINARY_GIGA), vm.Name()); DialogResult dr; using (var d = new WarningDialog(msg, new ThreeButtonDialog.TBDButton(Messages.CONTINUE_WITH_EXPORT, DialogResult.OK), new ThreeButtonDialog.TBDButton(Messages.CHOOSE_ANOTHER_DESTINATION, DialogResult.Retry), ThreeButtonDialog.ButtonCancel) { HelpNameSetter = "ExportVmDialogFSLimitExceeded" }) { dr = d.ShowDialog(Parent); } if (dr == DialogResult.Retry) { continue; } else if (dr == DialogResult.Cancel) { return; } } break; } } } finally { Directory.SetCurrentDirectory(oldDir); } new ExportVmAction(connection, host, vm, filename, verify).RunAsync(); }
private void Init() { // item db check RecruitsShortSword = GameServer.Database.FindObjectByKey <ItemTemplate>("recruits_short_sword_hib"); if (RecruitsShortSword == null) { RecruitsShortSword = new ItemTemplate(); RecruitsShortSword.Name = LanguageMgr.GetTranslation(ServerProperties.Properties.DB_LANGUAGE, "Hib.MagicalBacklash.Init.Text1"); if (log.IsWarnEnabled) { log.Warn("Could not find " + RecruitsShortSword.Name + ", creating it ..."); } RecruitsShortSword.Level = 5; RecruitsShortSword.Weight = 18; RecruitsShortSword.Model = 3; RecruitsShortSword.Hand = 2; RecruitsShortSword.Object_Type = (int)eObjectType.Blades; RecruitsShortSword.Item_Type = (int)eEquipmentItems.RIGHT_HAND; RecruitsShortSword.Id_nb = "recruits_short_sword_hib"; RecruitsShortSword.Price = 0; RecruitsShortSword.IsPickable = true; RecruitsShortSword.IsDropable = false; // can't be sold to merchand RecruitsShortSword.DPS_AF = 24; RecruitsShortSword.SPD_ABS = 30; RecruitsShortSword.Bonus = 1; RecruitsShortSword.Bonus1 = 3; RecruitsShortSword.Bonus1Type = (int)eProperty.Strength; RecruitsShortSword.Bonus2 = 1; RecruitsShortSword.Bonus2Type = (int)eProperty.AllMeleeWeaponSkills; RecruitsShortSword.Bonus3 = 1; RecruitsShortSword.Bonus3Type = (int)eProperty.Resist_Crush; RecruitsShortSword.Bonus4 = 1; RecruitsShortSword.Bonus4Type = (int)eProperty.Resist_Thrust; RecruitsShortSword.Bonus5 = 1; RecruitsShortSword.Bonus5Type = (int)eProperty.Quickness; RecruitsShortSword.Quality = 100; RecruitsShortSword.Condition = 50000; RecruitsShortSword.MaxCondition = 50000; RecruitsShortSword.Durability = 50000; RecruitsShortSword.MaxDurability = 50000; RecruitsShortSword.Type_Damage = 2; // You don't have to store the created item in the db if you don't want, // it will be recreated each time it is not found, just comment the following // line if you rather not modify your database if (SAVE_INTO_DATABASE) { GameServer.Database.AddObject(RecruitsShortSword); } } RecruitsDirk = GameServer.Database.FindObjectByKey <ItemTemplate>("recruits_dirk"); if (RecruitsDirk == null) { RecruitsDirk = new ItemTemplate(); RecruitsDirk.Name = LanguageMgr.GetTranslation(ServerProperties.Properties.DB_LANGUAGE, "Hib.MagicalBacklash.Init.Text2"); if (log.IsWarnEnabled) { log.Warn("Could not find " + RecruitsDirk.Name + ", creating it ..."); } RecruitsDirk.Level = 5; RecruitsDirk.Weight = 8; RecruitsDirk.Model = 21; RecruitsDirk.Hand = 2; RecruitsDirk.Object_Type = (int)eObjectType.ThrustWeapon; RecruitsDirk.Item_Type = (int)eEquipmentItems.RIGHT_HAND; RecruitsDirk.Id_nb = "recruits_dirk"; RecruitsDirk.Price = 0; RecruitsDirk.IsPickable = true; RecruitsDirk.IsDropable = false; // can't be sold to merchand RecruitsDirk.DPS_AF = 24; RecruitsDirk.SPD_ABS = 26; RecruitsDirk.Bonus = 1; RecruitsDirk.Bonus1 = 3; RecruitsDirk.Bonus1Type = (int)eProperty.Dexterity; RecruitsDirk.Bonus2 = 1; RecruitsDirk.Bonus2Type = (int)eProperty.AllMeleeWeaponSkills; RecruitsDirk.Bonus3 = 1; RecruitsDirk.Bonus3Type = (int)eProperty.Resist_Crush; RecruitsDirk.Bonus4 = 1; RecruitsDirk.Bonus4Type = (int)eProperty.Resist_Thrust; RecruitsDirk.Bonus5 = 1; RecruitsDirk.Bonus5Type = (int)eProperty.Strength; RecruitsDirk.Quality = 100; RecruitsDirk.Condition = 50000; RecruitsDirk.MaxCondition = 50000; RecruitsDirk.Durability = 50000; RecruitsDirk.MaxDurability = 50000; RecruitsDirk.Type_Damage = 3; // You don't have to store the created item in the db if you don't want, // it will be recreated each time it is not found, just comment the following // line if you rather not modify your database if (SAVE_INTO_DATABASE) { GameServer.Database.AddObject(RecruitsDirk); } } RecruitsClub = GameServer.Database.FindObjectByKey <ItemTemplate>("recruits_club"); if (RecruitsClub == null) { RecruitsClub = new ItemTemplate(); RecruitsClub.Name = LanguageMgr.GetTranslation(ServerProperties.Properties.DB_LANGUAGE, "Hib.MagicalBacklash.Init.Text3"); if (log.IsWarnEnabled) { log.Warn("Could not find " + RecruitsClub.Name + ", creating it ..."); } RecruitsClub.Level = 5; RecruitsClub.Weight = 24; RecruitsClub.Model = 14;// 11 RecruitsClub.Hand = 2; RecruitsClub.Object_Type = (int)eObjectType.Blunt; RecruitsClub.Item_Type = (int)eEquipmentItems.RIGHT_HAND; RecruitsClub.Id_nb = "recruits_club"; RecruitsClub.Price = 0; RecruitsClub.IsPickable = true; RecruitsClub.IsDropable = false; // can't be sold to merchand RecruitsClub.DPS_AF = 24; RecruitsClub.SPD_ABS = 30; RecruitsClub.Bonus = 1; RecruitsClub.Bonus1 = 3; RecruitsClub.Bonus1Type = (int)eProperty.Acuity; RecruitsClub.Bonus2 = 1; RecruitsClub.Bonus2Type = (int)eProperty.AllMagicSkills; RecruitsClub.Bonus3 = 1; RecruitsClub.Bonus3Type = (int)eProperty.Resist_Crush; RecruitsClub.Bonus4 = 1; RecruitsClub.Bonus4Type = (int)eProperty.Resist_Thrust; RecruitsClub.Bonus5 = 1; RecruitsClub.Bonus5Type = (int)eProperty.Constitution; RecruitsClub.Quality = 100; RecruitsClub.Condition = 50000; RecruitsClub.MaxCondition = 50000; RecruitsClub.Durability = 50000; RecruitsClub.MaxDurability = 50000; RecruitsClub.Type_Damage = 1; // You don't have to store the created item in the db if you don't want, // it will be recreated each time it is not found, just comment the following // line if you rather not modify your database if (SAVE_INTO_DATABASE) { GameServer.Database.AddObject(RecruitsClub); } } RecruitsStaff = GameServer.Database.FindObjectByKey <ItemTemplate>("recruits_staff"); if (RecruitsStaff == null) { RecruitsStaff = new ItemTemplate(); RecruitsStaff.Name = LanguageMgr.GetTranslation(ServerProperties.Properties.DB_LANGUAGE, "Hib.MagicalBacklash.Init.Text4"); if (log.IsWarnEnabled) { log.Warn("Could not find " + RecruitsStaff.Name + ", creating it ..."); } RecruitsStaff.Level = 5; RecruitsStaff.Weight = 24; RecruitsStaff.Model = 19; RecruitsStaff.Hand = 1; RecruitsStaff.Object_Type = (int)eObjectType.Staff; RecruitsStaff.Item_Type = (int)eEquipmentItems.TWO_HANDED; RecruitsStaff.Id_nb = "recruits_staff"; RecruitsStaff.Price = 0; RecruitsStaff.IsPickable = true; RecruitsStaff.IsDropable = false; // can't be sold to merchand RecruitsStaff.DPS_AF = 24; RecruitsStaff.SPD_ABS = 37; RecruitsStaff.Bonus = 1; RecruitsStaff.Bonus1 = 3; RecruitsStaff.Bonus1Type = (int)eProperty.Acuity; RecruitsStaff.Bonus2 = 1; RecruitsStaff.Bonus2Type = (int)eProperty.Dexterity; RecruitsStaff.Bonus3 = 1; RecruitsStaff.Bonus3Type = (int)eProperty.Resist_Crush; RecruitsStaff.Bonus4 = 1; RecruitsStaff.Bonus4Type = (int)eProperty.Resist_Thrust; RecruitsStaff.Bonus5 = 1; RecruitsStaff.Bonus5Type = (int)eProperty.AllMagicSkills; RecruitsStaff.Quality = 100; RecruitsStaff.Condition = 50000; RecruitsStaff.MaxCondition = 50000; RecruitsStaff.Durability = 50000; RecruitsStaff.MaxDurability = 50000; RecruitsStaff.Type_Damage = 1; // You don't have to store the created item in the db if you don't want, // it will be recreated each time it is not found, just comment the following // line if you rather not modify your database if (SAVE_INTO_DATABASE) { GameServer.Database.AddObject(RecruitsStaff); } } ItemTemplate nipperwing = new ItemTemplate(); nipperwing.Weight = 0; nipperwing.Condition = 50000; nipperwing.MaxCondition = 50000; nipperwing.Model = 551; nipperwing.Extension = 1; nipperwing.Name = LanguageMgr.GetTranslation(ServerProperties.Properties.DB_LANGUAGE, "Hib.MagicalBacklash.Init.Text5"); Level = 2; QuestGiver = Josson; Rewards.Experience = 90; Rewards.MoneyPercent = 20; Rewards.AddOptionalItem(RecruitsShortSword); Rewards.AddOptionalItem(RecruitsDirk); Rewards.AddOptionalItem(RecruitsClub); Rewards.AddOptionalItem(RecruitsStaff); Rewards.ChoiceOf = 1; OrchardNipperKilled = AddGoal(LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "Hib.MagicalBacklash.Init.Text6"), QuestGoal.GoalType.KillTask, 1, nipperwing); }
/// <summary> /// Write the RAW file metadata to file. /// <param name="rawFile">the RAW file object</param> /// <param name="firstScanNumber">the first scan number</param> /// <param name="lastScanNumber">the last scan number</param> /// </summary> public void WriteJsonMetada(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber) { // Get the start and end time from the RAW file var startTime = rawFile.RunHeaderEx.StartTime; var endTime = rawFile.RunHeaderEx.EndTime; var metadata = new Metadata(); /** File Properties **/ metadata.addFileProperty(new CVTerm("NCIT:C47922", "NCIT", "Pathname", rawFile.FileName)); metadata.addFileProperty(new CVTerm("NCIT:C25714", "NCIT", "Version", rawFile.FileHeader.Revision.ToString())); metadata.addFileProperty(new CVTerm("NCIT:C69199", "NCIT", "Content Creation Date", rawFile.FileHeader.CreationDate.ToString())); metadata.addFileProperty(new CVTerm("NCIT:C25365", "NCIT", "Description", rawFile.FileHeader.FileDescription)); metadata.addScanSetting(new CVTerm("MS:1000016", "MS", "scan start time", startTime.ToString())); metadata.addScanSetting(new CVTerm("MS:1000011", "MS", "mass resolution", rawFile.RunHeaderEx.MassResolution.ToString())); metadata.addScanSetting(new CVTerm("UO:0000002", "MS", "mass unit", rawFile.GetInstrumentData().Units.ToString())); metadata.addScanSetting(new CVTerm("PRIDE:0000478", "PRIDE", "Number of scans", rawFile.RunHeaderEx.SpectraCount.ToString())); metadata.addScanSetting(new CVTerm("PRIDE:0000479", "PRIDE", "MS scan range", firstScanNumber + ":" + lastScanNumber)); metadata.addScanSetting(new CVTerm("PRIDE:0000484", "PRIDE", "Retention time range", startTime + ":" + endTime)); metadata.addScanSetting(new CVTerm("PRIDE:0000485", "PRIDE", "Mz range", rawFile.RunHeaderEx.LowMass + ":" + rawFile.RunHeaderEx.HighMass)); metadata.addInstrumentProperty(new CVTerm("MS:1000494", "MS", "Thermo Scientific instrument model", rawFile.GetInstrumentData().Model)); metadata.addInstrumentProperty(new CVTerm("MS:1000496", "MS", "instrument attribute", rawFile.GetInstrumentData().Name)); metadata.addInstrumentProperty(new CVTerm("MS:1000529", "MS", "instrument serial number", rawFile.GetInstrumentData().SerialNumber)); var msTypes = new Dictionary <string, int>(); double minTime = 1000000000000000; double maxTime = 0; double minMz = 1000000000000000000; double maxMz = 0; double minCharge = 100000000000000; double maxCharge = 0; ICollection <CVTerm> fragmentationType = new HashSet <CVTerm>(CVTerm.CvTermComparer); for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++) { var time = rawFile.RetentionTimeFromScanNumber(scanNumber); // Get the scan filter for this scan number var scanFilter = rawFile.GetFilterForScanNumber(scanNumber); // Get the scan event for this scan number var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber); // Only consider MS2 spectra if (msTypes.ContainsKey(scanFilter.MSOrder.ToString())) { var value = msTypes[scanFilter.MSOrder.ToString()]; value = value + 1; msTypes[scanFilter.MSOrder.ToString()] = value; } else { msTypes.Add(scanFilter.MSOrder.ToString(), 1); } if (time > maxTime) { maxTime = time; } if (time < minTime) { minTime = time; } if (scanFilter.MSOrder == MSOrderType.Ms2) { fragmentationType.Add(parseActivationType(scanFilter.GetActivation(0))); if (scanEvent.ScanData == ScanDataType.Centroid || (scanEvent.ScanData == ScanDataType.Profile)) { try { var reaction = scanEvent.GetReaction(0); var precursorMass = reaction.PrecursorMass; if (precursorMass > maxMz) { maxMz = precursorMass; } if (precursorMass < minMz) { minMz = precursorMass; } } catch (ArgumentOutOfRangeException exception) { Log.Warn("No reaction found for scan " + scanNumber); } // trailer extra data list var trailerData = rawFile.GetTrailerExtraInformation(scanNumber); for (var i = 0; i < trailerData.Length; i++) { if (trailerData.Labels[i] == "Charge State:") { if (Int32.Parse(trailerData.Values[i]) > maxCharge) { maxCharge = Int32.Parse(trailerData.Values[i]); } if (Int32.Parse(trailerData.Values[i]) < minCharge) { maxCharge = Int32.Parse(trailerData.Values[i]); } } } } } } if (minCharge == 100000000000000) { minCharge = 0; } foreach (KeyValuePair <string, int> entry in msTypes) { if (entry.Key.Equals(MSOrderType.Ms.ToString())) { metadata.addMSData(new CVTerm("PRIDE:0000481", "PRIDE", "Number of MS1 spectra", entry.Value.ToString())); } if (entry.Key.Equals(MSOrderType.Ms2.ToString())) { metadata.addMSData(new CVTerm("PRIDE:0000482", "PRIDE", "Number of MS2 spectra", entry.Value.ToString())); } if (entry.Key.Equals(MSOrderType.Ms3.ToString())) { metadata.addMSData(new CVTerm("PRIDE:0000483", "PRIDE", "Number of MS3 spectra", entry.Value.ToString())); } } metadata.addScanSetting(fragmentationType); metadata.addMSData(new CVTerm("PRIDE:0000472", "PRIDE", "MS min charge", minCharge.ToString())); metadata.addMSData(new CVTerm("PRIDE:0000473", "PRIDE", "MS max charge", maxCharge.ToString())); metadata.addMSData(new CVTerm("PRIDE:0000474", "PRIDE", "MS min RT", minTime.ToString())); metadata.addMSData(new CVTerm("PRIDE:0000475", "PRIDE", "MS max RT", maxTime.ToString())); metadata.addMSData(new CVTerm("PRIDE:0000476", "PRIDE", "MS min MZ", minMz.ToString())); metadata.addMSData(new CVTerm("PRIDE:0000477", "PRIDE", "MS min MZ", maxMz.ToString())); // Write the meta data to file var json = JsonConvert.SerializeObject(metadata); json.Replace("\r\n", "\n"); File.WriteAllText(_outputDirectory + "/" + _rawFileNameWithoutExtension + "-metadata.json", json); }
private void Timer_Elapsed(object sender, ElapsedEventArgs e) { string[] files = { }; log.Debug(ID + " - Checking Source lock"); if (!sourceLock) { log.Debug(ID + " - Source lock false"); log.Debug(ID + " - Checking if source folder exists"); if (Directory.Exists(sourceFolder)) { log.Debug(ID + " - Source folder exists"); try { log.Debug(ID + " - Setting source lock"); sourceLock = true; log.Debug(ID + " - Getting filenames from source"); files = Directory.GetFiles(sourceFolder, "*", SearchOption.AllDirectories); } catch (Exception error) { log.Error(ID + " - Unable to get filenames from source"); log.Error(error.Message); log.Debug(ID + " - Unsetting source lock"); sourceLock = false; return; } log.Debug(ID + " - Checking if file count is greater than 0"); if (files.Count <string>() > 0) { log.Debug(string.Format(ID + " - File count is {0}", files.Count <string>())); log.Debug(ID + " - Setting Source Lock to true"); sourceLock = true; log.Debug(string.Format(ID + " - Beginning file iteration of {0}", sourceFolder)); foreach (string file in files) { log.Debug(string.Format(ID + " - Full path is {0}", file)); string fileName = Path.GetFileName(file); log.Debug(string.Format(ID + " - Filename is {0}", fileName)); string tempFile = file; bool success = true; foreach (string rootFolder in destFolders) { string destFolder = ""; string destFile = ""; try { destFolder = Path.Combine(rootFolder, Path.GetDirectoryName(file).Substring(sourceFolder.Length + 1)); destFile = Path.Combine(destFolder, fileName); } catch (Exception error) { log.Error(ID + " - " + error.Message); success = false; break; } log.Debug(string.Format(ID + " - Destination filename is {0}", destFile)); log.Debug(ID + " - Checking if destination folder exists"); if (!Directory.Exists(destFolder)) { log.Debug(string.Format(ID + " - Destination folder {0} did not exist. Creating folder now", destFolder)); try { Directory.CreateDirectory(destFolder); } catch (Exception error) { log.Error(string.Format(ID + " - Unable to create directory: {0}\n\t" + error.Message, destFolder)); break; } } try { log.Debug(string.Format(ID + " - Beginning transfer of {0} to {1}", tempFile, destFile)); File.Copy(tempFile, destFile, true); if (localMove) { tempFile = destFile; } } catch (Exception error) { log.Error(ID + " - " + error.Message); success = false; break; } log.Info(string.Format(ID + " - Successfully copied file {0} to {1}", fileName, destFile)); } if (success) { log.Debug(string.Format(ID + " - Deleting file {0}", file)); try { File.Delete(file); } catch (Exception error) { log.Warn(ID + " - Error deleting file: " + error.Message); } if (Directory.GetFiles(Path.GetDirectoryName(file), "*", SearchOption.AllDirectories).Count() == 0 && Path.GetDirectoryName(file) != sourceFolder) { log.Debug(string.Format(ID + " - Source Folder has had all files copied, removing folder {0}", Path.GetDirectoryName(file))); try { Directory.Delete(Path.GetDirectoryName(file), true); } catch (Exception error) { log.Warn(ID + " - Error deleting folder: " + error.Message); } } } } if (sourceLock) { log.Debug(ID + " - Unsetting source lock"); sourceLock = false; } } else { try { if (Directory.GetDirectories(sourceFolder, "*", SearchOption.AllDirectories).Count() > 0) { foreach (string dir in Directory.GetDirectories(sourceFolder)) { if (Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Count() == 0) { log.Info(string.Format(ID + " - Found empty directory, cleaning up directory {0}", dir)); Directory.Delete(dir, true); } } } } catch (DirectoryNotFoundException error) { log.Warn(error.Message); if (sourceLock) { log.Debug(ID + " - Unsetting source lock"); sourceLock = false; } } catch (Exception error) { log.Debug(ID + " - Folder cleanup error\t" + error.Message); if (sourceLock) { log.Debug(ID + " - Unsetting source lock"); sourceLock = false; } } log.Info(ID + " - No files to move"); if (sourceLock) { log.Debug(ID + " - Unsetting source lock"); sourceLock = false; } } } else { log.Error(string.Format(ID + " - Source folder {0} does not exist", sourceFolder)); } } else { log.Debug(ID + " - Source lock true, file transfer may be in progress"); } }
public void Execute() { if (!viewModel.ValidatableView.Validate()) { return; } foreach (var result in viewModel.InspectionTestResults) { if (!result.Date.IsValid()) { notify.ShowInfo(Program.LanguageManager.GetString(StringResources.WrongDate), Program.LanguageManager.GetString(StringResources.Message_ErrorHeader)); log.Warn("Date limits not valid!"); return; } } var c = repos.ComponentRepo.GetActiveByNumber(viewModel.Component); foreach (var component in c) { repos.ComponentRepo.Evict(component); } if (c != null && c.Count > 0) { notify.ShowInfo( string.Concat(Program.LanguageManager.GetString(StringResources.ComponentNewEdit_Duplicate), " ", viewModel.Number), Program.LanguageManager.GetString(StringResources.ComponentNewEdit_DuplicateHeader)); viewModel.Number = string.Empty; } else { foreach (InspectionTestResult t in viewModel.InspectionTestResults) { if (t.Status != PartInspectionStatus.Pending && t.Inspectors.Count <= 0) { numberOfOperationWithoutInspectors++; } } if (numberOfOperationWithoutInspectors == 0) { try { viewModel.Component.InspectionStatus = viewModel.Component.GetPartInspectionStatus(); repos.BeginTransaction(); viewModel.Component.Number = viewModel.Component.Number.ToUpper(); repos.ComponentRepo.SaveOrUpdate(viewModel.Component); var filesViewModel = viewModel.FilesFormViewModel; //saving attached documents bool fileCopySuccess = true; if (null != filesViewModel) { filesViewModel.FileRepo = repos.FileRepo; viewModel.FilesFormViewModel.Item = viewModel.Component.Id; if (!viewModel.FilesFormViewModel.TrySaveFiles(viewModel.Component)) { fileCopySuccess = false; repos.Rollback(); } } repos.Commit(); repos.ComponentRepo.Evict(viewModel.Component); viewModel.ModifiableView.IsModified = false; viewModel.ModifiableView.UpdateState(); if (fileCopySuccess) { if (null != filesViewModel) { filesViewModel.DetachFileEntities(); } notify.ShowSuccess( string.Concat(Program.LanguageManager.GetString(StringResources.ComponentNewEdit_Saved), viewModel.Number), Program.LanguageManager.GetString(StringResources.ComponentNewEdit_SavedHeader)); } else { notify.ShowError(Program.LanguageManager.GetString(StringResources.ExternalFiles_NotCopied), Program.LanguageManager.GetString(StringResources.ExternalFiles_NotCopied_Header)); } log.Info(string.Format("The entity #{0}, id:{1} has been saved in DB.", viewModel.Component.Number, viewModel.Component.Id)); } catch (RepositoryException ex) { log.Error(ex.Message); notify.ShowFailure(ex.InnerException.Message, ex.Message); } } else { notify.ShowError( Program.LanguageManager.GetString(StringResources.SelectInspectorsForTestResult), Program.LanguageManager.GetString(StringResources.SelectInspectorsForTestResultHeader)); numberOfOperationWithoutInspectors = 0; } } RefreshVisualStateEvent(); }
static void Main(string[] args) { _logger.Info("Hi there."); _logger.Warn("Waiting forever..."); Console.ReadLine(); }
/// <summary> /// Initializes the <c>SteamManager</c>. /// This MUST be called before other Steam operations are executed. /// </summary> /// <returns><c>true</c> if everything initialized properly, <c>false</c> otherwise.</returns> public static bool Init() { if (Enabled) { _log.Warn("Tried to call Init method when SteamManager has already been initialized! Aborting..."); return false; } _log = LogManager.GetLogger(typeof(SteamManager)); try { if (!Steamworks.Load()) { _log.Error("Steamworks failed to load, throwing exception!"); throw new SteamException("Steamworks failed to load.", SteamExceptionType.SteamworksLoadFail); } Client = Steamworks.CreateInterface<ISteamClient010>("SteamClient010"); if (Client == null) { _log.Error("Steamclient is NULL!! Throwing exception!"); throw new SteamException("Steamclient failed to load! Is the client running? (Sharpcraft.Steam.SteamManager.Client == null!)", SteamExceptionType.SteamLoadFail); } Pipe = Client.CreateSteamPipe(); User = Client.ConnectToGlobalUser(Pipe); Friends = Steamworks.CastInterface<ISteamFriends002>(Client.GetISteamFriends(User, Pipe, "SteamFriends002")); if (Friends == null) return false; FriendList = new SteamFriendList(); _steamWatcher = new Timer(SteamCheck, null, 0, 1000); } catch (SteamException ex) { _log.Warn("Warning! SteamManager caught a SteamException exception, returning FALSE. Steam components will NOT LOAD!"); _log.Warn("The SteamException type was: " + System.Enum.GetName(typeof(SteamExceptionType), ex.Type)); return false; } _log.Info("SteamManager has been initialized!"); SteamLoaded = true; Enabled = true; return true; }
//public HttpWebRequest DownloadRequest(long instart, long inend, File file, ShardInfo shard) //{ // string url = $"{_downloadServer.Value.Url}{Uri.EscapeDataString(file.FullPath)}?token={Authent.AccessToken}&client_id={HttpSettings.ClientId}"; // var request = (HttpWebRequest)WebRequest.Create(url); // request.Headers.Add("Accept-Ranges", "bytes"); // request.AddRange(instart, inend); // request.Proxy = HttpSettings.Proxy; // request.CookieContainer = Authent.Cookies; // request.Method = "GET"; // request.ContentType = MediaTypeNames.Application.Octet; // request.Accept = "*/*"; // request.UserAgent = HttpSettings.UserAgent; // request.AllowReadStreamBuffering = false; // request.Timeout = 15 * 1000; // return request; //} public void BanShardInfo(ShardInfo banShard) { //TODO: implement Logger.Warn($"{nameof(MobileRequestRepo)}.{nameof(BanShardInfo)} not implemented"); }
private void SaveSettings() { if (combobox_language.SelectedItem != null) { string newLang = combobox_language.SelectedValue.ToString(); if (!string.IsNullOrEmpty(newLang)) { coreConfiguration.Language = combobox_language.SelectedValue.ToString(); } } coreConfiguration.WindowCaptureMode = GetSelected <WindowCaptureMode>(combobox_window_capture_mode); if (!FilenameHelper.FillVariables(coreConfiguration.OutputFilePath, false).Equals(textbox_storagelocation.Text)) { coreConfiguration.OutputFilePath = textbox_storagelocation.Text; } coreConfiguration.OutputFileJpegQuality = trackBarJpegQuality.Value; List <string> destinations = new List <string>(); if (checkbox_picker.Checked) { destinations.Add(PickerDestination.DESIGNATION); } foreach (int index in destinationsListView.CheckedIndices) { ListViewItem item = destinationsListView.Items[index]; IDestination destination = item.Tag as IDestination; if (item.Checked) { destinations.Add(destination.Designation); } } coreConfiguration.OutputDestinations = destinations; coreConfiguration.CaptureDelay = (int)numericUpDownWaitTime.Value; coreConfiguration.DWMBackgroundColor = colorButton_window_background.SelectedColor; coreConfiguration.UpdateCheckInterval = (int)numericUpDown_daysbetweencheck.Value; IniConfig.Save(); // Make sure the current language & settings are reflected in the Main-context menu MainForm.instance.UpdateUI(); try { // Check if the Run for all is set if (!StartupHelper.checkRunAll()) { // If not set the registry according to the settings if (checkbox_autostartshortcut.Checked) { StartupHelper.setRunUser(); } else { StartupHelper.deleteRunUser(); } } else { // The run key for Greenshot is set for all users, delete the local version! StartupHelper.deleteRunUser(); } } catch (Exception e) { LOG.Warn("Problem checking registry, ignoring for now: ", e); } }
public void emailExists(string email) { if (!map.ContainsKey(email) || map[email].getEmail() != email) { logger.Warn("there is no board with this host email"); throw new Exception("invalid email host"); } }
public void Warn(string format, params object[] args) { _loger.Warn(Format(format, args)); }
/// <summary> /// Read file from device /// </summary> /// <param name="filename"></param> /// <param name="stream"></param> /// <param name="report_progress"></param> /// <param name="token"></param> public void ReadFile(string filename, int size, Stream stream, IProgress <int> report_progress, CancellationToken token) { ClearBuffers(); log.Info($"Receiving file {filename}"); // Create read helper function ReceivedData data; var cmd = String.Format(LuaCode.READ_HELPER, filename); foreach (var line in SplitLines(cmd)) { data = Exchange(line); if (data.Response.IndexOf("unexpected") > -1 || data.Response.IndexOf("stdin") > -1) { log.Error($"Error creating read helper function: {data.Response}"); throw new CommunicationException("Error creating read helper function", data.Response); } } // Call helper function and start reading data = Exchange(LuaCode.READ_START); if (data.Response.IndexOf("unexpected") > -1 || data.Response.IndexOf("stdin") > -1) { log.Error($"Error start reading: {data.Response}"); throw new CommunicationException("Error start reading", data.Response); } int b, buffer_length = 0, data_start_index; int data_start_length = DATA_START.Length, data_start_end_length = DATA_START.Length + DATA_END.Length; byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE]; // Packet size is 1024 bytes while (!BufferEndsWith(buffer, buffer_length, EOL)) { if (token.IsCancellationRequested) { log.Warn($"Cancel request reading file {filename}"); break; } b = this.port.ReadByte(); if (b == -1) { break; } buffer[buffer_length++] = (byte)b; // Check for DATA_END pattern on the end of readed bytes if (BufferEndsWith(buffer, buffer_length, DATA_END)) { // Find position of DATA_START pattern in readed bytes data_start_index = BufferIndexOf(buffer, buffer_length, DATA_START); if (data_start_index > -1) { // Full packet was readed, write it to output stream stream.Write(buffer, data_start_index + data_start_length, buffer_length - data_start_index - data_start_end_length); log.Debug($"{buffer_length} bytes readed"); buffer_length = 0; } // Report progress report_progress?.Report((int)((double)stream.Length / size * 100.0)); } } // Delete helper function data = Exchange(LuaCode.READ_END); if (data.Response.IndexOf("unexpected") > -1 || data.Response.IndexOf("stdin") > -1) { log.Error($"Error deleting read helper function: {data.Response}"); throw new CommunicationException("Error deleting read helper function", data.Response); } }
protected void LoginButton_Click(object sender, EventArgs e) { logger = log4net.LogManager.GetLogger("LogInFile"); HttpCookie cookie = new HttpCookie("blocoMorador"); cookie.Value = drpBloco.SelectedItem.Text; cookie.Expires = DateTime.Now.AddDays(365); this.Page.Response.AppendCookie(cookie); Response.Cookies.Add(cookie); Session.Clear(); oAPmodel.apartamento = Convert.ToInt32(txtAP.Text); oAPmodel.bloco = Convert.ToInt32(drpBloco.Text); oProprietarioModel.senha = Password.Text; Session["AP"] = Convert.ToInt32(txtAP.Text); Session["Bloco"] = Convert.ToInt32(drpBloco.Text); int valida = oProprietario.autenticaMorador(oAPmodel, oProprietarioModel); if (valida != 0) { foreach (var item in oProprietario.populaProprietario(oAPmodel, oProprietarioModel)) { Session["AP"] = item.ap.apartamento; Session["Bloco"] = item.ap.bloco; Session["Proprie1"] = item.proprietario1.ToString(); Session["Proprie2"] = item.proprietario2.ToString(); if (item.email != null) Session["email"] = item.email.ToString(); // Session["senha"] = item.senha.ToString(); } if (Session["AP"].ToString() == "0" && Session["Bloco"].ToString() == "0") { Response.Redirect("WelcomeAdmin.aspx"); } else { if (Session["AP"].ToString() != "301" && Session["Bloco"].ToString() != "6") { Util.SendMail oEmail = new SendMail(); oEmail.enviaSenha("Acesso feito com sucesso para o apartamento/bloco " + Session["AP"].ToString() + " - " + Session["Bloco"].ToString(), "Acessos", "*****@*****.**", 0); logger.Info("Acesso feito com sucesso para o apartamento/bloco " + Session["AP"].ToString() + " - " + Session["Bloco"].ToString()); Response.Redirect("~/paginaInicialMoradores.aspx"); } else { Response.Redirect("~/paginaInicialMoradores.aspx"); logger.Warn("Acesso negado!"); } } } else { FailureText.Text = "Número do Apartamento ou senha inválida"; Session.Clear(); } }
public WebForLinkException(string message) : base(message) { log.Warn(message); }
private async void InfoWorker_DoWorkAsync(object sender, DoWorkEventArgs e) { try { string query = string.Format("SELECT * FROM SMS_G_System_COMPUTER_SYSTEM WHERE ResourceID = '{0}'", PropertyManager["ResourceID"].IntegerValue); IResultObject contentObject = Utility.GetFirstWMIInstance(ConnectionManager, query); if (contentObject["Manufacturer"].StringValue == "Dell Inc.") { labelModel.Text = contentObject["Model"].StringValue; query = string.Format("SELECT * FROM SMS_G_System_PC_BIOS WHERE ResourceID = '{0}'", PropertyManager["ResourceID"].IntegerValue); contentObject = Utility.GetFirstWMIInstance(ConnectionManager, query); string serviceTag = contentObject["SerialNumber"].StringValue; labelServiceTag.Text = serviceTag; log.InfoFormat("Processing warranty request for service tag : {0}", serviceTag); using (HttpClient client = new HttpClient()) { try { labelHttpResponse.Text = "Requesting data from API"; client.BaseAddress = new Uri(registry.ReadString("DellAPIURI")); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); log.InfoFormat("Connecting to dell API : {0}", client.BaseAddress); HttpResponseMessage response = await client.GetAsync(string.Format("getassetwarranty/{0}?apikey={1}", serviceTag, registry.ReadString("DellApiKey"))); log.DebugFormat("URL : {0}", response.RequestMessage.RequestUri.OriginalString); log.DebugFormat("Response status code : {0}", response.StatusCode); if (response.IsSuccessStatusCode) { labelHttpResponse.Text = "Success"; string resultContent = response.Content.ReadAsStringAsync().Result; XElement assetInformation = XElement.Parse(resultContent); XNamespace ns = assetInformation.GetDefaultNamespace(); log.Info("Connected successfully, processing xml data"); CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; var headerData = assetInformation.Descendants(ns + "AssetHeaderData").First(); XElement node = headerData.Element(ns + "ShipDate"); if (node != null) { string shipDate = DateTime.Parse(node.Value).ToString(); labelShipDate.Text = shipDate; } IEnumerable <XElement> nodeList = assetInformation.Descendants(ns + "AssetEntitlement"); foreach (XElement entitlement in nodeList) { string serviceLevelDescription = entitlement.Element(ns + "ServiceLevelDescription").Value; if (serviceLevelDescription != "") { string type = entitlement.Element(ns + "EntitlementType").Value; listViewWarranty.Items.Add(new ListViewItem() { Text = serviceLevelDescription, SubItems = { textInfo.ToTitleCase(type.ToLower()), DateTime.Parse(entitlement.Element(ns + "StartDate").Value).ToShortDateString(), DateTime.Parse(entitlement.Element(ns + "EndDate").Value).ToShortDateString() } }); } } } else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { labelHttpResponse.Text = "Unauthorized - Check API Key"; log.Warn(labelHttpResponse.Text); } else if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { labelHttpResponse.Text = "Resource Not found"; log.Warn(labelHttpResponse.Text); } } catch (HttpRequestException ex) { string msg = string.Format("{0}: {1}", ex.GetType().Name, ex.Message); log.Error(msg); throw new InvalidOperationException(msg); } log.InfoFormat("Finished processing request for service tag : {0}", serviceTag); } } else { labelServiceTag.Text = "The device is not manufacutred by Dell Inc"; labelModel.Text = contentObject["Manufacturer"].StringValue; } contentObject.Dispose(); } catch (Exception ex) { string msg = string.Format("{0}: {1}", ex.GetType().Name, ex.Message); log.Error(msg); throw new InvalidOperationException(msg); } }
private void SendHeartbeat(Object obj) { StationDetail detail = GetDetail(); Model.StationInfo sinfo = Model.StationCollection.Instance.FindOne(); if (sinfo != null) { bool locChange = false; string baseurl = NetworkHelper.GetBaseURL(); if (baseurl != sinfo.Location) { // update location if baseurl changed logger.DebugFormat("station location changed: {0}", baseurl); sinfo.Location = baseurl; locChange = true; } try { WebClient agent = new WebClient(); Cloud.StationApi api = new Cloud.StationApi(sinfo.Id, sinfo.SessionToken); if (logon == false || DateTime.Now - sinfo.LastLogOn > TimeSpan.FromDays(1)) { logger.Debug("cloud logon start"); api.LogOn(agent, detail); logon = true; // update station info in database logger.Debug("update station information"); sinfo.LastLogOn = DateTime.Now; Model.StationCollection.Instance.Save(sinfo); } if (locChange) { // update station info in database logger.Debug("update station information"); Model.StationCollection.Instance.Save(sinfo); } api.Heartbeat(agent, detail); } catch (WammerCloudException ex) { WebException webex = (WebException)ex.InnerException; if (webex != null) { HttpWebResponse response = (HttpWebResponse)webex.Response; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized) { // station's session token expired, it might be caused by: // 1. server maintenance // 2. driver registered another station // in this situation, client has to re-login/re-register the station functionServer.BlockAuth(true); } } } logger.Warn("cloud send heartbeat error", ex); } catch (Exception ex) { logger.Warn("cloud send heartbeat error", ex); } } }
protected override void Run() { SafeToExit = false; Description = Messages.ACTION_EXPORT_DESCRIPTION_IN_PROGRESS; if (Cancelling) { throw new CancelledException(); } log.DebugFormat("Exporting resource list report from {1} to {2}", this.Connection.Cache.Pools[0].Name(), _filename); try { DoExport(); } catch (Exception e) { // Test for null: don't overwrite a previous exception if (_exception == null) { _exception = e; } } PercentComplete = 100; if (Cancelling || _exception is CancelledException) { log.InfoFormat("Export of Pool {0} cancelled", this.Connection.Cache.Pools[0].Name()); this.Description = Messages.ACTION_EXPORT_DESCRIPTION_CANCELLED; log.DebugFormat("Deleting {0}", _filename); try { File.Delete(_filename); } catch (Exception e) { this.Description = string.Format(Messages.ACTION_EXPORT_POOL_RESOURCE_CANCEL_AND_FILE_UNDELETE, _filename); log.Warn(string.Format(Messages.ACTION_EXPORT_POOL_RESOURCE_CANCEL_AND_FILE_UNDELETE, _filename), e); } throw new CancelledException(); } else if (_exception != null) { log.Warn(string.Format("Export of Pool {0} failed", this.Connection.Cache.Pools[0].Name()), _exception); log.DebugFormat("Progress of the action until exception: {0}", PercentComplete); if (_exception is IOException) { this.Description = _exception.Message; } else { try { File.Delete(_filename); } catch (Exception e) { log.Warn(string.Format("deleting file {0} failed", _filename), e); } this.Description = Messages.ACTION_EXPORT_DESCRIPTION_FAILED; } throw new Exception(Description); } else { log.InfoFormat("Export of Pool {0} successful", this.Connection.Cache.Pools[0].Name()); this.Description = Messages.ACTION_EXPORT_DESCRIPTION_SUCCESSFUL; } }
/// <summary> /// Logs the warning. /// </summary> /// <param name="message">The message.</param> /// <param name="args">The arguments.</param> public static void LogWarning(string message, params object[] args) { _logger.Warn(string.Format(message, args)); }
public static void Warn(string msg) { logger.Warn(msg); }
public int Workspace(string folderYaml, string bsddUrl, string bsddUser, string bsddPassword, string languageCode) { log.Info($"Upload the texts to concepts in the buildingSMART Data Dictionary (bSDD) from this source: {folderYaml}"); if (folderYaml != null) { if (!Directory.Exists(folderYaml)) { log.Error($"ERROR - The Directory {folderYaml} does not exist. Exiting!"); return(1); } } Bsdd bsdd = new Bsdd(bsddUrl, bsddUser, bsddPassword); log.Info($"Successfully logged in, into bSDD at {bsddUrl}"); var yamlFileNames = Directory.EnumerateFiles(folderYaml, "PSet*.YAML");//.Where(x => x.Contains("Pset_StairCommon")); //A dirty trick to get all PSets done within one hour (the build time of Appveyor is limited to one hour) //Travers randomly the list of the PSet in ascending or descending order Random rand = new Random(); if (rand.Next(0, 2) == 0) { yamlFileNames = yamlFileNames.OrderBy(x => x); } else { yamlFileNames = yamlFileNames.OrderByDescending(x => x); } int ctPSets = 0; int ctProperties = 0; int ctPropertiesWithMissingTranslation = 0; int ctPropertiesWithMissingGuid = 0; foreach (string yamlFileName in yamlFileNames) { ctPSets++; log.Info($"--------------------------------------------------------------------------------------------------------"); log.Info($"--------------------------------------------------------------------------------------------------------"); log.Info($"Loading PSet {ctPSets}/{yamlFileNames.Count()}"); var yamlDeserializer = new DeserializerBuilder().Build(); PropertySet PSet; try { PSet = yamlDeserializer.Deserialize <PropertySet>(new StringReader(File.ReadAllText(yamlFileName))); log.Info($"Opened the YAML file {yamlFileName}"); log.Info($"--------------------------------------------------------------------------------------------------------"); log.Info($"--------------------------------------------------------------------------------------------------------"); log.Info($"Now checking the PSet {PSet.name} in the bSDD at {PSet.dictionaryReference.ifdGuid}"); IfdConcept pSetConcept = bsdd.GetConcept(PSet.dictionaryReference.ifdGuid); if (pSetConcept != null) { log.Info($"Ok, the PSet lives here: {bsddUrl}/#concept/browse/{pSetConcept.Guid}"); log.Info($"Status: {pSetConcept.Status}"); //Localisations of the PSet foreach (var localization in PSet.localizations .Where(x => x.language.ToLower() == languageCode.ToLower()) .Where(x => x.name.Length > 0)) { log.Info($"Publishing PSet {PSet.name} for language {localization.language}"); var existingFullName = pSetConcept.FullNames.Where(x => x.Language.LanguageCode.ToLower() == localization.language.ToLower()).FirstOrDefault(); //Dirty fix for https://github.com/buildingSMART/bSDD/issues/11 localization.name = localization.name.Replace(" ", " "); if (existingFullName == null) { log.Info($" Insert Name for concept => {localization.name}"); var answer = bsdd.InsertConceptName(pSetConcept.Guid, localization.language, localization.name); log.Info($" Succesfully inserted => {answer.Guid}"); } else { log.Info($" Existing Translation for name {existingFullName.Language.LanguageCode}"); log.Info($" NameType : {existingFullName.NameType}"); if (existingFullName.Name != localization.name) { log.Warn($" Update: {existingFullName.Name}=>{localization.name}"); var answer = bsdd.UpdateConceptName(pSetConcept.Guid, existingFullName.Guid, localization.language, localization.name); log.Warn($" Succesfully update => {answer.Guid}"); } else { log.Info($" No Update needed, the names are identical: {existingFullName.Guid}"); } } var existingDefinition = pSetConcept.Definitions.Where(x => x.Language.LanguageCode.ToLower() == localization.language.ToLower()).FirstOrDefault(); //Dirty fix for https://github.com/buildingSMART/bSDD/issues/11 localization.definition = localization.definition.Replace(" ", " "); if (existingDefinition == null) { log.Warn($" Insert description for concept : '{localization.definition}'"); var answer = bsdd.InsertConceptDefinition(pSetConcept.Guid, localization.language, localization.definition); log.Warn($" Succesfully inserted => {answer.Guid}"); } else { log.Info($" Existing Translation for description {existingDefinition.Language.LanguageCode}"); log.Info($" DescriptionType : {existingDefinition.DescriptionType}"); if (existingDefinition.Description != localization.definition) { log.Warn($" Update: {existingDefinition.Description}=>{localization.definition}"); var answer = bsdd.UpdateConceptDefinition(pSetConcept.Guid, existingDefinition.Guid, localization.language, localization.definition); log.Warn($" Succesfully update => {answer.Guid}"); } else { log.Info($" No Update needed, the definitions are identical: {existingDefinition.Guid}"); } } } //Now traversing the properties of the PSet foreach (var property in PSet.properties) { log.Info($"--------------------------------------------------------------------------------------------------------"); ctProperties++; log.Info($"Loading property #{ctProperties}"); IfdConcept propertyConcept = bsdd.GetConcept(property.dictionaryReference.ifdGuid); if (propertyConcept != null) { log.Info($"Ok, the property '{property.name}' lives here: {bsddUrl}/#concept/browse/{propertyConcept.Guid}"); log.Info($"Status: {propertyConcept.Status}"); //Check, if the property is correctly related to its PSet //If not, fix the relation bool isRelated = bsdd.RelatePropertyToPSet(psetGuid: pSetConcept.Guid, propertyGuid: propertyConcept.Guid, relationContextGuid: GuidOfIfc4Context); if (isRelated) { log.Info($"The property is correctly related to its PSet"); } else { log.Warn($"The relation of the property to its PSet was now inserted with the relationshipType='COLLECTS'."); } //Localizations of the Property var propertyLocalizations = property.localizations .Where(x => x.language.ToLower() == languageCode.ToLower()) .Where(x => x.name.Length > 0); if (propertyLocalizations.Count() == 0) { ctPropertiesWithMissingTranslation++; log.Error($"ERROR: Translation missing for {PSet.name}.{property.name} into {languageCode}"); } else { foreach (var localization in propertyLocalizations) { log.Info($"Publishing the Property for language {localization.language}"); { //managing the names of the property //Dirty fix for https://github.com/buildingSMART/bSDD/issues/11 localization.name = localization.name.Replace(" ", " "); var existingNames = propertyConcept.FullNames.Where(x => x.Language.LanguageCode.ToLower() == localization.language.ToLower()).ToList(); if (existingNames.Count == 0) { log.Warn($" No name exists for the language {localization.language}"); log.Warn($" Insert this name as the first name : '{localization.name}'"); if (localization.name.Length > 0) { var answer = bsdd.InsertConceptName(propertyConcept.Guid, localization.language, localization.name); log.Warn($" Succesfully inserted first name with GUID {answer.Guid} for the concept {propertyConcept.Guid}"); } else { ctPropertiesWithMissingTranslation++; log.Error($" ERROR: Translation of name missing for {PSet.name}.{property.name} into {languageCode}"); } } else { log.Info($" There exists {existingNames.Count()} name(s) for the concept {propertyConcept.Guid} in the language {localization.language}"); //INTERNAL REMARK: In the context of IFC should only exist one name per concept and language, // even when the data model of IFD allows more than one name // So, we check, if the name allready exists, and if not, // then we insert the new name and delete all existing name for this language and concept //TECHNICAL REMARK: Since at leat one name mus exist, we have to insert first the new name, if is does not // allready exist, and then delete all other names for this concept and language string guidOfExistingName = null; string guidOfNewName = null; if (existingNames.Select(x => x.Name).ToList().Contains(localization.name)) { guidOfExistingName = existingNames.Where(x => x.Name == localization.name).FirstOrDefault().Guid; log.Info($" The name already exists with the GUID {guidOfExistingName} : '{localization.name}'"); log.Info($" No insertion needed"); } else { log.Warn($" The name does not exist, inserting it now : '{localization.name}'"); var answer = bsdd.InsertConceptName(propertyConcept.Guid, localization.language, localization.name); guidOfNewName = answer.Guid; log.Warn($" Succesfully inserted with the GUID {guidOfNewName}"); } foreach (var name in existingNames.Where(x => x.Guid != guidOfExistingName).Where(y => y.Guid != guidOfNewName)) { log.Warn($" Deleting old name with GUID {name.Guid} : '{name.Name}'"); var answer = bsdd.DeleteConceptName(propertyConcept.Guid, name.Guid); } } } { //Managing the definitions of the property //Dirty fix for https://github.com/buildingSMART/bSDD/issues/11 localization.definition = localization.definition.Replace(" ", " "); var existingDefinitions = propertyConcept.Definitions.Where(x => x.Language.LanguageCode.ToLower() == localization.language.ToLower()).ToList(); if (existingDefinitions.Count() == 0) { log.Warn($" No description exists for the language {localization.language}"); log.Warn($" Insert this description as the first description : '{localization.definition}'"); if (localization.definition.Length > 0) { var answer = bsdd.InsertConceptDefinition(propertyConcept.Guid, localization.language, localization.definition); log.Warn($" Succesfully inserted first description with GUID {answer.Guid} for the concept {propertyConcept.Guid}"); } else { ctPropertiesWithMissingTranslation++; log.Error($" ERROR: Translation of definition missing for {PSet.name}.{property.name} into {languageCode}"); } } else { log.Info($" There exists {existingDefinitions.Count()} description(s) for the concept {propertyConcept.Guid} in the language {localization.language}"); string guidOfExistingDefinition = null; string guidOfNewDefinition = null; if (existingDefinitions.Select(x => x.Description).ToList().Contains(localization.definition)) { guidOfExistingDefinition = existingDefinitions.Where(x => x.Description == localization.definition).FirstOrDefault().Guid; log.Info($" The description already exists with the GUID {guidOfExistingDefinition} : '{localization.definition}'"); log.Info($" No insertion needed"); } else { log.Warn($" The description does not exist, inserting it now : '{localization.definition}'"); var answer = bsdd.InsertConceptDefinition(propertyConcept.Guid, localization.language, localization.definition); guidOfNewDefinition = answer.Guid; log.Warn($" Succesfully inserted with the GUID {guidOfNewDefinition}"); } foreach (var definition in existingDefinitions.Where(x => x.Guid != guidOfExistingDefinition).Where(y => y.Guid != guidOfNewDefinition)) { log.Warn($" Deleting old description with GUID {definition.Guid} : '{definition.Description}'"); var answer = bsdd.DeleteConceptDescription(propertyConcept.Guid, definition.Guid); } } } } } if (propertyConcept.Status != IfdStatusEnum.APPROVED) { bsdd.UpdateConceptStatus(propertyConcept.Guid, IfdStatusEnum.APPROVED); log.Warn($" Succesfully updated the status of the Property concept {propertyConcept.Guid} to APPROVED"); } } else { ctPropertiesWithMissingGuid++; log.Error($"ERROR: The property '{property.name}' cannot be found in the bSDD!"); if (property.dictionaryReference.ifdGuid.Length == 0) { log.Error($"ERROR: The property '{PSet.name}.{property.name}' has no ifdGuid in the YAML file."); log.Warn($"Please search the GUID for the property in the bSDD and insert it into the YAML file."); log.Warn($"Then store the file to GitHub(e.g.with a pull request)"); log.Warn($"ERROR: Now I am making a search for you on the bSDD for possible concepts with the term '{property.name}'"); IfdConceptList possibleConcepts = bsdd.SearchConcepts(property.name); if (possibleConcepts == null) { log.Warn($" no terms found"); } else { log.Warn($" {possibleConcepts.IfdConcept.Count()} terms found, showing the first 15"); foreach (var possibleConcept in possibleConcepts.IfdConcept.Where(x => x.Definitions != null).OrderBy(x => x.Status.ToString()).Take(15)) { log.Warn($" Found: {possibleConcept.Status} : {possibleConcept.ConceptType} - {possibleConcept.Guid} : {possibleConcept.Definitions.FirstOrDefault().Description}"); } log.Warn($"{possibleConcepts.IfdConcept.Count()} Concepts found - You could pick up one of these for your property..."); } } } } log.Info($"--------------------------------------------------------------------------------------------------------"); if (pSetConcept.Status != IfdStatusEnum.APPROVED) { bsdd.UpdateConceptStatus(pSetConcept.Guid, IfdStatusEnum.APPROVED); log.Warn($" Succesfully updated the status of the PSet concept {pSetConcept.Guid} to APPROVED"); } } } catch (Exception ex) { log.Error(ex.Message); return(1); } } log.Warn($"Published {ctPSets} PSets with {ctProperties} Properties."); log.Warn($"{ctPropertiesWithMissingTranslation} translations missing."); log.Warn($"{ctPropertiesWithMissingGuid} guid missing."); return(ctPropertiesWithMissingTranslation + ctPropertiesWithMissingGuid); }
public JointNewEditViewModel( IConstructionRepository repoConstruction, IUserNotify notify, Guid id, Prizm.Data.DAL.IMillReportsRepository adoRepo, ISecurityContext ctx) { this.repoConstruction = repoConstruction; this.JointId = id; this.notify = notify; this.adoRepo = adoRepo; this.ctx = ctx; #region Commands saveOrUpdateJointCommand = ViewModelSource.Create(() => new SaveOrUpdateJointCommand(repoConstruction, this, notify, ctx)); saveJointCommand = ViewModelSource.Create(() => new SaveJointCommand(repoConstruction, this, notify, ctx)); newSaveJointCommand = ViewModelSource.Create(() => new NewSaveJointCommand(repoConstruction, this, notify, ctx)); extractOperationsCommand = ViewModelSource.Create(() => new ExtractOperationsCommand(repoConstruction, this, notify)); jointdeactivationCommand = ViewModelSource.Create(() => new JointDeactivationCommand(repoConstruction, this, notify, ctx)); jointCutCommand = ViewModelSource.Create(() => new JointCutCommand(repoConstruction, this, notify)); quickSearchCommand = ViewModelSource.Create(() => new QuickSearchCommand(this, repoConstruction.RepoJoint, notify)); #endregion try { Inspectors = repoConstruction.RepoInspector.GetAll(); if (this.Inspectors == null || this.Inspectors.Count <= 0) { log.Warn(string.Format("Joint (id:{0}) creation: List of Inspectors is NULL or empty", this.JointId)); } Welders = repoConstruction.RepoWelder.GetAll(); if (this.Welders == null || this.Welders.Count <= 0) { log.Warn(string.Format("Joint (id:{0}) creation: List of Welders is NULL or empty", this.JointId)); } Pieces = adoRepo.GetPipelineElements(); if (this.Pieces == null || this.Pieces.Rows.Count <= 0) { log.Warn(string.Format("Joint (id:{0}) creation: Data Table of Pieces is NULL or empty", this.JointId)); } extractOperationsCommand.Execute(); if (id == Guid.Empty) { NewJoint(); } else { this.Joint = repoConstruction.RepoJoint.Get(id); RefreshJointData(); } } catch (RepositoryException ex) { log.Warn("JointNewEditViewModel " + ex.ToString()); notify.ShowWarning(Program.LanguageManager.GetString(StringResources.Notification_Error_Db_Message), Program.LanguageManager.GetString(StringResources.Notification_Error_Db_Header)); } }
public void Load() { Trace.Call(); #if LOG4NET _Logger.Debug("Loading config"); #endif string prefix; // setting required default values prefix = "Server/"; Get(prefix + "BindAddress", "127.0.0.1"); Get(prefix + "Port", 7689); Get(prefix + "Channel", "TCP"); Get(prefix + "Formatter", "binary"); prefix = "Engine/Users/DEFAULT/Interface/"; Get(prefix + "ShowAdvancedSettings", false); prefix = "Engine/Users/DEFAULT/Interface/Notebook/"; Get(prefix + "TimestampFormat", "HH:mm"); Get(prefix + "TabPosition", "top"); Get(prefix + "BufferLines", 500); Get(prefix + "EngineBufferLines", 100); Get(prefix + "StripColors", false); Get(prefix + "StripFormattings", false); Get(prefix + "AutoSwitchPersonChats", false); Get(prefix + "AutoSwitchGroupChats", true); prefix = "Engine/Users/DEFAULT/Interface/Notebook/Tab/"; Get(prefix + "NoActivityColor", "#000000"); Get(prefix + "ActivityColor", "#0080FF"); Get(prefix + "EventColor", "#2020C0"); Get(prefix + "HighlightColor", "#E80000"); prefix = "Engine/Users/DEFAULT/Interface/Notebook/Channel/"; Get(prefix + "UserListPosition", "left"); Get(prefix + "TopicPosition", "top"); Get(prefix + "NickColors", true); prefix = "Engine/Users/DEFAULT/Interface/Chat/"; Get(prefix + "BackgroundColor", String.Empty); Get(prefix + "ForegroundColor", String.Empty); Get(prefix + "FontFamily", String.Empty); Get(prefix + "FontStyle", String.Empty); Get(prefix + "FontSize", 0); Get(prefix + "WrapMode", "Word"); prefix = "Engine/Users/DEFAULT/Interface/Entry/"; Get(prefix + "CompletionCharacter", ":"); Get(prefix + "CommandCharacter", "/"); Get(prefix + "BashStyleCompletion", false); Get(prefix + "CommandHistorySize", 30); prefix = "Engine/Users/DEFAULT/Interface/Notification/"; Get(prefix + "NotificationAreaIconMode", "Never"); Get(prefix + "MessagingMenuEnabled", true); Get(prefix + "PopupsEnabled", true); prefix = "Engine/Users/DEFAULT/Sound/"; Get(prefix + "BeepOnHighlight", false); prefix = "Engine/Users/DEFAULT/Connection/"; Get(prefix + "Encoding", "ISO-8859-1"); Get(prefix + "AutoConvertUTF8", true); Get(prefix + "ProxyType", "System"); Get(prefix + "ProxyHostname", String.Empty); Get(prefix + "ProxyPort", -1); Get(prefix + "ProxyUsername", String.Empty); Get(prefix + "ProxyPassword", String.Empty); prefix = "Engine/Users/DEFAULT/Logging/"; Get(prefix + "Enabled", false); Get(prefix + "LogFilteredMessages", false); prefix = "Engine/Users/DEFAULT/MessageBuffer/"; Get(prefix + "PersistencyType", "Volatile"); prefix = "Engine/Users/DEFAULT/MessageBuffer/Volatile/"; Get(prefix + "MaxCapacity", 200); prefix = "Engine/Users/DEFAULT/MessageBuffer/Persistent/"; Get(prefix + "MaxCapacity", 50 * 1000); prefix = "Engine/Users/DEFAULT/Servers/"; Get(prefix + "Servers", new string[] { "IRC/irc.oftc.net", "IRC/irc.gimp.org", "IRC/irc.geekshed.net", "IRC/irc.efnet.org", "IRC/irc.ircnet.org", "IRC/irc.freenode.net" }); prefix = "Engine/Users/DEFAULT/Servers/IRC/irc.oftc.net/"; Get(prefix + "Hostname", "irc.oftc.net"); Get(prefix + "Port", 6667); Get(prefix + "Network", "OFTC"); Get(prefix + "Nickname", String.Empty); Get(prefix + "Realname", String.Empty); Get(prefix + "Username", String.Empty); Get(prefix + "Password", String.Empty); Get(prefix + "UseEncryption", false); Get(prefix + "ValidateServerCertificate", false); Get(prefix + "OnStartupConnect", true); Get(prefix + "OnConnectCommands", new string[] { "/join #smuxi", } ); prefix = "Engine/Users/DEFAULT/Servers/IRC/irc.gimp.org/"; Get(prefix + "Hostname", "irc.gimp.org"); Get(prefix + "Port", 6667); Get(prefix + "Network", "GIMPNet"); Get(prefix + "Nickname", String.Empty); Get(prefix + "Realname", String.Empty); Get(prefix + "Username", String.Empty); Get(prefix + "Password", String.Empty); Get(prefix + "UseEncryption", false); Get(prefix + "ValidateServerCertificate", false); prefix = "Engine/Users/DEFAULT/Servers/IRC/irc.geekshed.net/"; Get(prefix + "Hostname", "irc.geekshed.net"); Get(prefix + "Port", 6667); Get(prefix + "Network", "GeekShed"); Get(prefix + "Nickname", String.Empty); Get(prefix + "Realname", String.Empty); Get(prefix + "Username", String.Empty); Get(prefix + "Password", String.Empty); Get(prefix + "UseEncryption", false); Get(prefix + "ValidateServerCertificate", false); prefix = "Engine/Users/DEFAULT/Servers/IRC/irc.efnet.org/"; Get(prefix + "Hostname", "irc.efnet.org"); Get(prefix + "Port", 6667); Get(prefix + "Network", "EFnet"); Get(prefix + "Nickname", String.Empty); Get(prefix + "Realname", String.Empty); Get(prefix + "Username", String.Empty); Get(prefix + "Password", String.Empty); Get(prefix + "UseEncryption", false); Get(prefix + "ValidateServerCertificate", false); prefix = "Engine/Users/DEFAULT/Servers/IRC/irc.ircnet.org/"; Get(prefix + "Hostname", "irc.ircnet.org"); Get(prefix + "Port", 6667); Get(prefix + "Network", "IRCnet"); Get(prefix + "Nickname", String.Empty); Get(prefix + "Realname", String.Empty); Get(prefix + "Username", String.Empty); Get(prefix + "Password", String.Empty); Get(prefix + "UseEncryption", false); Get(prefix + "ValidateServerCertificate", false); prefix = "Engine/Users/DEFAULT/Servers/IRC/irc.freenode.net/"; Get(prefix + "Hostname", "irc.freenode.net"); Get(prefix + "Port", 6667); Get(prefix + "Network", "freenode"); Get(prefix + "Nickname", String.Empty); Get(prefix + "Realname", String.Empty); Get(prefix + "Username", String.Empty); Get(prefix + "Password", String.Empty); Get(prefix + "UseEncryption", false); Get(prefix + "ValidateServerCertificate", false); prefix = "Engine/Users/"; Get(prefix + "Users", new string[] { "local" }); /* * prefix = "Engine/Users/local/"; * Get(prefix+"Password", String.Empty); * * prefix = "Engine/Users/local/Servers/"; * Get(prefix+"Servers", new string[] {}); */ prefix = "Server/"; LoadEntry(prefix + "Port", 7689); LoadEntry(prefix + "Formatter", "binary"); LoadEntry(prefix + "Channel", "TCP"); LoadEntry(prefix + "BindAddress", null); // loading defaults LoadAllEntries("Engine/Users/DEFAULT"); prefix = "Engine/Users/"; string[] users = GetList(prefix + "Users"); m_Preferences[prefix + "Users"] = users; foreach (string user in users) { LoadUserEntry(user, "Password", "smuxi"); string[] startup_commands = GetList(prefix + user + "/OnStartupCommands"); if (startup_commands != null) { m_Preferences[prefix + user + "/OnStartupCommands"] = startup_commands; } else { m_Preferences[prefix + user + "/OnStartupCommands"] = new string[] {}; } string[] nick_list = GetList(prefix + user + "/Connection/Nicknames"); if (nick_list != null) { m_Preferences[prefix + user + "/Connection/Nicknames"] = nick_list; } else { string nick = Environment.UserName; // clean typical disallowed characters nick = nick.Replace(" ", String.Empty); if (String.IsNullOrEmpty(nick)) { nick = "Smuxi"; } m_Preferences[prefix + user + "/Connection/Nicknames"] = new string[] { nick }; } LoadUserEntry(user, "Connection/Username", String.Empty); string realname = null; try { string gecos = Mono.Unix.UnixUserInfo.GetRealUser().RealName; if (gecos == null) { gecos = String.Empty; } int pos = gecos.IndexOf(","); if (pos != -1) { realname = gecos.Substring(0, pos); } else { realname = gecos; } } catch (Exception ex) { #if LOG4NET _Logger.Warn("Load(): error getting realname from gecos (ignoring)", ex); #endif } if (String.IsNullOrEmpty(realname)) { realname = "Your Name"; } LoadUserEntry(user, "Connection/Realname", realname); LoadUserEntry(user, "Connection/Encoding", String.Empty); if (Get(prefix + user + "/Connection/AutoConvertUTF8", null) == null) { // upgrade path var enc = Get <string>(prefix + user + "/Connection/Encoding", String.Empty); if (((enc == String.Empty) && (System.Text.Encoding.Default.WebName.ToUpper() == "UTF-8")) || (enc.ToUpper() == "UTF-8")) { this[prefix + user + "/Connection/Encoding"] = "ISO-8859-1"; this[prefix + user + "/Connection/AutoConvertUTF8"] = true; } } LoadUserEntry(user, "Connection/AutoConvertUTF8", true); LoadUserEntry(user, "Connection/ProxyType", "System"); LoadUserEntry(user, "Connection/ProxyHostname", String.Empty); LoadUserEntry(user, "Connection/ProxyPort", -1); LoadUserEntry(user, "Connection/ProxyUsername", null); LoadUserEntry(user, "Connection/ProxyPassword", null); string[] command_list = GetList(prefix + user + "/Connection/OnConnectCommands"); if (command_list != null) { m_Preferences[prefix + user + "/Connection/OnConnectCommands"] = command_list; } else { m_Preferences[prefix + user + "/Connection/OnConnectCommands"] = new string[] {}; } string[] highlight_words = GetList(prefix + user + "/Interface/Chat/HighlightWords"); if (highlight_words != null) { m_Preferences[prefix + user + "/Interface/Chat/HighlightWords"] = highlight_words; } else { m_Preferences[prefix + user + "/Interface/Chat/HighlightWords"] = new string[] {}; } LoadUserEntry(user, "Interface/ShowAdvancedSettings", null); LoadUserEntry(user, "Interface/Notebook/TimestampFormat", null); LoadUserEntry(user, "Interface/Notebook/TabPosition", null); LoadUserEntry(user, "Interface/Notebook/BufferLines", null); LoadUserEntry(user, "Interface/Notebook/EngineBufferLines", null); LoadUserEntry(user, "Interface/Notebook/StripColors", null); LoadUserEntry(user, "Interface/Notebook/StripFormattings", null); LoadUserEntry(user, "Interface/Notebook/AutoSwitchPersonChats", null); LoadUserEntry(user, "Interface/Notebook/AutoSwitchGroupChats", null); LoadUserEntry(user, "Interface/Notebook/Tab/NoActivityColor", null); LoadUserEntry(user, "Interface/Notebook/Tab/ActivityColor", null); LoadUserEntry(user, "Interface/Notebook/Tab/EventColor", null); LoadUserEntry(user, "Interface/Notebook/Tab/HighlightColor", null); LoadUserEntry(user, "Interface/Notebook/Channel/UserListPosition", null); LoadUserEntry(user, "Interface/Notebook/Channel/TopicPosition", null); LoadUserEntry(user, "Interface/Notebook/Channel/NickColors", null); LoadUserEntry(user, "Interface/Chat/ForegroundColor", null); LoadUserEntry(user, "Interface/Chat/BackgroundColor", null); LoadUserEntry(user, "Interface/Chat/FontFamily", null); LoadUserEntry(user, "Interface/Chat/FontStyle", null); LoadUserEntry(user, "Interface/Chat/FontSize", null); LoadUserEntry(user, "Interface/Chat/WrapMode", null); LoadUserEntry(user, "Interface/Entry/CompletionCharacter", null); LoadUserEntry(user, "Interface/Entry/CommandCharacter", null); LoadUserEntry(user, "Interface/Entry/BashStyleCompletion", null); LoadUserEntry(user, "Interface/Entry/CommandHistorySize", null); LoadUserEntry(user, "Interface/Notification/NotificationAreaIconMode", null); LoadUserEntry(user, "Interface/Notification/MessagingMenuEnabled", null); LoadUserEntry(user, "Interface/Notification/PopupsEnabled", null); LoadUserEntry(user, "Sound/BeepOnHighlight", null); LoadUserEntry(user, "Logging/Enabled", null); LoadUserEntry(user, "Logging/LogFilteredMessages", null); LoadUserEntry(user, "MessageBuffer/PersistencyType", null); LoadUserEntry(user, "MessageBuffer/Volatile/MaxCapacity", null); LoadUserEntry(user, "MessageBuffer/Persistent/MaxCapacity", null); string[] servers = null; string sprefix = prefix + user + "/Servers/"; servers = GetList(sprefix + "Servers"); if (servers == null) { // this user has no servers string dprefix = prefix + "DEFAULT/Servers/"; servers = GetList(dprefix + "Servers"); if (servers == null) { // no default servers, use empty list servers = new string[] {}; } else { // we have default servers, so lets copy them foreach (string server in servers) { LoadEntry(sprefix + server + "/Hostname", Get(dprefix + server + "/Hostname", null)); LoadEntry(sprefix + server + "/Port", Get(dprefix + server + "/Port", null)); LoadEntry(sprefix + server + "/Network", Get(dprefix + server + "/Network", null)); LoadEntry(sprefix + server + "/Encoding", Get(dprefix + server + "/Encoding", null)); LoadEntry(sprefix + server + "/AutoConvertUTF8", Get(dprefix + server + "/AutoConvertUTF8", null)); LoadEntry(sprefix + server + "/Nickname", Get(dprefix + server + "/Nickname", null)); LoadEntry(sprefix + server + "/Realname", Get(dprefix + server + "/Realname", null)); LoadEntry(sprefix + server + "/Username", Get(dprefix + server + "/Username", null)); LoadEntry(sprefix + server + "/Password", Get(dprefix + server + "/Password", null)); LoadEntry(sprefix + server + "/UseEncryption", Get(dprefix + server + "/UseEncryption", null)); LoadEntry(sprefix + server + "/ValidateServerCertificate", Get(dprefix + server + "/ValidateServerCertificate", null)); LoadEntry(sprefix + server + "/OnStartupConnect", Get(dprefix + server + "/OnStartupConnect", null)); LoadEntry(sprefix + server + "/OnConnectCommands", Get(dprefix + server + "/OnConnectCommands", null)); } } m_Preferences[sprefix + "Servers"] = servers; } else { // this user has servers m_Preferences[sprefix + "Servers"] = servers; } foreach (string server in servers) { sprefix = prefix + user + "/Servers/" + server + "/"; LoadEntry(sprefix + "Hostname", null); LoadEntry(sprefix + "Port", null); LoadEntry(sprefix + "Network", String.Empty); LoadEntry(sprefix + "Encoding", null); LoadEntry(sprefix + "AutoConvertUTF8", null); LoadEntry(sprefix + "Nickname", String.Empty); LoadEntry(sprefix + "Realname", String.Empty); LoadEntry(sprefix + "Username", String.Empty); LoadEntry(sprefix + "Password", String.Empty); LoadEntry(sprefix + "UseEncryption", false); LoadEntry(sprefix + "ValidateServerCertificate", false); LoadEntry(sprefix + "OnStartupConnect", false); string[] commands = GetList(sprefix + "OnConnectCommands"); if (commands == null) { commands = new string[] {}; m_Preferences[sprefix + "OnConnectCommands"] = new string[] {}; } else { m_Preferences[sprefix + "OnConnectCommands"] = commands; } // HACK: XMPP specific values LoadEntry(sprefix + "Resource", null); LoadEntry(sprefix + "PriorityAvailable", null); LoadEntry(sprefix + "PriorityAway", null); } string[] filters = null; string cprefix = "Filters/"; filters = GetList(prefix + user + "/" + cprefix + "Filters"); if (filters == null) { filters = new string[] {}; m_Preferences[prefix + user + "/" + cprefix + "Filters"] = new string[] {}; } else { m_Preferences[prefix + user + "/" + cprefix + "Filters"] = filters; } foreach (string filter in filters) { cprefix = "Filters/" + filter + "/"; LoadUserEntry(user, cprefix + "Protocol", null); LoadUserEntry(user, cprefix + "ChatType", null); LoadUserEntry(user, cprefix + "ChatID", null); LoadUserEntry(user, cprefix + "MessageType", null); LoadUserEntry(user, cprefix + "MessagePattern", null); } string lprefix = "MessagePatterns/"; var linkKeys = GetList(prefix + user + "/" + lprefix + "MessagePatterns"); if (linkKeys == null) { linkKeys = new string[] {}; m_Preferences[prefix + user + "/" + lprefix + "MessagePatterns"] = new string[] {}; } else { m_Preferences[prefix + user + "/" + lprefix + "MessagePatterns"] = linkKeys; } foreach (var linkKey in linkKeys) { lprefix = "MessagePatterns/" + linkKey + "/"; LoadUserEntry(user, lprefix + "MessagePartPattern", String.Empty); LoadUserEntry(user, lprefix + "MessagePartType", String.Empty); LoadUserEntry(user, lprefix + "LinkFormat", String.Empty); LoadUserEntry(user, lprefix + "TextFormat", String.Empty); } } }
/// <summary> /// Logs Warning information to the Log File. /// </summary> /// <param name="InfoMessage"></param> public void Warning(string WarningMessage) { WarningMessage = "" + WarningMessage; log.Warn(WarningMessage); }
public void TestBatch() { try { using (EsgynDBConnection conn = new EsgynDBConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); using (EsgynDBCommand cmd = conn.CreateCommand()) { try { cmd.CommandText = "drop table t0"; cmd.ExecuteNonQuery(); } catch (Exception e) { log.Warn(e.Message); } cmd.CommandText = "create table t0 (c1 varchar(20), c2 nchar(20)) no partition"; cmd.ExecuteNonQuery(); cmd.CommandText = "insert into t0 values(?,?)"; cmd.Parameters.Add(new EsgynDBParameter("c0", EsgynDBType.Varchar)); cmd.Parameters.Add(new EsgynDBParameter("c1", EsgynDBType.Varchar)); cmd.Prepare(); for (int i = 0; i < 10; i++) { if (i == 2) { cmd.Parameters[0].Value = "test col1"; } else { cmd.Parameters[0].Value = "test col1rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"; } cmd.Parameters[1].Value = "test col2"; cmd.AddBatch(); log.Info(cmd.Parameters[0].Value); } //cmd.ExecuteNonQuery(); //Console.Read(); cmd.ExecuteNonQuery(); log.Info("start to select ...."); cmd.Parameters.Clear(); cmd.CommandText = "select * from t0"; using (EsgynDBDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { for (int i = 0; i < dr.FieldCount; i++) { log.Info(dr.GetValue(i) + " " + dr.GetDataTypeName(i)); } } } } } } catch (EsgynDBException e) { log.Info(e.ToString()); for (int i = 0; i < e.Errors.Count; i++) { log.Info(e.Errors[i]); } } }
public async Task <IActionResult> UploadMobileLogs() { var requestBody = string.Empty; try { if (_logEndpointOverride) { return(Ok()); } _logger.LogDebug("LogMessage action invoked"); using (var reader = new StreamReader(HttpContext.Request.Body)) { requestBody = await reader.ReadToEndAsync(); } var logMessagesMobileDeserialized = JsonSerializer.Deserialize <LogMessagesMobileCollection>(requestBody, new JsonSerializerOptions() { IgnoreNullValues = false }); foreach (var logMessageMobile in logMessagesMobileDeserialized.logs) { _logMessageValidator.SanitizeAndShortenTextFields(logMessageMobile, _maxTextFieldLength == 0 ? 500 : _maxTextFieldLength); _logMessageValidator.ValidateLogMobileMessagePatterns(logMessageMobile, _logMobilePatternsDictionary); _logMessageValidator.ValidateLogMobileMessageDateTimeFormats(logMessageMobile); switch (logMessageMobile.severity) { case "INFO": _loggerMobile.Info(logMessageMobile); break; case "ERROR": _loggerMobile.Error(logMessageMobile); break; case "WARNING": _loggerMobile.Warn(logMessageMobile); break; default: break; } } _logger.LogDebug("Log message saved successfully"); return(Ok()); } catch (HttpResponseException ex) { _logger.LogError("Error when uploading mobile logs" + ex); throw; } catch (JsonException ex) { _logger.LogError($"No logs found in body or unable to parse logs data. {ex} [Deserialized request]: {requestBody}"); return(BadRequest("No logs found in body or unable to parse logs data")); } catch (Exception ex) { _logger.LogError("An error occurred while trying to save logs " + ex); return(StatusCode(500)); } }
public void warn(string s) { log.Warn(category + ": " + s); }
/// <summary> /// 警告信息 /// </summary> /// <param name="info">错误信息</param> public static void LogWarn(string info) { logger.Warn(info); }
private static void Main() { if (!IsDebugBuild) { // Capture all unhandled Exceptions AppDomain.CurrentDomain.UnhandledException += (sender, args) => HandleUnhandledException(args.ExceptionObject as Exception, "UnhandledException"); Application.ThreadException += (sender, args) => HandleUnhandledException(args.Exception, "ThreadException"); } // Mutex is used to check if another instance of AML is already running Mutex mutex = new Mutex(true, "E3241D27-3DD8-4615-888A-502252B9E2A1", out var isFirstInstance); IDisposable sentrySdkInstance = null; try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); InitAppSettings(); sentrySdkInstance = InitSentry(); if (!CheckDotNet4_7_2()) { Log.Warn(".NET Framework v4.7.2 required"); var result = MessageBox.Show("This program requires Microsoft .NET Framework v4.7.2 or newer. Do you want to open the download page now?", "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (result == DialogResult.Yes) { Tools.StartProcess("https://dotnet.microsoft.com/download/dotnet-framework"); } return; } if (!SteamAPIWrapper.Init()) { Log.Warn("Failed to detect Steam"); StringBuilder message = new StringBuilder(); message.AppendLine("Please make sure that:"); message.AppendLine("- Steam is running"); message.AppendLine("- the file steam_appid.txt exists in the AML folder"); message.AppendLine("- neither (or both) of Steam and AML are running\n with admin privileges"); MessageBox.Show(message.ToString(), "Error - unable to detect Steam!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Load settings var settings = InitializeSettings(); if (settings == null) { Log.Error("Failed to initialize settings"); return; } // Exit if another instance of AML is already running and multiple instances are disabled. if (!settings.AllowMultipleInstances && !isFirstInstance) { MessageBox.Show("Another instance of AML is already running.", "AML already started", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // Check for update if (!IsDebugBuild && settings.CheckForUpdates) { CheckForUpdate(); } // clean up old files if (File.Exists(Program.XEnv.DefaultConfigDir + @"\DefaultModOptions.ini.bak")) { // Restore backup File.Copy(Program.XEnv.DefaultConfigDir + @"\DefaultModOptions.ini.bak", Program.XEnv.DefaultConfigDir + @"\DefaultModOptions.ini", true); File.Delete(Program.XEnv.DefaultConfigDir + @"\DefaultModOptions.ini.bak"); } Application.Run(new MainForm(settings)); SteamAPIWrapper.Shutdown(); } finally { Log.Info("Shutting down..."); sentrySdkInstance?.Dispose(); GlobalSettings.Instance.Save(); GC.KeepAlive(mutex); // prevent the mutex from being garbage collected early mutex.Dispose(); } }
public static void Start(string[] args) { bool isAlreadyRunning = false; List<string> filesToOpen = new List<string>(); // Init Log4NET LogFileLocation = LogHelper.InitializeLog4NET(); // Get logger LOG = log4net.LogManager.GetLogger(typeof(MainForm)); Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); // Log the startup LOG.Info("Starting: " + EnvironmentInfo.EnvironmentToString(false)); IniConfig.Init(); AppConfig.UpgradeToIni(); // Read configuration conf = IniConfig.GetIniSection<CoreConfiguration>(); try { // Fix for Bug 2495900, Multi-user Environment // check whether there's an local instance running already try { // Added Mutex Security, hopefully this prevents the UnauthorizedAccessException more gracefully // See an example in Bug #3131534 SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); MutexSecurity mutexsecurity = new MutexSecurity(); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny)); bool created = false; // 1) Create Mutex applicationMutex = new Mutex(false, @"Local\F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", out created, mutexsecurity); // 2) Get the right to it, this returns false if it's already locked if (!applicationMutex.WaitOne(0, false)) { LOG.Debug("Greenshot seems already to be running!"); isAlreadyRunning = true; // Clean up applicationMutex.Close(); applicationMutex = null; } } catch (AbandonedMutexException e) { // Another Greenshot instance didn't cleanup correctly! // we can ignore the exception, it happend on the "waitone" but still the mutex belongs to us LOG.Warn("Greenshot didn't cleanup correctly!", e); } catch (UnauthorizedAccessException e) { LOG.Warn("Greenshot is most likely already running for a different user in the same session, can't create mutex due to error: ", e); isAlreadyRunning = true; } catch (Exception e) { LOG.Warn("Problem obtaining the Mutex, assuming it was already taken!", e); isAlreadyRunning = true; } if (args.Length > 0 && LOG.IsDebugEnabled) { StringBuilder argumentString = new StringBuilder(); for (int argumentNr = 0; argumentNr < args.Length; argumentNr++) { argumentString.Append("[").Append(args[argumentNr]).Append("] "); } LOG.Debug("Greenshot arguments: " + argumentString.ToString()); } for (int argumentNr = 0; argumentNr < args.Length; argumentNr++) { string argument = args[argumentNr]; // Help if (argument.ToLower().Equals("/help")) { // Try to attach to the console bool attachedToConsole = Kernel32.AttachConsole(Kernel32.ATTACHCONSOLE_ATTACHPARENTPROCESS); // If attach didn't work, open a console if (!attachedToConsole) { Kernel32.AllocConsole(); } StringBuilder helpOutput = new StringBuilder(); helpOutput.AppendLine(); helpOutput.AppendLine("Greenshot commandline options:"); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/help"); helpOutput.AppendLine("\t\tThis help."); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/exit"); helpOutput.AppendLine("\t\tTries to close all running instances."); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/reload"); helpOutput.AppendLine("\t\tReload the configuration of Greenshot."); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t/language [language code]"); helpOutput.AppendLine("\t\tSet the language of Greenshot, e.g. greenshot /language en-US."); helpOutput.AppendLine(); helpOutput.AppendLine(); helpOutput.AppendLine("\t[filename]"); helpOutput.AppendLine("\t\tOpen the bitmap files in the running Greenshot instance or start a new instance"); Console.WriteLine(helpOutput.ToString()); // If attach didn't work, wait for key otherwise the console will close to quickly if (!attachedToConsole) { Console.ReadKey(); } FreeMutex(); return; } if (argument.ToLower().Equals("/exit")) { // unregister application on uninstall (allow uninstall) try { LOG.Info("Sending all instances the exit command."); // Pass Exit to running instance, if any SendData(new CopyDataTransport(CommandEnum.Exit)); } catch (Exception e) { LOG.Warn("Exception by exit.", e); } FreeMutex(); return; } // Reload the configuration if (argument.ToLower().Equals("/reload")) { // Modify configuration LOG.Info("Reloading configuration!"); // Update running instances SendData(new CopyDataTransport(CommandEnum.ReloadConfig)); FreeMutex(); return; } // Stop running if (argument.ToLower().Equals("/norun")) { // Make an exit possible FreeMutex(); return; } // Language if (argument.ToLower().Equals("/language")) { conf.Language = args[++argumentNr]; IniConfig.Save(); continue; } // Files to open filesToOpen.Add(argument); } // Finished parsing the command line arguments, see if we need to do anything CopyDataTransport transport = new CopyDataTransport(); if (filesToOpen.Count > 0) { foreach (string fileToOpen in filesToOpen) { transport.AddCommand(CommandEnum.OpenFile, fileToOpen); } } if (MainForm.instance == null) MainForm.instance = new MainForm(transport); // if language is not set, show language dialog if (string.IsNullOrEmpty(conf.Language)) { LanguageDialog languageDialog = LanguageDialog.GetInstance(); languageDialog.ShowDialog(); conf.Language = languageDialog.SelectedLanguage; IniConfig.Save(); } // Check if it's the first time launch? if (conf.IsFirstLaunch) { conf.IsFirstLaunch = false; IniConfig.Save(); transport.AddCommand(CommandEnum.FirstLaunch); } } catch (Exception ex) { LOG.Error("Exception in startup.", ex); Application_ThreadException(MainForm.ActiveForm, new ThreadExceptionEventArgs(ex)); } }
/// <summary> /// 登录 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSubmit_Click(object sender, EventArgs e) { string adminName = tbxUserName.Text.Trim(); string password = tbxPassword.Text.Trim(); MS_LoginBLL BLLLogin = new MS_LoginBLL(); //为空 if (adminName == "") { Alert.Show("请输入用户名!"); return; } if (password == "") { Alert.Show("请输入密码!"); return; } //长度 if (adminName.Length > 50) { Alert.Show("用户名过长!"); return; } if (password.Length > 50) { Alert.Show("密码过长!"); return; } if (BLLLogin.LoginErrorLock(adminName, 3, 3)) { Alert.Show("登录失败:登陆错误次数超过三次,请过5分钟重新登陆"); return; } //MS_AdminBLL BLLAdmin = new MS_AdminBLL(); MS_Admin m_admin = new MS_AdminBLL().Get(adminName); if (m_admin != null && m_admin.F_LoginName == adminName) { if (EKPasswordUtil.ComparePasswords(m_admin.F_Password, password)) { if (!m_admin.F_Enabled) { logger.Error("用户: " + m_admin.F_LoginName + " 未启用,请联系管理员!"); Alert.Show("用户未启用,请联系管理员!"); return; } else { //登录成功 logger.Info(String.Format("登录成功:用户“{0}”,登录IP:" + EKRequest.GetIP() + "", m_admin.F_LoginName)); new MS_AdminBLL().LoginSuccess(m_admin); return; } } else { BLLLogin.LoginAddError(adminName); logger.Warn(String.Format("登录失败:用户“{0}”密码错误", adminName)); Alert.Show("用户名或密码错误!"); return; } } else { BLLLogin.LoginAddError(adminName); logger.Warn(String.Format("登录失败:用户“{0}”不存在", adminName)); Alert.ShowInTop("用户名或密码错误!"); } }
/// <summary> /// Set stats according to necro pet server properties /// </summary> public override void AutoSetStats() { if (Name.ToUpper() == "GREATER NECROSERVANT") { Strength = ServerProperties.Properties.NECRO_GREATER_PET_STR_BASE; Constitution = (short)(ServerProperties.Properties.NECRO_GREATER_PET_CON_BASE + m_summonConBonus); Dexterity = ServerProperties.Properties.NECRO_GREATER_PET_DEX_BASE; Quickness = ServerProperties.Properties.NECRO_GREATER_PET_QUI_BASE; if (Level > 1) { Strength += (short)(Math.Round(ServerProperties.Properties.NECRO_GREATER_PET_STR_MULTIPLIER * Level)); Constitution += (short)(Math.Round(ServerProperties.Properties.NECRO_GREATER_PET_CON_MULTIPLIER * Level)); Dexterity += (short)(Math.Round(ServerProperties.Properties.NECRO_GREATER_PET_DEX_MULTIPLIER * Level)); Quickness += (short)(Math.Round(ServerProperties.Properties.NECRO_GREATER_PET_QUI_MULTIPLIER * Level)); } } else { Strength = ServerProperties.Properties.NECRO_PET_STR_BASE; Constitution = (short)(ServerProperties.Properties.NECRO_PET_CON_BASE + m_summonConBonus); Dexterity = ServerProperties.Properties.NECRO_PET_DEX_BASE; Quickness = ServerProperties.Properties.NECRO_PET_QUI_BASE; if (Level > 1) { Strength += (short)(Math.Round(ServerProperties.Properties.NECRO_PET_STR_MULTIPLIER * Level)); Constitution += (short)(Math.Round(ServerProperties.Properties.NECRO_PET_CON_MULTIPLIER * Level)); Dexterity += (short)(Math.Round(ServerProperties.Properties.NECRO_PET_DEX_MULTIPLIER * Level)); Quickness += (short)(Math.Round(ServerProperties.Properties.NECRO_PET_QUI_MULTIPLIER * Level)); } } Empathy = (byte)(29 + Level); Piety = (byte)(29 + Level); Charisma = (byte)(29 + Level); // Now scale them according to NPCTemplate values if (NPCTemplate != null) { if (NPCTemplate.Strength > 0) { Strength = (short)Math.Round(Strength * NPCTemplate.Strength / 100.0); } if (NPCTemplate.Constitution > 0) { Constitution = (short)Math.Round(Constitution * NPCTemplate.Constitution / 100.0); } if (NPCTemplate.Quickness > 0) { Quickness = (short)Math.Round(Quickness * NPCTemplate.Quickness / 100.0); } if (NPCTemplate.Dexterity > 0) { Dexterity = (short)Math.Round(Dexterity * NPCTemplate.Dexterity / 100.0); } if (NPCTemplate.Intelligence > 0) { Intelligence = (short)Math.Round(Intelligence * NPCTemplate.Intelligence / 100.0); } // Except for CHA, EMP, AND PIE as those don't have autoset values. if (NPCTemplate.Empathy > 0) { Empathy = (short)(NPCTemplate.Empathy + Level); } if (NPCTemplate.Piety > 0) { Piety = (short)(NPCTemplate.Piety + Level); } if (NPCTemplate.Charisma > 0) { Charisma = (short)(NPCTemplate.Charisma + Level); } // Older DBs have necro pet templates with stats at 30, so warn servers that they need to update their templates if (NPCTemplate.Strength == 30 || NPCTemplate.Constitution == 30 || NPCTemplate.Quickness == 30 || NPCTemplate.Dexterity == 30 || NPCTemplate.Intelligence == 30) { log.Warn($"AutoSetStats(): NpcTemplate with TemplateId=[{NPCTemplate.TemplateId}] scales necro pet Str/Con/Qui/Dex/Int to 30%. " + "If this is not intended, change stat values in template to desired percentage or set to 0 to use default."); } } }
static void Main(string[] args) { if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = "Main"; #if WINDOWS && DEBUG if (!System.Diagnostics.Debugger.IsAttached) { AllocConsole(); var stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); var safeFileHandle = new SafeFileHandle(stdHandle, true); var fileStream = new FileStream(safeFileHandle, FileAccess.Write); var encoding = Encoding.GetEncoding(CODE_PAGE); var stdOut = new StreamWriter(fileStream, encoding) { AutoFlush = true }; Console.SetOut(stdOut); } #endif _log = LogManager.GetLogger(typeof(Program)); _log.Info("### !!! APPLICATION LOAD !!! ###"); _log.Info("Deleting old log files (>7 days)..."); // Delete log files older than 7 days if (Directory.Exists("logs")) { var now = DateTime.Now; var max = new TimeSpan(7, 0, 0, 0); // 7 days foreach (var file in from file in Directory.GetFiles("logs") let modTime = File.GetLastAccessTime(file) let age = now.Subtract(modTime) where age > max select file) { try { File.Delete(file); _log.Info("Deleted old log file: " + file); } catch (IOException ex) { _log.Warn("Failed to delete log file: " + file + "(" + ex.Message + ")"); } } } _log.Info("Old log files deleted!"); _log.Info("Starting game..."); using (var game = new MainGame()) game.Run(); #if WINDOWS && DEBUG _log.Debug("Unloading console..."); FreeConsole(); _log.Debug("Console unloaded!"); #endif _log.Info("### !!! APPLICATION EXIT !!! ###"); }