private void savetofilelog() { if (LogBox.Text != "") { bool newfile = true; string textlog = ""; if (File.Exists("log.txt")) { newfile = false; textlog = File.ReadAllText("log.txt"); File.WriteAllText("log.txt", ""); } else { newfile = true; File.WriteAllText("log.txt", ""); } using (var stream = File.CreateText("log.txt")) { stream.Write(LogBox.Text); LogBox.Clear(); if (!newfile) { stream.Write(textlog); } } } }
/// <exception cref="System.IO.IOException"/> public virtual void Load(string fileName, Encoding encoding) { if (fileName == null) { return; } string text; #if !COMPACT if (encoding != null) { text = File.ReadAllText(fileName, encoding); } else { text = File.ReadAllText(fileName); } #else if (encoding != null) { text = ReadAllText(fileName, encoding); } else { text = ReadAllText(fileName); } #endif data = text.ToCharArray(); n = data.Length; }
private void TryDeleteUnusedAssemblies(string dllPathFile) { if (File.Exists(dllPathFile)) { var dllPath = File.ReadAllText(dllPathFile); DirectoryInfo? dirInfo = new DirectoryInfo(dllPath).Parent; IEnumerable <FileInfo>?files = dirInfo?.GetFiles().Where(f => f.FullName != dllPath); if (files is null) { return; } foreach (FileInfo file in files) { try { File.Delete(file.FullName); } catch (UnauthorizedAccessException) { // The file is in use, we'll try again next time... // This shouldn't happen anymore. } } } }
public static IEnumerable <NavigationWidget> SuiteWidgets(IFileProvider fileProvider) { var file = fileProvider.GetFileInfo("/shared/nav.json"); var navigationJson = IOFile.ReadAllText(file.PhysicalPath); return(JsonConvert.DeserializeObject <IEnumerable <NavigationWidget> >(navigationJson)); }
public IWorldInstance Deserialise(string worldName) { string directory = Directory.GetCurrentDirectory() + "/save/" + worldName; string json = File.ReadAllText(directory + "/relationships.dat"); Dictionary tempDict = this.GetDictionary(json); GlobalConstants.GameManager.RelationshipHandler.Load(tempDict); json = File.ReadAllText(directory + "/entities.dat"); tempDict = this.GetDictionary(json); GlobalConstants.GameManager.EntityHandler.Load(tempDict); json = File.ReadAllText(directory + "/items.dat"); tempDict = this.GetDictionary(json); GlobalConstants.GameManager.ItemHandler.Load(tempDict); json = File.ReadAllText(directory + "/quests.dat"); tempDict = this.GetDictionary(json); GlobalConstants.GameManager.QuestTracker.Load(tempDict); json = File.ReadAllText(directory + "/world.dat"); tempDict = this.GetDictionary(json); IWorldInstance overworld = new WorldInstance(); overworld.Load(tempDict); return(overworld); }
private void LaunchInformationDialog(string sourceName) { try { if (informationDialog == null) { informationDialog = new InformationDialog { Height = 500, Width = 400 }; informationDialog.Closed += (o, args) => { informationDialog = null; }; informationDialog.Closing += (o, args) => { }; } informationDialog.Height = 500; informationDialog.Width = 400; var filePath = AppDomain.CurrentDomain.BaseDirectory + @"HelpFiles\" + sourceName + ".html"; var helpFile = File.ReadAllText(filePath); informationDialog.HelpInfo.NavigateToString(helpFile); informationDialog.Launch(); } catch (Exception ex) { LogErrorMessage(ex); } }
public JsonRpcResponse <T> MakeFauxRequest <T>(string file) { string json; try { json = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"/../../App_Data/" + file); } catch (Exception) { json = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"/../../App_Data/error.json"); } var response = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json); if (response.Error == null) { return(response); } var internalServerErrorException = new RpcInternalServerErrorException(response.Error.Message) { RpcErrorCode = response.Error.Code }; throw internalServerErrorException; }
public virtual void ParseAndRewrite() { ProcessArgs(args); ICharStream input = null; if (filename != null) { input = new ANTLRStringStream(File.ReadAllText(filename), filename); } else { input = new ANTLRReaderStream(Console.In, ANTLRReaderStream.InitialBufferSize, ANTLRReaderStream.ReadBufferSize); } // BUILD AST ANTLRLexer lex = new ANTLRLexer(input); tokens = new TokenRewriteStream(lex); ANTLRParser g = new ANTLRParser(tokens); Grammar grammar = new Grammar(); var r = g.grammar_(grammar); CommonTree t = (CommonTree)r.Tree; if (tree_option) { Console.Out.WriteLine(t.ToStringTree()); } Rewrite(g.TreeAdaptor, t, g.TokenNames); }
public ActionResult Index(string path) { if (String.IsNullOrEmpty(path) || ( !path.StartsWith("/Views") && !path.StartsWith("/Models") && !path.StartsWith("/content") && !path.StartsWith("/Controllers"))) { return(NotFound()); } var mappedPath = _hostingEnvironment.ContentRootPath + path.Replace("/", "\\"); if (!IOFile.Exists(mappedPath)) { return(NotFound()); } if (path.StartsWith("/content") && path.EndsWith("html")) { return(Content(IOFile.ReadAllText(mappedPath), "text/html")); } var source = IOFile.ReadAllText(mappedPath); return(Content("<pre class='prettyprint'>" + _htmlEncoder.Encode(source) + "</pre>", "text/plain")); }
private Credentials GetCredentials() { if (applicationOptions == null) { return(null); } var filename = applicationOptions.CredentialsFile; if (string.IsNullOrWhiteSpace(filename)) { logger.LogInformation("No Credentials file given. Anonymous requests will be performed."); return(null); } if (!IOFile.Exists(filename)) { logger.LogInformation($"No Credentials file found at '{filename}'"); } var content = IOFile.ReadAllText(applicationOptions.CredentialsFile); var document = JsonDocument.Parse(content); var element = document.RootElement; return(new Credentials { Username = element.GetProperty("username").GetString(), Password = element.GetProperty("password").GetString() }); }
/// <summary> /// bot を初期化します。 /// </summary> /// <returns>初期化された <see cref="Shell"/> のインスタンス。</returns> public static async Task <Shell> InitializeAsync() { MisskeyClient mi; var logger = new Logger(nameof(Shell)); try { var credential = File.ReadAllText("./token"); mi = new MisskeyClient(JsonConvert.DeserializeObject <Disboard.Models.Credential>(credential)); logger.Info("Misskey に接続しました。"); } catch (Exception) { logger.Error($"認証に失敗しました。セットアップを開始します。"); Write("Misskey URLを入力してください。> "); var host = ReadLine(); mi = new MisskeyClient(host); await AuthorizeAsync(mi, logger); } var myself = await mi.IAsync(); logger.Info($"bot ユーザーを取得しました (@{myself.Username})"); // 呼ばないとストリームの初期化ができないらしい await mi.Streaming.ConnectAsync(); var sh = new Shell(mi, myself, logger); sh.MaxNoteLength = (await mi.MetaAsync()).MaxNoteTextLength; return(sh); }
public void Start() { if (File.Exists("playersToNotify.txt")) { try { var lines = File.ReadAllLines("playersToNotify.txt").Select(x => { if (long.TryParse(x, out var id)) { return((long?)id); } return(null); }); foreach (var line in lines.Where(x => x.HasValue).Cast <long>()) { _playersToNotify.Add(line); } } catch (Exception e) { Console.WriteLine(e); } } var key = File.ReadAllText("botkey.key"); _botClient = new TelegramBotClient(key); _botClient.OnMessage += Bot_OnMessage; _botClient.StartReceiving(); }
public void Provision(ClientContext ctx, Web web, string siteDefinitionJsonFileAbsolutePath) { var json = File.ReadAllText(siteDefinitionJsonFileAbsolutePath); var siteDef = SiteDefinition.GetSiteDefinitionFromJson(json); Provision(ctx, web, siteDef); }
static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; Console.WriteLine("Hello World!"); var token = File.ReadAllText(AppContext.BaseDirectory + "token").Trim(); Handlers = new List <BaseHandler>() { new ConsoleWriterHandler() } .Concat(ReflectiveEnumerator.GetListOfType <BaseHandler>().Where(a => !(a is ConsoleWriterHandler))) .ToList(); for (int i = 0; i < Handlers.Count - 1; i++) { Handlers[i].NextHandler = Handlers[i + 1]; } _client = new TelegramBotClient(token); _client.OnMessage += OnMessage; _client.OnMessageEdited += OnMessage; AppDomain.CurrentDomain.UnhandledException += async(object sender, UnhandledExceptionEventArgs args2) => { await _client.SendTextMessageAsync(new ChatId(91740825), $"Unhandled exception!\n{args2.ExceptionObject}\n{(args2.ExceptionObject as Exception).InnerException?.Message}", disableNotification : true); }; _client.StartReceiving(new[] { UpdateType.EditedMessage, UpdateType.Message }); Console.ReadLine(); }
protected IEnumerable <NavigationWidget> LoadWidgets() { var rootPath = _hostingEnvironment.WebRootPath; var navJson = IOFile.ReadAllText(rootPath + "/shared/nav.json"); return(JsonConvert.DeserializeObject <NavigationWidget[]>(navJson.Replace("$FRAMEWORK", "ASP.NET Core"))); }
public MainWindow() { InitializeComponent(); Closing += OnClosing; timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += TimerOnTick; try { string alltext = File.ReadAllText("settings.txt"); string[] keyAndSql = alltext.Split('|'); KeyText.Text = keyAndSql[0]; constr = keyAndSql[1]; } catch (Exception ex) { MessageBox.Show("Settings file not found or file is corrupted", "Alert", MessageBoxButton.OK, MessageBoxImage.Error); File.WriteAllText(DateTime.Now.ToString("dd.MM.yy hh.mm.ss") + " errorlog.txt", DateTime.Now + " -- " + "Settings file not found or file is corrupted"); Application.Current.Shutdown(); } bw = new BackgroundWorker(); bw.DoWork += bw_DoWork; if (KeyText.Text != "") { var text = @KeyText.Text; if (text != "" && bw.IsBusy != true) { bw.RunWorkerAsync(text); timer.Start(); autostart = true; } } }
private void _on_LoadSaveFile_Signed(string path) { var content = File.ReadAllText(path); GMRoot.runner = GMData.Run.Runner.Deserialize(content); GetTree().ChangeScene(MainScene.path); }
/// <summary> /// First param "_1" should be the filename of the JSON file containing the parameters and values /// </summary> /// <returns> /// JSON with parameters. /// JSON content sample: /// { "SquarePegSize": "0.24 in" } /// </returns> private static string GetParametersToChange(NameValueMap map, int index) { string paramFile = (string)map.Value[$"_{index}"]; string json = File.ReadAllText(paramFile); LogTrace("Inventor Parameters JSON: \"" + json + "\""); return(json); }
public StateFixture() { _rawState = File.ReadAllText($"{Environment.CurrentDirectory}\\Data\\terraform.tfstate"); _workspace = new Workspace { State = _rawState }; _state = _workspace.GetState(); _resources = _state.GetResources(); }
/// <summary> /// Проверяет наличие файлов с данными БД /// </summary> /// <param name="dataPath"> /// Путь до папки, где должеы лежать искомые файлы /// </param> /// <param name="isFilesEmpty"> /// true - если оба файла пустые, иначе false /// </param> private void CheckJSONFiles() { if (File.Exists(imagesFile) && File.Exists(objectClassesFile) && File.Exists(sessionsFile)) { //считываем из файликов данные Images = JsonConvert.DeserializeObject <List <Image> >(File.ReadAllText(imagesFile)); ObjectClasses = JsonConvert.DeserializeObject <List <ObjectClass> >(File.ReadAllText(objectClassesFile)); Sessions = JsonConvert.DeserializeObject <List <Session> >(File.ReadAllText(sessionsFile)); if (Images == null && (Sessions != null)) { throw new DatabaseException("Файл imagesData.json пуст!"); } else if (Images == null && ObjectClasses == null) { Images = new List <Image>(); ObjectClasses = new List <ObjectClass>(); } else if (Images != null && ObjectClasses == null) { ObjectClasses = new List <ObjectClass>(); } if (Sessions == null) { Sessions = new List <Session>(); } } else { //создаем недостающие файлы, оставляя их пустыми (!) if (!File.Exists(imagesFile)) { using (File.Create(imagesFile)) { } Images = new List <Image>(); } if (!File.Exists(objectClassesFile)) { using (File.Create(objectClassesFile)) { } ObjectClasses = new List <ObjectClass>(); } if (!File.Exists(sessionsFile)) { using (File.Create(sessionsFile)) { } Sessions = new List <Session>(); } } }
public static string Read(string filename) { try { // This appears to strip all carriage returns from the string! return(SysFile.ReadAllText(Config.DIR_CONTENT + filename).Replace("\r", "")); } catch { return(null); } }
public static IDictionary <string, NavigationWidget[]> SuiteWidgets(string suite) { var navigationJson = IOFile.ReadAllText( HttpContext.Current.Server.MapPath( string.Format(Config.SuiteNavigationData(suite)) ) ); return(Serializer.Deserialize <IDictionary <string, NavigationWidget[]> >(navigationJson)); }
private Settings GetSettings() { if (File.Exists(_pathInfo.SettingsFilePath)) { var json = File.ReadAllText(_pathInfo.SettingsFilePath); return(JsonConvert.DeserializeObject <Settings>(json)); } return(new Settings()); }
public static void ConfigureMicrosoft(this IModelApplication application) { var json = JsonConvert.DeserializeObject <dynamic>( File.ReadAllText($"{AppDomain.CurrentDomain.ApplicationPath()}\\MicrosoftAppCredentials.json")); IModelOAuthRedirectUri modelOAuth = application.ToReactiveModule <IModelReactiveModuleOffice>().Office.Microsoft().OAuth; modelOAuth.ClientId = json.MSClientId; modelOAuth.RedirectUri = json.RedirectUri; modelOAuth.ClientSecret = json.MSClientSecret; }
public void ParseDataDeliveryTest_ParseOk() { string path = FileLocator.FindFileInTree(@"Data\NatureArea\NiNCoreImportExample.xml"); string dataDeliveryXmlText = File.ReadAllText(path, Encoding.GetEncoding("iso-8859-1")); XDocument dataDeliveryXml = XDocument.Parse(dataDeliveryXmlText); Dataleveranse dataleveranse = DataleveranseParser.ParseDataleveranse(dataDeliveryXml); Assert.NotNull(dataleveranse); }
static ServiceProvider() { var setupInformation = System.AppDomain.CurrentDomain.SetupInformation; var credentialsPath = $@"{setupInformation.PrivateBinPath ?? setupInformation.ApplicationBase}\{AppCredentialsFile}"; var text = File.ReadAllText(credentialsPath); var settings = JsonConvert.DeserializeObject <dynamic>(text); ClientAppBuilder = PublicClientApplicationBuilder.Create($"{settings.ClientId}") .WithAuthority(AzureCloudInstance.AzurePublic, "common") .WithRedirectUri($"{settings.RedirectUrl}"); }
/// <summary> /// Creates an <see cref="Attachment" /> that contains an <see cref="AdaptiveCard" />. /// </summary> /// <param name="filePath">The path to the <see cref="AdaptiveCard" /> json file.</param> /// <returns>An <see cref="Attachment" /> that contains an adaptive card.</returns> private static Attachment CreateAdaptiveCardAttachment(string filePath) { var adaptiveCardJson = File.ReadAllText(filePath); var adaptiveCardAttachment = new Attachment { ContentType = "application/vnd.microsoft.card.adaptive", Content = JsonConvert.DeserializeObject(adaptiveCardJson) }; return(adaptiveCardAttachment); }
public override void RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; //convert variables var filePath = v_FilePath.ConvertUserVariableToString(engine); //read text from file var textFromFile = OBFile.ReadAllText(filePath); //assign text to user variable textFromFile.StoreInUserVariable(engine, v_OutputUserVariableName, nameof(v_OutputUserVariableName), this); }
public override void OnActionExecuting(ActionExecutingContext context) { ViewBag.svgsprite = FILE.ReadAllText(Startup.MapPath("~/img/svg/icon-sprites.svg")); ViewBag.auth_logged = Auth.IsLogged(context.HttpContext); if (ViewBag.auth_logged) { var user = Auth.LoggedUser(context.HttpContext, db); ViewBag.auth_name = user.nome; } base.OnActionExecuting(context); }
public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; //convert variables var filePath = (string)await v_FilePath.EvaluateCode(engine); //read text from file var textFromFile = OBFile.ReadAllText(filePath); //assign text to user variable textFromFile.SetVariableValue(engine, v_OutputUserVariableName); }