internal Dictionary <string, Assembly> LoadAssemblies(IEnumerable <FileInfo> assemblyLocations) { var namespaces = new Dictionary <string, Assembly>(); AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; try { foreach (FileInfo assemblyLocation in assemblyLocations) { Assembly.ReflectionOnlyLoadFrom(assemblyLocation.FullName); } foreach (Assembly reflectionOnlyAssembly in AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies()) { try { foreach (Type type in reflectionOnlyAssembly.GetTypes()) { try { if (type.Namespace != null && !namespaces.ContainsKey(type.Namespace)) { namespaces.Add(type.Namespace, reflectionOnlyAssembly); } } catch {} // Already added in the list. } } catch (TypeLoadException ex) { MessageBox.Show(ex.Message); } } return(namespaces); } catch (FileNotFoundException) { // Continue loading assemblies even if an assembly can not be loaded in the new AppDomain. return(namespaces); } }
/// <summary> /// Load all of the Mod data, get available mods from the /// reserve folder, add new mods found in the mods folder. /// Also grab all stored Mod data in the DB /// </summary> public void Init() { AvailableMods = new List <Mod>(); //Get mods from DB first AvailableMods.AddRange(Data.GetModsFromDb()); //Get mods in the Mod directory try { var modFolderMods = ScanDirForMods(App.FactorioLoader.Config.ModFolder); MergeModsWithDataFromScanDir(modFolderMods); } catch (PathMissingException) { MessageBox.Show("Mod folder doesn't exist :(\nPlease set the Mod folder before continuing"); App.FactorioLoader.Config.RequestModFolder(); } //If no reserve dir then create it if (!Directory.Exists(App.FactorioLoader.Config.ReserveFolder)) { Directory.CreateDirectory(App.FactorioLoader.Config.ReserveFolder); } //Get mods in the reserve directory var reserveFolderMods = ScanDirForMods(App.FactorioLoader.Config.ReserveFolder, true); MergeModsWithDataFromScanDir(reserveFolderMods); }
public SearchViewModel() { ExecuteSearchDelegateCommand = new DelegateCommand(() => { Search(searchValue); }, CanExecute); HotKeyManager.RegisterHotKey(Keys.F12, ModifierKeys.Control); HotKeyManager.HotKeyPressed += (sender, args) => { try { Application.Current.Dispatcher.Invoke(() => { Search(Clipboard.GetText()); }); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } }; if (Environment.GetCommandLineArgs().Length > 1) { string keyword = Environment.GetCommandLineArgs()[1]; if (keyword.Trim().Length > 0) { Search(keyword); } } }
/// <summary> /// 导出皮肤 /// </summary> /// <param name="model"></param> public void SkinExport(Skin model) { var file = Soft.SkinFile(model); if (!File.Exists(file)) { MessageBox.Show("皮肤文件丢失!", "导出失败"); return; } 生成带皮肤信息的压缩包(model); var dialog = new FolderBrowserDialog { Description = @"请选择导出路径" }; if (dialog.ShowDialog() == DialogResult.OK) { string foldPath = dialog.SelectedPath + "\\" + model.FileName; try { File.Copy(file, foldPath, true); Process.Start("explorer.exe", dialog.SelectedPath); } catch (Exception ex) { MessageBox.Show("文件被占用或导出路径出错!!", "导出失败!"); Log.LogError("导出失败!", ex); } } }
/// <summary> /// Clears log at once /// </summary> public void ClearLog() { EntityConnectionStringBuilder entityBuilder; if (!CreateConnection(out entityBuilder)) { return; } using (LoggerEntities context = new LoggerEntities(entityBuilder.ConnectionString)) { try { var list = new ObservableCollection <LogEntry>(context.LogEntries.ToList()); foreach (var logEntry in list) { context.DeleteObject(logEntry); } context.SaveChanges(); LoadDataSource(); } catch (Exception e) { logger.ErrorException("LoadDataSource", e); MessageBox.Show(e.Message); } } }
//сохранение строки private void SaveData(Object o) { if (newRow != null && !String.IsNullOrEmpty(newRow.PROD_NAME))//сохранение новой записи { if (methodsEntities.PRODUCER.Where(p => p.PROD_NAME == newRow.PROD_NAME && (p.PROD_COUNTRY == null && String.IsNullOrEmpty(newRow.PROD_COUNTRY) || p.PROD_COUNTRY != null && p.PROD_COUNTRY == newRow.PROD_COUNTRY)).Any()) { MessageBox.Show("Такая строка уже сущестует в таблице."); return; } methodsEntities.PRODUCER.Add(newRow); methodsEntities.SaveChanges(); RaisePropertyChanged(() => data); //возврат в режим ввода новой записи AddData(null); } else //сохранение откорректированной записи { int selectedId = selectedRow.PROD_ID; methodsEntities.SaveChanges(); RaisePropertyChanged(() => data); selectedRow = data.Where(p => p.PROD_ID == selectedId).FirstOrDefault(); } }
public void ExecuteConvertCheckToCreditCommand() { if (SelectedPayment.Transaction.BusinessPartner.AllowCreditsWithoutCheck && SelectedPayment.Clearance == null)//(SelectedPayment.Transaction.BusinessPartner.PaymentMethod == PaymentMethods.Credit && SelectedPayment.Clearance == null) { try { SelectedCheck.Enabled = false; _unitOfWork.Repository <CheckDTO>().Update(SelectedCheck); SelectedPayment.PaymentMethod = PaymentMethods.Credit; SelectedPayment.CheckId = null; _unitOfWork.Repository <PaymentDTO>().Update(SelectedPayment); _unitOfWork.Commit(); } catch { MessageBox.Show("Problem converting check to credit"); } } else { MessageBox.Show("Problem converting check to credit"); } }
private void EncryptFile() { var files = GetFiles(); if (files == null || !files.Any()) { return; } var password = ShowPasswordEnter(); if (string.IsNullOrEmpty(password)) { return; } foreach (var file in files) { if (!File.Exists(file)) { continue; } EncryptionCryptoWrapper.EncryptFileWithPassword(new FileInfo(file), password); } MessageBox.Show("Successfully encrypted"); }
private void EncryptFolder() { var folder = GetFolder(); if (string.IsNullOrEmpty(folder)) { return; } var password = ShowPasswordEnter(); if (string.IsNullOrEmpty(password)) { return; } var files = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories); // BUG 1: Key derivation should not be performed outside a foreach block that is using its return value. // Otherwise all operations in this loop have the same encryption key var keyData = WeakPasswordDerivation.DerivePassword(password); foreach (var file in files) { if (!File.Exists(file)) { continue; } EncryptionCryptoWrapper.EncryptFile(new FileInfo(file), keyData.Key, keyData.Salt); } MessageBox.Show("Successfully encrypted"); }
private void ExtractImagesCommand_Execute() { try { SetBusy(true); var dialog = new FolderBrowserDialog(); var result = dialog.ShowDialog(); if (result == DialogResult.OK) { var pdfFilePaths = PdfFiles.ToArray(); var imageExtractor = new ImageExtractor(pdfFilePaths, dialog.SelectedPath); imageExtractor.Extract(); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo { FileName = dialog.SelectedPath, UseShellExecute = true, Verb = "open" }); } } catch (Exception exception) { MessageBox.Show(exception.Message); Console.WriteLine(exception); } finally { SetBusy(false); } }
public HotkeySelectWindow(Keys current, Action <Keys> callback) { InitializeComponent(); TxtHotkey.Text = current.ToString().ToUpper(); TxtHotkey.TextChanged += (s, a) => { var i = TxtHotkey.CaretIndex; TxtHotkey.Text = TxtHotkey.Text.ToUpper(); TxtHotkey.CaretIndex = i; }; BtnCancel.Click += (e, a) => { callback?.Invoke(current); Close(); }; BtnSave.Click += (e, a) => { if (Enum.TryParse <Keys>(TxtHotkey.Text, true, out var keys)) { callback?.Invoke(keys); Close(); } else { MessageBox.Show("Error", "Invalid key"); } }; }
public void SaveOffer(Offer offer) { Offer newoffer = new Offer(); var importSymbolsForm = new ImportProviderSymbolsForm(); if (importSymbolsForm.ShowDialog() == true) { newoffer.Name = importSymbolsForm.NameField; newoffer.Description = importSymbolsForm.DescriptionField; newoffer.CreatedDate = DateTime.Now; } else { importSymbolsForm.Close(); return; } Services.SaveOffer(newoffer); foreach (var offerserviceViewModel in _offerViewModel.OfferServices) { OfferService ofs = offerserviceViewModel.ToDbModel(); newoffer.OfferServices.Add(ofs); } newoffer.Total = _offerViewModel.Total; newoffer.VAT = _offerViewModel.Vat; Services.SaveOffer(newoffer); MessageBox.Show("Успешно запазена!"); }
/// <summary> /// Function to get the path and other information from get-dscresource property execution /// </summary> /// <returns></returns> public List <DscNameInfo> GetPathEtcInfo() { List <DscNameInfo> newInfo = null; try { newInfo = new List <DscNameInfo> { PrintPsPropertyDetail(Constants.DscResourceName), new DscNameInfo(Constants.DscResourceModule, Module), PrintPsPropertyDetail(Constants.DscResourceResourceType), PrintPsPropertyDetail(Constants.DscResourceFriendlyName) }; var resourceType = newInfo[2];//Strore resorucetype _actualClassName = (resourceType != null) ? resourceType.Value : null; string path = PrintPsPropertyEmptyIfNull(_dscResourceItem.Properties[Constants.DscResourcePath]); if (path != String.Empty && !path.StartsWith(Environment.GetEnvironmentVariable("windir")) && Module != String.Empty) { this._pathInPsHome = false; } newInfo.Add(PrintPsPropertyDetail(Constants.DscResourcePath)); newInfo.Add(PrintPsPropertyDetail(Constants.DscResourceParentPath)); newInfo.Add(PrintPsPropertyDetail(Constants.DscResourceImplementedAs)); newInfo.Add(PrintPsPropertyDetail(Constants.DscResourceCompanyName)); } catch (Exception e) { MessageBox.Show("An error occured! Sorry, some crash due to " + e.Message, "Error"); } return(newInfo); }
public static int Listing(int location, string DecompileOffset) { bool success = int.TryParse(DecompileOffset, out location); if (!success) { success = int.TryParse(ToDecimal(DecompileOffset), out location); if (!success) { MessageBox.Show("入力したオフセットが無効です。"); } } try { //return location; ここに記述しても値を返さない tryを削ることも不可 } catch (IOException) { MessageBox.Show("ROMを読み込めません。"); } catch (Exception exc) { MessageBox.Show("不明な例外がありました。\n" + exc); } return(location); }
public DataTable ViewPending() { var data = new DataTable(); using (VistaDBConnection connection = new VistaDBConnection(new Connection().ConnectionString)) { try { connection.Open(); using (VistaDBCommand command = new VistaDBCommand()) { command.Connection = connection; var query = command.CommandText = $"SELECT Id,PoNumber,Beneficiary,Amount,(SELECT SchoolName FROM School s WHERE s.Id=p.SchoolId) AS 'School' FROM dbo.PaymentOrder p where status='Pending'"; var adapter = new VistaDBDataAdapter(command.CommandText, command.Connection); adapter.Fill(data); connection.Close(); } } catch (VistaDBException exception) { MessageBox.Show("Something went wrong"); Log.Error(exception); } } return(data); }
private void DecryptFile() { var files = GetFiles("falsecrypt File (*.falsecrypt)|*.falsecrypt"); if (files == null || !files.Any()) { return; } var password = ShowPasswordEnter(); if (string.IsNullOrEmpty(password)) { return; } foreach (var file in files) { if (!File.Exists(file)) { continue; } try { EncryptionCryptoWrapper.DecryptFileWithPassword(new FileInfo(file), password); } catch (Exception e) { MessageBox.Show("Wrong password"); return; } } MessageBox.Show("Successfully decrypted"); }
private void CalculateFields() { if (CurrentFirmaWraperSource == null) { MessageBox.Show("Не е избрана фирма, от която да се копират номенклатури"); return; } this.Fields = new ObservableCollection <ObservableCollection <string> >(); this.SFields = new ObservableCollection <ObservableCollection <string> >(); if (_Lookup == null) { return; } LookupModel lm = context.GetLookup(_Lookup.Id); var title = new ObservableCollection <string>(); foreach (var field in lm.Fields) { title.Add(field.Name); } title.Add("ФирмаКод"); Fields.Add(title); var list = context.GetLookup(_Lookup.Tablename, CurrentFirmaWraperSource.Id); foreach (var li in list) { var ader = new ObservableCollection <string>(li); Fields.Add(ader); } }
private async void Connect() { if (_connector == null) { _connector = new Connector(); } if (!_connector.Connect()) { MessageBox.Show("Please click Connect to try connecting to Dynamics CRM again. A valid connection is required."); return; } IsBusy = true; IsConnected = true; _service = _connector.OrganizationServiceProxy; ConnectText = "Reconnect"; _messenger.Send(new UpdateHeaderMessage { Header = "Export Assemblies: " + _connector.OrganizationFriendlyName }); var assemblies = await LoadAssemblies(); Assemblies = new ObservableCollection <Assembly>(assemblies); IsBusy = false; }
private void ExcuteAddNewPaymentCommand() { if (SelectedPayment != null) { if (SelectedPayment.PaymentMethod == PaymentMethods.Credit) { new AddPayment(SelectedPayment).ShowDialog(); } else if (SelectedPayment.Status != PaymentStatus.Cleared) { if (Singleton.Setting.HandleBankTransaction) { new PaymentClearance(SelectedPayment).ShowDialog(); } else { try { SelectedPayment.Status = PaymentStatus.Cleared; _unitOfWork.Repository <PaymentDTO>().Update(SelectedPayment); } catch { MessageBox.Show("Can't deposit payment, try again..."); } } } GetPayments(); } }
public static void Load(bool isLoader = false) { if (App.Args.Length == 0 && !isLoader) { if (LoadFromCloud()) { return; } } if (LoadFromFile()) { return; } if (LoadFromBackup()) { return; } if (LoadFromResource()) { return; } MessageBox.Show("Something went horribly wrong while loading your Configuration /ff"); Environment.Exit(0); }
/// <summary> /// 挂载皮肤 /// </summary> /// <param name="model"></param> public Skin SkinMount(Skin model) { var gameskin = Game.SkinFile(model); var softskin = Soft.SkinFile(model); if (!File.Exists(softskin)) { MessageBox.Show("皮肤 [" + model.SkinName + "]文件丢失", "挂载失败"); } try { if (FileOperations.CreateFileDir(gameskin) && ReadOrWriteClientZipstxt(model, true)) { File.Copy(softskin, gameskin, true); model.MountType = "已挂载"; _skin.ChangeMountType(model); } else { MessageBox.Show("ClientZips.txt文件读写失败!请确认改文件未被锁定", "挂载失败!"); } } catch (Exception ex) { ReadOrWriteClientZipstxt(model, false); MessageBox.Show("皮肤复制出错!\r\n文件被占用或无权限操作", "挂载失败!"); Log.LogError("挂载皮肤", ex); } return(model); }
public static void Save(bool cloud = false) { try { if (!Instance.IsOnScreen()) { Instance.WindowTop = 100; Instance.WindowLeft = 100; } Utility.MapClassToXmlFile(typeof(Config), Instance, Directories.ConfigFilePath); if (cloud && Instance.UseCloudConfig && !string.IsNullOrEmpty(Instance.Username) && !string.IsNullOrEmpty(Instance.Password) && WebService.IsAuthenticated) { WebService.CloudStore(Instance, "Config"); } } catch (Exception e) { MessageBox.Show(e.ToString()); } }
private static void CloseApplication(_Application oWord) { try { oWord.Activate(); oWord.Quit(); if (oWord != null) { try { oWord.Activate(); while (System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oWord) > 0) { ; } } catch { } finally { oWord = null; } } } catch (Exception ex) { MessageBox.Show("Error to close WORD Application\n"); } }
//加载Excel public DataSet LoadDataFromExcel() { /* * 参数HDR的值: * HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。 * IMEX: * 0 is Export mode, 只能写入 * 1 is Import mode, 只能读取 * 2 is Linked mode (full update capabilities) */ try { //strConn = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + filePath + "; Extended Properties=\"Excel 8.0; HDR=No; IMEX=1;\""; var srcTabelName = "Sheet1$"; var OleConn = new OleDbConnection($@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={ExcelPath};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"); OleConn.Open(); string sql = $"SELECT * FROM [{srcTabelName}]";//可是更改Sheet名称,比如sheet2,等等 var OleDaExcel = new OleDbDataAdapter(sql, OleConn); var dataSet = new DataSet(); OleDaExcel.Fill(dataSet, srcTabelName); OleConn.Close(); return(dataSet); } catch (Exception err) { MessageBox.Show("数据绑定Excel失败!失败原因:" + err.Message, "提示信息"); return(null); } }
public void LoadDataSource() { EntityConnectionStringBuilder entityBuilder; if (!CreateConnection(out entityBuilder)) { return; } if (ItemsList != null) { ItemsList.Clear(); } using (LoggerEntities context = new LoggerEntities(entityBuilder.ConnectionString)) { try { ItemsList = new ObservableCollection <LogEntry>(context.LogEntries.OrderByDescending(l => l.id).ToList()); } catch (Exception e) { logger.ErrorException("LoadDataSource", e); MessageBox.Show(e.Message); } } }
public void FillData(DataSet dataSet) { var curColumn = 0; var curRow = 0; var showRoCo = true; try { var owList = new List <OverWork>(); var dataTable = dataSet.Tables[0]; for (; curRow < dataTable.Rows.Count; curRow++) { curColumn = 0; showRoCo = true; var number = dataTable.Rows[curRow][curColumn++]?.ToString(); var epNo = dataTable.Rows[curRow][curColumn++]?.ToString(); var epName = dataTable.Rows[curRow][curColumn++]?.ToString(); var startTime = DateTime.Parse(dataTable.Rows[curRow][curColumn++]?.ToString()); var endTime = DateTime.Parse(dataTable.Rows[curRow][curColumn++]?.ToString()); var applyTime = int.Parse(dataTable.Rows[curRow][curColumn++].ToString()); //var reduceTime = DateTime.Parse(dataTable.Rows[ro][curColumn++]?.ToString()); var typeOverWork = dataTable.Rows[curRow][curColumn++]?.ToString(); var IsOnduty = int.Parse(dataTable.Rows[curRow][curColumn++].ToString()); var IsOffduty = int.Parse(dataTable.Rows[curRow][curColumn++].ToString()); var description = dataTable.Rows[curRow][curColumn++]?.ToString(); var creator = dataTable.Rows[curRow][curColumn]?.ToString(); showRoCo = false; var foundEp = ModelSource.Employees.ToList() .Find(ep => ep.EmployeeNO == epNo && ep.EmployeeBaseInfo.EmployName == epName); if (foundEp == null) { throw new Exception($"未找到员工:{epNo}/{epName}"); } var o = new OverWork { Number = number, Employee = foundEp, BeginDateTime = startTime.ToString(CultureInfo.InvariantCulture), EndDateTime = endTime.ToString(CultureInfo.InvariantCulture), ApplyTime = applyTime.ToString(), //ReduceTime = reduceTime.ToString(CultureInfo.InvariantCulture), OverWorkType = typeOverWork, IsOnDuty = IsOnduty.ParseToBoolean(), IsOffDuty = IsOffduty.ParseToBoolean(), Description = description, Creator = creator }; owList.Add(o); ModelSource.OverWorks.AddWithoutEntity(o); //Console.WriteLine(cellValue is DBNull ? "Empty" : cellValue); } (ModelSource.OverWorks.EntityCtrl as OverWorkControl)?.ImportData(owList); } catch (Exception exception) { //第一行为列名, 第二行开始; 代码从0开始, 显示从1开始; 计算列时catch之前已经被++,所以不用+1 var failTip = showRoCo? $"(行:{curRow + 2} 列:{curColumn})" : string.Empty; MessageBox.Show($"{exception.Message}\r\n{failTip}", "加班单导入失败!"); StatusConsole.WriteLine("加班单导入失败! " + failTip); } }
private void AddEdgeFeature(int index, bool start) // true if start of the edge, false - end of edge { if (index < 0 || (index > Stages.Count - 1)) { MessageBox.Show(@"Error on Chamfering/Filleting\nthis index not exsist"); return; } //default initisialize double value = 1; object operation = "None"; if (start == true) { operation = Stages[index].SOperation; value = Stages[index].SValue; } else { operation = Stages[index].EOperation; value = Stages[index].EValue; } if (operation == (object)"Chamfer") { SwModel.FeatureManager.InsertFeatureChamfer(4, 1, value, helper.ToRad(45), 0, 0, 0, 0); } if (operation == (object)"Fillet") { SwModel.FeatureManager.FeatureFillet(195, value, 0, 0, null, null, null); } }
private void LoadPerformerImageFromFile() { var ofd = new OpenFileDialog(); var result = ofd.ShowDialog(); if (!result.HasValue || result.Value != true) { return; } var filepath = ChooseImageSavePath(); if (filepath is null) { return; } try { PrepareFileForSaving(filepath); File.Copy(ofd.FileName, filepath); } catch (Exception ex) { MessageBox.Show(ex.Message); } _performer.ImagePath = filepath; RaisePropertyChanged("Performer"); }
/// <summary> /// call up old alert settings by number /// вызвать насройки старого алерта по номеру /// </summary> /// <param name="number">номер</param> public void ShowAlertRedactDialog(int number) { try { if (_alertChartUi != null) { MessageBox.Show(OsLocalization.Alerts.Message1); return; } if (number > _alertArray.Count || _alertArray.Count == 0) { return; } if (_alertArray[number].TypeAlert == AlertType.ChartAlert) { _alertChartUi = new AlertToChartCreateUi((AlertToChart)_alertArray[number], this); _alertChartUi.Closing += _ChartAertUi_Closing; _alertChartUi.Show(); } if (_alertArray[number].TypeAlert == AlertType.PriceAlert) { ((AlertToPrice)_alertArray[number]).ShowDialog(); } } catch (Exception error) { SendNewMessage(error.ToString(), LogMessageType.Error); } }
public static void SaveIniData(string section, string key, string value = "") { // ファイルが存在しない場合新規作成 if (!File.Exists(FilePath)) { try { // アプリの設定ファイルを保存するフォルダーが存在しなければ新規作成 if (!Directory.Exists(FolderPath)) { Directory.CreateDirectory(FolderPath); } // ファイルを新規作成 using (var hstream = File.Create(FilePath)) { hstream.Close(); } } catch (Exception e) { MessageBox.Show("エラーが発生しました\n設定ファイルが正常に保存できませんでした"); MessageBox.Show(e.ToString()); } } var ini = new IniFile(FilePath) {