public static void Main(string[] sargs) { Thread.CurrentThread.CurrentUICulture = Culture; CommandArgs args = new CommandArgs(sargs); if (args.styles) { Application.EnableVisualStyles(); } // Damn .NET text rendering Application.SetCompatibleTextRenderingDefault(false); Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(Application.ExecutablePath)); Localizations = new LocalizationInterface(); try { string [] langfiles = Directory.GetFiles("MGE3", "*.lng"); foreach (string langfile in langfiles) { Localizations.Add(langfile); } } catch { }; string language = "English (default)"; bool autoLanguage = true; try { INIFile MGEini = new INIFile(iniFileName, new INIFile.INIVariableDef [] { INIFile.iniDefEmpty, MainForm.iniLanguage, MainForm.iniAutoLang }); language = MGEini.getKeyString("Language"); autoLanguage = (MGEini.getKeyValue("AutoLang") == 1); } catch { } Localizations.Current = language; Localizations.ApplyStrings("", strings); if (args.mutex && !MutexCheck.PerformCheck()) { MessageBox.Show(strings ["MGEguiRunning"], strings ["Error"]); return; } Process [] morrowind = Process.GetProcessesByName("Morrowind"); foreach (Process p in morrowind) { MessageBox.Show(strings ["MWRunning"], strings ["Error"]); return; } if (!File.Exists("./morrowind.exe") || !File.Exists("./morrowind.ini") || !Directory.Exists("data files")) { MessageBox.Show(strings ["NotMWDir"], strings ["Error"]); return; } if (!Directory.Exists("MGE3") || !File.Exists("./MGE3/MGEfuncs.dll") || !File.Exists("./d3d8.dll") || !File.Exists("./dinput8.dll")) { MessageBox.Show(strings ["MGEMissing"], strings ["Error"]); return; } //Morrowind version info try { FileVersionInfo MorrowVersion = FileVersionInfo.GetVersionInfo("Morrowind.exe"); if (MorrowVersion.FileMajorPart != 1 || MorrowVersion.FileMinorPart < 6) { MessageBox.Show(strings ["MWIncompat"], strings ["Error"]); return; } } catch { MessageBox.Show(strings ["MWCorrupt"], strings ["Error"]); return; } runDir = System.Windows.Forms.Application.StartupPath; //check if MW registry keys exist if (Registry.LocalMachine.OpenSubKey(reg_mw) == null) { MessageBox.Show(strings ["MWRegistry"], strings ["Error"]); return; } //Create some structures for (int i = 0; i < MACROS; i++) { Macros [i] = new Macro(); } for (int i = 0; i < TRIGGERS; i++) { Triggers [i] = new Trigger(); } DXMain.GetDeviceCaps(); mf = new MainForm(autoLanguage); Application.Run(mf); }
protected override bool CanShowDefaultIcon() { return(File.Exists(InstalledFilePath)); }
protected override void ExecuteCmdlet() { List <string> exportedTerms; if (ParameterSetName == "TermSet") { if (Delimiter != "|" && Delimiter == ";#") { throw new Exception("Restricted delimiter specified"); } if (!string.IsNullOrEmpty(TermStoreName)) { var taxSession = TaxonomySession.GetTaxonomySession(ClientContext); var termStore = taxSession.TermStores.GetByName(TermStoreName); exportedTerms = ClientContext.Site.ExportTermSet(TermSetId, IncludeID, termStore, Delimiter, Lcid); } else { exportedTerms = ClientContext.Site.ExportTermSet(TermSetId, IncludeID, Delimiter, Lcid); } } else { exportedTerms = ClientContext.Site.ExportAllTerms(IncludeID, Delimiter); } if (Path == null) { WriteObject(exportedTerms); } else { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } System.Text.Encoding textEncoding = System.Text.Encoding.Unicode; switch (Encoding) { case Encoding.ASCII: { textEncoding = System.Text.Encoding.ASCII; break; } case Encoding.BigEndianUnicode: { textEncoding = System.Text.Encoding.BigEndianUnicode; break; } case Encoding.UTF32: { textEncoding = System.Text.Encoding.UTF32; break; } case Encoding.UTF7: { textEncoding = System.Text.Encoding.UTF7; break; } case Encoding.UTF8: { textEncoding = System.Text.Encoding.UTF8; break; } case Encoding.Unicode: { textEncoding = System.Text.Encoding.Unicode; break; } } if (File.Exists(Path)) { if (Force || ShouldContinue(string.Format(Resources.File0ExistsOverwrite, Path), Resources.Confirm)) { File.WriteAllLines(Path, exportedTerms, textEncoding); } } else { File.WriteAllLines(Path, exportedTerms, textEncoding); } } }
/** <summary> * Load a template from dir or group file. Group file is given * precedence over dir with same name. <paramref name="name"/> is * always fully qualified. * </summary> */ protected override CompiledTemplate Load(string name) { if (Verbose) { Console.WriteLine("STGroupDir.load(" + name + ")"); } string parent = Utility.GetParent(name); // must have parent; it's fully-qualified string prefix = Utility.GetPrefix(name); // if (parent.isEmpty()) { // // no need to check for a group file as name has no parent // return loadTemplateFile("/", name+TemplateFileExtension); // load t.st file // } if (!Path.IsPathRooted(parent)) { throw new ArgumentException(); } Uri groupFileURL = null; try { // see if parent of template name is a group file groupFileURL = new Uri(TemplateName.GetTemplatePath(root.LocalPath, parent) + GroupFileExtension); } catch (UriFormatException e) { ErrorManager.InternalError(null, "bad URL: " + TemplateName.GetTemplatePath(root.LocalPath, parent) + GroupFileExtension, e); return(null); } if (!File.Exists(groupFileURL.LocalPath)) { string unqualifiedName = Path.GetFileName(name); return(LoadTemplateFile(prefix, unqualifiedName + TemplateFileExtension)); // load t.st file } #if false InputStream @is = null; try { @is = groupFileURL.openStream(); } catch (FileNotFoundException fnfe) { // must not be in a group file return(loadTemplateFile(parent, name + TemplateFileExtension)); // load t.st file } catch (IOException ioe) { errMgr.internalError(null, "can't load template file " + name, ioe); } try { // clean up if (@is != null) { @is.close(); } } catch (IOException ioe) { errMgr.internalError(null, "can't close template file stream " + name, ioe); } #endif LoadGroupFile(prefix, groupFileURL.LocalPath); return(RawGetTemplate(name)); }
public async Task <JsonResult> UploadGallery(App app, IEnumerable <HttpPostedFileBase> galleries) { if (galleries != null && app.UploadGuid != null) { //look for cache if sequence exist before var nextSequence = GetSequenceNumber(app.UploadGuid); var nextCount = GetHowManyGalleryImageExist(app.UploadGuid); if (nextCount > AppVar.Setting.GalleryMaxPictures) { ResetSessionForUploadSequence(app.UploadGuid); return(Json(new { isUploaded = false, uploadedFiles = 0, message = "You are out of your limit." }, "text/html")); } var fileName = app.UploadGuid.ToString(); var firstTime = true; var countDone = 0; foreach (var file in galleries) { if (file.ContentLength > 0) { // first save gallery and temp record. if (!firstTime) { nextSequence = GetSequenceNumber(app.UploadGuid); nextCount = GetHowManyGalleryImageExist(app.UploadGuid); if (nextCount > AppVar.Setting.GalleryMaxPictures) { ResetSessionForUploadSequence(app.UploadGuid); return (Json( new { isUploaded = true, uploadedFiles = countDone, message = "You are out of your limit." }, "text/html")); } } else { firstTime = false; } //upload app-details page gallery image Statics.UProcessorGallery.UploadFile(file, fileName, nextSequence, true, true); //successfully uploaded now save a gallery info var galleryCategory = await db.GalleryCategories.FindAsync(GalleryCategoryIDs.AppPageGallery); //var thumbsCategory = await db.GalleryCategories.FindAsync(GalleryCategoryIDs.GalleryIcon); var gallery = await db.Galleries.FirstOrDefaultAsync( n => n.UploadGuid == app.UploadGuid && n.GalleryCategoryID == galleryCategory.GalleryCategoryID && n.Sequence == nextSequence); // saving in the database if (gallery == null) { // we didn't get the error // image sequence and guid is correct. gallery = new Gallery(); gallery.GalleryID = Guid.NewGuid(); gallery.UploadGuid = app.UploadGuid; if (!string.IsNullOrEmpty(app.AppName)) { gallery.Title = app.AppName + "-" + nextSequence; } gallery.Extension = UploadProcessor.GetExtension(file); gallery.GalleryCategoryID = galleryCategory.GalleryCategoryID; gallery.Sequence = nextSequence; db.Galleries.Add(gallery); // try to add a temp record as well. var tempUpload = new TempUpload(); tempUpload.TempUploadID = Guid.NewGuid(); tempUpload.UserID = UserManager.GetLoggedUserId(); tempUpload.GalleryID = gallery.GalleryID; tempUpload.RelatingUploadGuidForDelete = app.UploadGuid; db.TempUploads.Add(tempUpload); await db.SaveChangesAsync(); } // resize //new Thread(() => { // resize app-details page gallery image Statics.UProcessorGallery.ResizeImageAndProcessImage(gallery, galleryCategory); //var source = "~/Uploads/Images/" + Variables.ADDITIONAL_ROOT_GALLERY_LOCATION + // UploadProcessor.GetOrganizeNameStatic(gallery, true, true); //var target = "~/Uploads/Images/" + Variables.ADDITIONAL_ROOT_GALLERY_ICON_LOCATION + // UploadProcessor.GetOrganizeNameStatic(gallery, true); // #apps detail page gallery thumbs generate //Statics.uProcessorGallery.ResizeImageAndProcessImage(source, target, thumbsCategory.Width, // thumbsCategory.Height, gallery.Extension); var source = "~/Uploads/Images/" + Variables.AdditionalRootGalleryLocation + UploadProcessor.GetOrganizeNameStatic(gallery, true, true); //removing temp image what was exact uploaded after resizing it. if (FileSys.Exists(Statics.UProcessorGallery.VirtualPathtoAbsoluteServerPath(source))) { // if processed image exist then remove the temp. Statics.UProcessorGallery.RemoveTempImage(gallery); } countDone++; //}).Start(); } } var countUploaded = galleries.Count(); return (Json( new { isUploaded = true, uploadedFiles = countUploaded, message = "+" + countUploaded + " files successfully done." }, "text/html")); } return(Json(new { isUploaded = false, uploadedFiles = 0, message = "No file send." }, "text/html")); }
protected virtual void HandleArgs() { int i = 0; while (args != null && i < args.Length) { string arg = args[i]; i++; if (arg.StartsWith("-D")) { // -Dlanguage=Java syntax HandleOptionSetArg(arg); continue; } if (arg[0] != '-') { // file name if (!grammarFiles.Contains(arg)) grammarFiles.Add(arg); continue; } bool found = false; foreach (Option o in optionDefs) { if (arg.Equals(o.name)) { found = true; string argValue = null; if (o.argType == OptionArgType.STRING) { argValue = args[i]; i++; } // use reflection to set field try { FieldInfo f = GetField(GetType(), o.fieldName); if (argValue == null) { if (arg.StartsWith("-no-")) f.SetValue(this, false); else f.SetValue(this, true); } else f.SetValue(this, argValue); } catch (Exception) { errMgr.ToolError(ErrorType.INTERNAL_ERROR, "can't access field " + o.fieldName); } } } if (!found) { errMgr.ToolError(ErrorType.INVALID_CMDLINE_ARG, arg); } } if (outputDirectory != null) { if (outputDirectory.EndsWith("/") || outputDirectory.EndsWith("\\")) { outputDirectory = outputDirectory.Substring(0, outputDirectory.Length - 1); } string outDir = outputDirectory; haveOutputDir = true; if (File.Exists(outDir)) { errMgr.ToolError(ErrorType.OUTPUT_DIR_IS_FILE, outputDirectory); libDirectory = "."; } } else { outputDirectory = "."; } if (libDirectory != null) { if (libDirectory.EndsWith("/") || libDirectory.EndsWith("\\")) { libDirectory = libDirectory.Substring(0, libDirectory.Length - 1); } string outDir = libDirectory; if (!Directory.Exists(outDir)) { errMgr.ToolError(ErrorType.DIR_NOT_FOUND, libDirectory); libDirectory = "."; } } else { libDirectory = "."; } if (launch_ST_inspector) { //TemplateGroup.trackCreationEvents = true; return_dont_exit = true; } }
/// <summary> /// Finds the main AASX Package Explorer window and executes the code dependent on it. /// </summary> /// <remarks>This method is necessary since splash screen confuses FlaUI and prevents us from /// easily determining the main window.</remarks> /// <param name="implementation">Code to be executed</param> /// <param name="run">Run options. If null, a new run with default values is used</param> public static void RunWithMainWindow(Implementation implementation, Run?run = null) { string environmentVariable = "AASX_PACKAGE_EXPLORER_RELEASE_DIR"; string releaseDir = System.Environment.GetEnvironmentVariable(environmentVariable); if (releaseDir == null) { throw new InvalidOperationException( $"Expected the environment variable to be set: {environmentVariable}; " + "otherwise we can not find binaries to be tested through functional tests."); } string pathToExe = Path.Combine(releaseDir, "AasxPackageExplorer.exe"); if (!File.Exists(pathToExe)) { throw new FileNotFoundException( "The executable of the AASX Package Explorer " + $"could not be found in the release directory: {pathToExe}; did you compile it properly before?"); } var resolvedRun = run ?? new Run(); // See https://stackoverflow.com/questions/5510343/escape-command-line-arguments-in-c-sharp string joinedArgs = string.Join( " ", resolvedRun.Args .Select(arg => Regex.Replace(arg, @"(\\*)" + "\"", @"$1$1\" + "\""))); var psi = new ProcessStartInfo { FileName = pathToExe, Arguments = joinedArgs, RedirectStandardError = true, WorkingDirectory = releaseDir, UseShellExecute = false }; bool gotStderr = false; var process = new Process { StartInfo = psi }; try { process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { gotStderr = true; TestContext.Error.WriteLine(e.Data); } }; process.Start(); process.BeginErrorReadLine(); } catch (Exception) { TestContext.Error.WriteLine( $"Failed to launch the process: FileName: {psi.FileName}, " + $"Arguments: {psi.Arguments}, Working directory: {psi.WorkingDirectory}"); throw; } var app = new Application(process, false); try { using var automation = new UIA3Automation(); var mainWindow = Retry.Find(() => // ReSharper disable once AccessToDisposedClosure app.GetAllTopLevelWindows(automation) .FirstOrDefault( (w) => w.AutomationId == "mainWindow"), new RetrySettings { ThrowOnTimeout = true, Timeout = TimeSpan.FromSeconds(5), TimeoutMessage = "Could not find the main window" }).AsWindow(); implementation(app, automation, mainWindow); } finally { if (!resolvedRun.DontKill) { app.Kill(); } } if (gotStderr) { throw new AssertionException( "Unexpected writes to standard error. Please see the test context for more detail."); } }
public static bool Exists(string path) { return(File.Exists(path)); }
/// <summary> /// Uninstalls a package /// </summary> /// <param name="fastPackageReference"></param> /// <param name="request"> /// An object passed in from the CORE that contains functions that can be used to interact with /// the CORE and HOST /// </param> public void UninstallPackage(string fastPackageReference, Request request) { if (string.IsNullOrWhiteSpace(fastPackageReference)) { return; } if (request == null) { throw new ArgumentNullException("request"); } request.Debug("Calling '{0}::UninstallPackage' '{1}'", ProviderName, fastPackageReference); // Nice-to-have put a debug message in that tells what's going on. var path = fastPackageReference.Split(new[] { '\\' }, 3); var uninstallCommand = string.Empty; Dictionary <string, string> properties = null; if (path.Length == 3) { switch (path[0].ToLowerInvariant()) { case "hklm64": using (var product = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(path[2], RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey)) { if (product == null) { return; } properties = product.GetValueNames().ToDictionaryNicely(each => each.ToString(), each => (product.GetValue(each) ?? string.Empty).ToString(), StringComparer.OrdinalIgnoreCase); uninstallCommand = properties.Get("QuietUninstallString") ?? properties.Get("UninstallString") ?? ""; } break; case "hkcu64": using (var product = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).OpenSubKey(path[2], RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey)) { if (product == null) { return; } properties = product.GetValueNames().ToDictionaryNicely(each => each.ToString(), each => (product.GetValue(each) ?? string.Empty).ToString(), StringComparer.OrdinalIgnoreCase); uninstallCommand = properties.Get("QuietUninstallString") ?? properties.Get("UninstallString") ?? ""; } break; case "hklm32": using (var product = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(path[2], RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey)) { if (product == null) { return; } properties = product.GetValueNames().ToDictionaryNicely(each => each.ToString(), each => (product.GetValue(each) ?? string.Empty).ToString(), StringComparer.OrdinalIgnoreCase); uninstallCommand = properties.Get("QuietUninstallString") ?? properties.Get("UninstallString") ?? ""; } break; case "hkcu32": using (var product = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).OpenSubKey(path[2], RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey)) { if (product == null) { return; } properties = product.GetValueNames().ToDictionaryNicely(each => each.ToString(), each => (product.GetValue(each) ?? string.Empty).ToString(), StringComparer.OrdinalIgnoreCase); uninstallCommand = properties.Get("QuietUninstallString") ?? properties.Get("UninstallString") ?? ""; } break; } if (properties == null) { return; } if (!string.IsNullOrWhiteSpace(uninstallCommand)) { do { if (File.Exists(uninstallCommand)) { ExecStandalone(request, uninstallCommand); break; } // not a single file. // check if it's just quoted. var c = uninstallCommand.Trim('\"'); if (File.Exists(c)) { ExecStandalone(request, c); break; } if (uninstallCommand.IndexOf("msiexec", StringComparison.OrdinalIgnoreCase) > -1) { MsiUninstall(request, uninstallCommand); break; } if (uninstallCommand.IndexOf("rundll32", StringComparison.OrdinalIgnoreCase) > -1) { RunDll32(request, uninstallCommand); break; } if (uninstallCommand.IndexOf("cmd.exe", StringComparison.OrdinalIgnoreCase) == 0) { CmdCommand(request, uninstallCommand); continue; } if (uninstallCommand.IndexOf("cmd ", StringComparison.OrdinalIgnoreCase) == 0) { CmdCommand(request, uninstallCommand); continue; } if (uninstallCommand[0] == '"') { var p = uninstallCommand.IndexOf('"', 1); if (p > 0) { var file = uninstallCommand.Substring(1, p - 1); var args = uninstallCommand.Substring(p + 1); if (File.Exists(file)) { CommandWithParameters(request, file, args); } } } else { var p = uninstallCommand.IndexOf(' '); if (p > 0) { var file = uninstallCommand.Substring(0, p); var args = uninstallCommand.Substring(p + 1); if (File.Exists(file)) { CommandWithParameters(request, file, args); continue; } var s = 0; do { s = uninstallCommand.IndexOf(' ', s + 1); if (s == -1) { break; } file = uninstallCommand.Substring(0, s); if (File.Exists(file)) { args = uninstallCommand.Substring(s + 1); CommandWithParameters(request, file, args); break; } } while (s > -1); if (s == -1) { // never found a way to parse the command :( request.Error(ErrorCategory.InvalidOperation, properties["DisplayName"], Constants.Messages.UnableToUninstallPackage); return; } } } } while (false); YieldPackage(fastPackageReference, fastPackageReference, properties, request); return; } request.Error(ErrorCategory.InvalidOperation, properties["DisplayName"], Constants.Messages.UnableToUninstallPackage); } }
private void ParseReferenceSourceFile(object state) { string fileName = state as string; if (string.IsNullOrEmpty(fileName)) { return; } try { if (!File.Exists(fileName)) { return; } string sourceText = File.ReadAllText(fileName); var inputStream = new ANTLRStringStream(sourceText, fileName); var unicodeStream = new JavaUnicodeStream(inputStream); var lexer = new Java2Lexer(unicodeStream); var tokenStream = new CommonTokenStream(lexer); var parser = new Java2Parser(tokenStream); int[] lineOffsets = null; var outputWindow = OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense); List <ParseErrorEventArgs> errors = new List <ParseErrorEventArgs>(); parser.ParseError += (sender, e) => { errors.Add(e); string message = e.Message; if (message.Length > 100) { message = message.Substring(0, 100) + " ..."; } if (lineOffsets == null) { lineOffsets = FindLineOffsets(sourceText); } int line = Array.BinarySearch(lineOffsets, e.Span.Start); if (line < 0) { line = -line - 2; } int column; if (line >= lineOffsets.Length) { column = 0; } else { column = e.Span.Start - lineOffsets[line]; } if (outputWindow != null) { outputWindow.WriteLine(string.Format("{0}({1},{2}): {3}", fileName, line + 1, column + 1, message)); } if (errors.Count > 20) { throw new OperationCanceledException(); } }; var result = parser.compilationUnit(); CodeFileBuilder fileBuilder = new CodeFileBuilder(fileName); var treeNodeStream = new CommonTreeNodeStream(result.Tree); treeNodeStream.TokenStream = tokenStream; var walker = new IntelliSenseCacheWalker(treeNodeStream); List <ParseErrorEventArgs> walkerErrors = new List <ParseErrorEventArgs>(); walker.ParseError += (sender, e) => { walkerErrors.Add(e); string message = e.Message; if (message.Length > 100) { message = message.Substring(0, 100) + " ..."; } if (lineOffsets == null) { lineOffsets = FindLineOffsets(sourceText); } int line = Array.BinarySearch(lineOffsets, e.Span.Start); if (line < 0) { line = -line - 2; } int column; if (line >= lineOffsets.Length) { column = 0; } else { column = e.Span.Start - lineOffsets[line]; } if (outputWindow != null) { outputWindow.WriteLine(string.Format("{0}({1},{2}): {3}", fileName, line + 1, column + 1, message)); } if (walkerErrors.Count > 20) { throw new OperationCanceledException(); } }; walker.compilationUnit(fileBuilder); UpdateFile(fileBuilder); } catch (Exception e) { if (ErrorHandler.IsCriticalException(e)) { throw; } } }
public static void Setup() { // Get the application configuration file. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (File.Exists(configFile)) { File.Delete(configFile); } do { qconf.Name = ""; qconf.QuikPath = ""; qconf.User = ""; qconf.Password = ""; while (string.IsNullOrEmpty(qconf.Name)) { Console.WriteLine(@"Please enter connection name, e.g. MyQuik (max 50 symbols)"); qconf.Name = Console.ReadLine().Trim(new char[] { '"', ' ', "'".ToCharArray()[0] }); if (qconf.Name.Length > 50) { Console.WriteLine(@"Too long"); qconf.Name = ""; } } ; while (string.IsNullOrEmpty(qconf.QuikPath)) { Console.WriteLine(@"Please enter the full path to Quik, e.g. C:\Quik\info.exe"); qconf.QuikPath = Console.ReadLine().Trim(new char[] { '"', ' ', "'".ToCharArray()[0] }); } while (string.IsNullOrEmpty(qconf.User)) { Console.WriteLine(@"Please enter user name, e.g. Smith John or Иванов Иван (max 50 symbols)"); qconf.User = Console.ReadLine().Trim(new char[] { '"', ' ', "'".ToCharArray()[0] }); if (qconf.User.Length > 50) { Console.WriteLine(@"Too long"); qconf.User = ""; } } while (string.IsNullOrEmpty(qconf.Password)) { Console.WriteLine(@"Please enter password (it will be visible on the screen), e.g. myPa$$w0rD (max 50 symbols)"); qconf.Password = Console.ReadLine().Trim(); if (qconf.Password.Length > 50) { Console.WriteLine(@"Too long"); qconf.Password = ""; } } Console.WriteLine(@"Is everything correct (Y/N)?"); } while (Console.ReadLine().ToLower().Substring(0, 1) != "y"); //Console.Clear(); // From MSDN: Key containers provide the most secure way to persist cryptographic keys // and keep them secret from malicious third parties. string containerName = qconf.Name.GetStringHash(); string salt = MachineIdentificator.GetUniqueStringID(); var RSAProvider = RsaUtilities.GetRSAProviderFromContainer(containerName + salt, false); //Encrypt sensitive parts qconf.User = Convert.ToBase64String( RSAProvider.Encrypt(Encoding.UTF8.GetBytes(qconf.User), false) ); qconf.Password = Convert.ToBase64String( RSAProvider.Encrypt(Encoding.UTF8.GetBytes(qconf.Password), false) ); // You need to remove the old settings object before you can replace it config.Sections.Remove("QuikConfiguration"); // with an updated one config.Sections.Add("QuikConfiguration", qconf); // Write the new configuration data to the XML file config.SaveAs(configFile, ConfigurationSaveMode.Full); Console.WriteLine(@"You data is saved."); }
private void OnRestore(object sender = null, RoutedEventArgs e = null) { MessageBoxResult result; bool cleanup = false; if (!ValidPathTest()) { return; } if (!File.Exists(Patcher.BackupPath)) { TriggerMessageBox.Show(this, MessageIcon.Error, "Could not find Terraria backup!", "Missing Backup"); return; } result = TriggerMessageBox.Show(this, MessageIcon.Question, "Would you like to restore the current Terraria executable to its backup and cleanup the required files or just restore the backup?", "Restore Terraria", MessageBoxButton.YesNoCancel, "Cleanup & Restore", "Restore Only"); if (result == MessageBoxResult.Cancel) { return; } cleanup = result == MessageBoxResult.Yes; if (File.Exists(Patcher.ExePath) && IL.GetAssemblyVersion(Patcher.BackupPath) < IL.GetAssemblyVersion(Patcher.ExePath)) { result = TriggerMessageBox.Show(this, MessageIcon.Warning, "The backed up Terraria executable is an older game version. Are you sure you want to restore it?", "Older Version", MessageBoxButton.YesNo); if (result == MessageBoxResult.No) { return; } } try { Patcher.Restore(cleanup); bool someMissing = ContentReplacer.Restore(); // Clean up directory and remove config file if (cleanup) { string configPath = Path.Combine(Patcher.ExeDirectory, CoinReplacer.ConfigName); string logPath = Path.Combine(Patcher.ExeDirectory, ErrorLogger.LogName); if (File.Exists(configPath)) { File.Delete(configPath); } if (File.Exists(logPath)) { File.Delete(logPath); } } if (someMissing) { TriggerMessageBox.Show(this, MessageIcon.Info, "Terraria executable restored but some backup content files were missing!", "Missing Content"); } else { TriggerMessageBox.Show(this, MessageIcon.Info, "Terraria successfully restored!", "Terraria Restored"); } } catch (Exception ex) { result = TriggerMessageBox.Show(this, MessageIcon.Error, "An error occurred while restoring Terraria! Would you like to see the error?", "Restore Error", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { ErrorMessageBox.Show(ex, true); } } }
// This is NOT thread safe but it is only called from within a lock private Assembly GetModelsAssembly(bool forceRebuild) { if (!Directory.Exists(_pureLiveDirectory.Value)) { Directory.CreateDirectory(_pureLiveDirectory.Value); } IList <TypeModel> typeModels = UmbracoServices.GetAllTypes(); var currentHash = TypeModelHasher.Hash(typeModels); var modelsHashFile = Path.Combine(_pureLiveDirectory.Value, "models.hash"); var modelsSrcFile = Path.Combine(_pureLiveDirectory.Value, "models.generated.cs"); var projFile = Path.Combine(_pureLiveDirectory.Value, "all.generated.cs"); var dllPathFile = Path.Combine(_pureLiveDirectory.Value, "all.dll.path"); // caching the generated models speeds up booting // currentHash hashes both the types & the user's partials if (!forceRebuild) { _logger.LogDebug("Looking for cached models."); if (File.Exists(modelsHashFile) && File.Exists(projFile)) { var cachedHash = File.ReadAllText(modelsHashFile); if (currentHash != cachedHash) { _logger.LogDebug("Found obsolete cached models."); forceRebuild = true; } // else cachedHash matches currentHash, we can try to load an existing dll } else { _logger.LogDebug("Could not find cached models."); forceRebuild = true; } } Assembly assembly; if (!forceRebuild) { // try to load the dll directly (avoid rebuilding) // // ensure that the .dll file does not have a corresponding .dll.delete file // as that would mean the the .dll file is going to be deleted and should not // be re-used - that should not happen in theory, but better be safe if (File.Exists(dllPathFile)) { var dllPath = File.ReadAllText(dllPathFile); _logger.LogDebug($"Cached models dll at {dllPath}."); if (File.Exists(dllPath) && !File.Exists(dllPath + ".delete")) { assembly = ReloadAssembly(dllPath); ModelsBuilderAssemblyAttribute?attr = assembly.GetCustomAttribute <ModelsBuilderAssemblyAttribute>(); if (attr != null && attr.IsInMemory && attr.SourceHash == currentHash) { // if we were to resume at that revision, then _ver would keep increasing // and that is probably a bad idea - so, we'll always rebuild starting at // ver 1, but we remember we want to skip that one - so we never end up // with the "same but different" version of the assembly in memory _skipver = assembly.GetName().Version?.Revision; _logger.LogDebug("Loading cached models (dll)."); return(assembly); } _logger.LogDebug("Cached models dll cannot be loaded (invalid assembly)."); } else if (!File.Exists(dllPath)) { _logger.LogDebug("Cached models dll does not exist."); } else if (File.Exists(dllPath + ".delete")) { _logger.LogDebug("Cached models dll is marked for deletion."); } else { _logger.LogDebug("Cached models dll cannot be loaded (why?)."); } } // must reset the version in the file else it would keep growing // loading cached modules only happens when the app restarts var text = File.ReadAllText(projFile); Match match = s_assemblyVersionRegex.Match(text); if (match.Success) { text = text.Replace(match.Value, "AssemblyVersion(\"0.0.0." + _ver + "\")"); File.WriteAllText(projFile, text); } _ver++; try { var assemblyPath = GetOutputAssemblyPath(currentHash); RoslynCompiler.CompileToFile(projFile, assemblyPath); assembly = ReloadAssembly(assemblyPath); File.WriteAllText(dllPathFile, assembly.Location); File.WriteAllText(modelsHashFile, currentHash); TryDeleteUnusedAssemblies(dllPathFile); } catch { ClearOnFailingToCompile(dllPathFile, modelsHashFile, projFile); throw; } _logger.LogDebug("Loading cached models (source)."); return(assembly); } // need to rebuild _logger.LogDebug("Rebuilding models."); // generate code, save var code = GenerateModelsCode(typeModels); // add extra attributes, // IsLive=true helps identifying Assemblies that contain live models // AssemblyVersion is so that we have a different version for each rebuild var ver = _ver == _skipver ? ++_ver : _ver; _ver++; string mbAssemblyDirective = $@"[assembly:ModelsBuilderAssembly(IsInMemory = true, SourceHash = ""{currentHash}"")] [assembly:System.Reflection.AssemblyVersion(""0.0.0.{ver}"")]"; code = code.Replace("//ASSATTR", mbAssemblyDirective); File.WriteAllText(modelsSrcFile, code); // generate proj, save var projFiles = new Dictionary <string, string> { { "models.generated.cs", code } }; var proj = GenerateModelsProj(projFiles); File.WriteAllText(projFile, proj); // compile and register try { var assemblyPath = GetOutputAssemblyPath(currentHash); RoslynCompiler.CompileToFile(projFile, assemblyPath); assembly = ReloadAssembly(assemblyPath); File.WriteAllText(dllPathFile, assemblyPath); File.WriteAllText(modelsHashFile, currentHash); TryDeleteUnusedAssemblies(dllPathFile); } catch { ClearOnFailingToCompile(dllPathFile, modelsHashFile, projFile); throw; } _logger.LogDebug("Done rebuilding."); return(assembly); }
public bool Load() { bool r = false; bool ve = FileIO.Exists(VersionFilePath); if (ve) { String VersionFileContents = FileIO.ReadAllText(VersionFilePath, System.Text.Encoding.Unicode); if (VersionFileContents == NetworkConfig.VersionString) { r = true; } else { String IncompatPath = String.Concat(DataSavePath, "_", VersionFileContents); if (DirectoryIO.Exists(IncompatPath)) { DirectoryIO.Delete(IncompatPath, true); } DirectoryIO.Move(DataSavePath, IncompatPath); System.Windows.Forms.MessageBox.Show(String.Concat( "The application tried to load Js ChatterBox files that were incompatible ", "with this version. They have been moved to \"", IncompatPath, "\".")); } } if (r) { try { #region ConfigFileLoading { String ConfigText = FileIO.ReadAllText(ConfigFilePath, System.Text.Encoding.Unicode); JsEncoder.TableValue ConfigTable = (JsEncoder.TableValue)JsEncoder.DecoderStream.DecodeValue(ConfigText); UserName = ((JsEncoder.StringValue)ConfigTable[new JsEncoder.StringValue("UserName")]).Value; WorkingPort = ((JsEncoder.IntValue)ConfigTable[new JsEncoder.StringValue("WorkingPort")]).Value; } #endregion String HostListFileContents = FileIO.ReadAllText(HostListFilePath, System.Text.Encoding.Unicode); JsEncoder.TableValue HostListTable = (JsEncoder.TableValue)JsEncoder.DecoderStream.DecodeValue(HostListFileContents); HostList = UserHostList.FromTable(HostListTable); } catch (Exception e) { String BaseIncompatPath = String.Concat(DataSavePath, "_Damaged<N>"); String FinalIncompatPath = null; int i = 0; while (FinalIncompatPath == null) { i++; FinalIncompatPath = BaseIncompatPath.Replace("<N>", i.ToString()); if (DirectoryIO.Exists(FinalIncompatPath)) { FinalIncompatPath = null; } } DirectoryIO.Move(DataSavePath, FinalIncompatPath); r = false; System.Windows.Forms.MessageBox.Show(String.Concat( "An error occured while loading your save files. They have been moved to \"", FinalIncompatPath, "\" and you will now get the defaults. ", "The error message is \"", e.Message, "\".")); } } if (!r) { UserName = "******"; HostList = new UserHostList(); WorkingPort = NetworkConfig.DefaultServerPort; } _IsLoaded = true; return(r); }
public bool NewerThan(FileRef dst) { Debug.Assert(IOFile.Exists(this)); return(!IOFile.Exists(dst) || IOFile.GetLastWriteTime(this) > IOFile.GetLastWriteTime(dst)); }