Ejemplo n.º 1
0
        private void AddPage(object sender, RoutedEventArgs e)
        {
            BookPage p   = new BookPage();
            int      idx = pageList.Children.Count;

            pageList.Children.Insert(idx - 1, p);
            if (idx < 10)
            {
                p.pageIdx.Text = string.Format("第0{0}页", idx);
            }
            else
            {
                p.pageIdx.Text = string.Format("第{0}页", idx);
            }
            if (pageList.Children.Count == 51)
            {
                newPage.IsEnabled = false;
            }
            JsonEditor doc = p.doc;

            doc.Bold           = bold;
            doc.Italic         = italic;
            doc.Underlined     = underlined;
            doc.Strikethrough  = strikethrough;
            doc.Obfuscated     = obfuscated;
            doc.ColorPicker    = TextColor;
            doc.Window         = (CmdGenerator.Parent as ContentControl).Parent as IMtbWindow;
            doc.EntitySelector = ES;
            doc.InitializeSettings(clearStyle, c, addSelector, addObjective, addEvent, TextColor, doc.Foreground);
            doc.GotFocus += FocusedChanged;
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                throw new ArgumentNullException("root path is expexted");
            }

            var rootPath = args[0];
            IDictionary <FileType, string> filesPath = new Dictionary <FileType, string>()
            {
                { FileType.Config, $"{rootPath}config.json" },
                { FileType.Launch, $"{rootPath}launch.json" },
                { FileType.Task, $"{rootPath}tasks.json" }
            };
            JsonEditor jsonEditor = new JsonEditor(filesPath);

            var config         = jsonEditor.GetConfig();
            var activeSolution = jsonEditor.GetActiveConfiguration();
            var jsonLanuch     = jsonEditor.LoadLunchJson();
            var jsonTask       = jsonEditor.LoadTaskJson();

            jsonLanuch.SetupConfiguration(config, activeSolution);
            jsonTask.SetupConfiguration(config, activeSolution);

            jsonEditor.Update <JsonLaunch>(jsonLanuch);
            jsonEditor.Update <JsonTask>(jsonTask);
        }
Ejemplo n.º 3
0
        public int Execute()
        {
            string result = JsonEditor.GetValue(Path, Key);

            System.Console.Write(result);
            return(0);
        }
Ejemplo n.º 4
0
        public void ShouldReturn_ActiveConfiguration()
        {
            var      jsonEditor     = new JsonEditor(filesPath);
            Solution activeSolution = jsonEditor.GetActiveConfiguration();

            Assert.AreEqual("serializacja", activeSolution.Key);
        }
Ejemplo n.º 5
0
        public async Task AddAndSelectRuleLevel(string bicepConfigFilePath, string ruleCode)
        {
            if (await SelectRuleLevelIfExists(ruleCode, bicepConfigFilePath))
            {
                // The rule already exists and has been shown/selected
                return;
            }

            string json = File.ReadAllText(bicepConfigFilePath);

            (int line, int column, string text)? insertion = new JsonEditor(json).InsertIfNotExist(
                new string[] { "analyzers", "core", "rules", ruleCode },
                new { level = "warning" });

            if (insertion.HasValue)
            {
                var(line, column, insertText) = insertion.Value;
                try
                {
                    File.WriteAllText(bicepConfigFilePath, JsonEditor.ApplyInsertion(json, (line, column, insertText)));
                }
                catch (Exception ex)
                {
                    server.Window.ShowError($"Unable to write to configuration file \"{bicepConfigFilePath}\": {ex.Message}");
                }

                await SelectRuleLevelIfExists(ruleCode, bicepConfigFilePath);
            }
        }
Ejemplo n.º 6
0
        private void InitializeWithPopulatedJson()
        {
            _PathToSampleConfigFile = CreateSampleJsonConfigFile();

            Console.WriteLine(_PathToSampleConfigFile);

            _SystemUnderTest = new JsonEditor(_PathToSampleConfigFile);
        }
Ejemplo n.º 7
0
 public ManageController(ApplicationDbContext dbContext,
                         ILogger <ManageController> logger,
                         UserManager <User> userManager)
 {
     _manage     = new Manage(new DbManage(dbContext, logger), new JsonEditor(logger), logger, userManager);
     _jsonEditor = new JsonEditor(logger);
     _logger     = logger;
 }
Ejemplo n.º 8
0
        public int Execute()
        {
            if (!File.Exists(SourceFile))
            {
                File.WriteAllText(SourceFile, "{}");
            }

            JsonEditor.SetProperty(SourceFile, Key, Value);
            return(0);
        }
        public ScheduleController(ApplicationDbContext dbContext, UserManager <User> userManager,
                                  ILogger <ScheduleController> logger)
        {
            var dbAgenda   = new DbAgenda(dbContext, logger);
            var jsonEditor = new JsonEditor(logger);

            _agenda      = new Agenda(dbAgenda, jsonEditor, logger);
            _userManager = userManager;
            _logger      = logger;
        }
 public AuthenticationController(
     UserManager <User> userManager,
     SignInManager <User> signInManager,
     RoleManager <IdentityRole> roleManager,
     ApplicationDbContext dbContext,
     ILogger <AuthenticationController> logger)
 {
     _authentication = new Authentication(userManager, signInManager, roleManager, dbContext, logger);
     _json           = new JsonEditor(logger);
     _logger         = logger;
 }
Ejemplo n.º 11
0
        private void FromClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedModViewer.IsVanilla)
            {
                return;
            }
            if (!Clipboard.ContainsText())
            {
                return;
            }

            JsonEditor je = new JsonEditor(Clipboard.GetText());

            if (je.ShowDialog() == DialogResult.OK)
            {
                switch (je.ObjectType)
                {
                case "Aspect":
                    FromClipboardOnOkay(selectedModViewer.Content.Aspects, je.ObjectText);
                    break;

                case "Element":
                    FromClipboardOnOkay(selectedModViewer.Content.Elements, je.ObjectText);
                    break;

                case "Recipe":
                    FromClipboardOnOkay(selectedModViewer.Content.Recipes, je.ObjectText);
                    break;

                case "Deck":
                    FromClipboardOnOkay(selectedModViewer.Content.Decks, je.ObjectText);
                    break;

                case "Legacy":
                    FromClipboardOnOkay(selectedModViewer.Content.Legacies, je.ObjectText);
                    break;

                case "Ending":
                    FromClipboardOnOkay(selectedModViewer.Content.Endings, je.ObjectText);
                    break;

                case "Verb":
                    FromClipboardOnOkay(selectedModViewer.Content.Verbs, je.ObjectText);
                    break;

                default:
                    MessageBox.Show("I'm not sure what you selected or how, but that was an invalid choice.", "Unknown Object Type", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                selectedModViewer.MarkDirty();
            }
        }
        private string GetClaimValue(JsonEditor editor, string claimName)
        {
            var args = new SiblingValueArguments();

            args.SiblingSearchKey   = "typ";
            args.SiblingSearchValue = claimName;

            args.DesiredNodeKey = "val";
            args.PathArguments  = new[] { "user_claims" };

            var temp = editor.GetSiblingValue(args);

            return(temp);
        }
        private bool AddClaimIfExists(List <Claim> claims, JsonEditor editor, string claimTypeName)
        {
            var temp = GetClaimValue(editor, claimTypeName);

            if (temp.IsNullOrWhitespace() == false)
            {
                AddClaim(claims, claimTypeName, temp);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            JsonEditor = await _context.JsonEditor.FirstOrDefaultAsync(m => m.Id == id);

            if (JsonEditor == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Ejemplo n.º 15
0
        public bool Execute()
        {
            const string fullPath = "FullPath";
            string       src      = SourceFile.GetMetadata(fullPath);
            string       dest     = (DestinationFile?.GetMetadata(fullPath) ?? Path.Combine(Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode), "appsettings.json"));

            foreach (string path in JPath.Split(new char[] { ';', ',' }, System.StringSplitOptions.RemoveEmptyEntries))
            {
                JsonEditor.CopyProperty(src, dest, path);
                BuildEngine.LogMessageEvent(new BuildMessageEventArgs(
                                                $"Copied  '{Path.GetFileName(src)}':'{path}' property to '{Path.GetFileName(dest)}'", null, nameof(CopyJsonProperties), MessageImportance.Normal));
            }

            return(true);
        }
Ejemplo n.º 16
0
 public Sign(CommandsGeneratorTemplate tmp)
 {
     InitializeComponent();
     CmdGenerator         = tmp;
     line1.Bold           = bold;
     line1.Italic         = italic;
     line1.Underlined     = underlined;
     line1.Strikethrough  = strikethrough;
     line1.Obfuscated     = obfuscated;
     line1.ColorPicker    = TextColor;
     line1.Window         = (tmp.Parent as ContentControl).Parent as IMtbWindow;
     line1.EntitySelector = ES;
     line1.InitializeSettings(clearStyle, c, null, null, null, TextColor, line1.Foreground);
     line2.Bold           = bold;
     line2.Italic         = italic;
     line2.Underlined     = underlined;
     line2.Strikethrough  = strikethrough;
     line2.Obfuscated     = obfuscated;
     line2.ColorPicker    = TextColor;
     line2.Window         = (tmp.Parent as ContentControl).Parent as IMtbWindow;
     line2.EntitySelector = ES;
     line2.InitializeSettings(clearStyle, c, null, null, null, TextColor, line2.Foreground);
     line3.Bold           = bold;
     line3.Italic         = italic;
     line3.Underlined     = underlined;
     line3.Strikethrough  = strikethrough;
     line3.Obfuscated     = obfuscated;
     line3.ColorPicker    = TextColor;
     line3.Window         = (tmp.Parent as ContentControl).Parent as IMtbWindow;
     line3.EntitySelector = ES;
     line3.InitializeSettings(clearStyle, c, null, null, null, TextColor, line3.Foreground);
     line4.Bold           = bold;
     line4.Italic         = italic;
     line4.Underlined     = underlined;
     line4.Strikethrough  = strikethrough;
     line4.Obfuscated     = obfuscated;
     line4.ColorPicker    = TextColor;
     line4.Window         = (tmp.Parent as ContentControl).Parent as IMtbWindow;
     line4.EntitySelector = ES;
     line4.InitializeSettings(clearStyle, c, null, null, null, TextColor, line4.Foreground);
     EditingCommands.AlignCenter.Execute(null, line1);
     EditingCommands.AlignCenter.Execute(null, line2);
     EditingCommands.AlignCenter.Execute(null, line3);
     EditingCommands.AlignCenter.Execute(null, line4);
     editing             = line1;
     addSelector.Click  += AddSelector_Click;
     addObjective.Click += AddObjective_Click;
 }
        /// <summary>
        /// On the "JSON" button click, this method opens a JSON editor that allows the user to modify JSON data in the action variable.
        /// </summary>
        private void jsonEditButton_Click(object sender, EventArgs e)
        {
            string json = JsonConvert.SerializeObject(action, ConfigManager.JsonSettings);

            je          = new JsonEditor();
            je.Closing += (o, args) =>
            {
                action = JsonConvert.DeserializeObject(je.GetEditorText(), ConfigManager.JsonSettings);
                BindActionToUi();
                SetEnableModifications(true);
            };

            SetEnableModifications(false);
            je.SetEditorText(json);
            je.Show();
        }
Ejemplo n.º 18
0
        public void Can_get_json_value()
        {
            // Arrange
            var sourceFile = TestData.GetFile("config1.json");

            // Act
            var result1 = JsonEditor.GetValue(sourceFile, "nugetKey");
            var result2 = JsonEditor.GetValue(sourceFile, "local:datastore:auth");
            var result3 = JsonEditor.GetValue(sourceFile, "local:datastore:main");
            var result4 = JsonEditor.GetValue(sourceFile, "invaild");

            // Assert
            result1.ShouldNotBeNullOrEmpty();
            result2.ShouldNotBeNullOrEmpty();
            result3.ShouldNotBeNullOrEmpty();
            result4.ShouldBeNullOrEmpty();
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            JsonEditor = await _context.JsonEditor.FindAsync(id);

            if (JsonEditor != null)
            {
                _context.JsonEditor.Remove(JsonEditor);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Ejemplo n.º 20
0
        public Book(CommandsGeneratorTemplate cmdGenerator)
        {
            InitializeComponent();
            CmdGenerator = cmdGenerator;
            JsonEditor doc = Page1.doc;

            doc.Bold           = bold;
            doc.Italic         = italic;
            doc.Underlined     = underlined;
            doc.Strikethrough  = strikethrough;
            doc.Obfuscated     = obfuscated;
            doc.ColorPicker    = TextColor;
            doc.Window         = (cmdGenerator.Parent as ContentControl).Parent as IMtbWindow;
            doc.EntitySelector = ES;
            doc.InitializeSettings(clearStyle, c, addSelector, addObjective, addEvent, TextColor, doc.Foreground);
            Page1.doc.GotFocus += FocusedChanged;
            editing             = Page1.doc;
        }
Ejemplo n.º 21
0
        public void SetJsonValueUsingOneLevelOfElement()
        {
            string expectedValue = "new-value";

            Args = CreateArgsArray(
                CommandNameArgument,
                GetArgEntry(Constants.ArgumentNameConfigFilename, _PathToSampleConfigFile),
                GetArgEntry(Constants.ArgumentNameLevel1, "FirstLevel"),
                GetArgEntry(Constants.ArgumentNameAttributeName, "processPath"),
                GetArgEntry(Constants.ArgumentNameValue, expectedValue));

            SystemUnderTest.Run();

            var editor = new JsonEditor(_PathToSampleConfigFile);

            var actual = editor.GetValue(
                "FirstLevel");

            Assert.AreEqual <string>(expectedValue, actual, "Result was wrong.");
        }
Ejemplo n.º 22
0
        public void Can_copy_json_property(string jpath)
        {
            // Arrange
            string sourceFilePath = TestData.GetFile("config1.json");
            string resultFilePath = Path.Combine(_currentWorkingDirectory, $"cecret-copy-test.{jpath}.json".Replace('*', '_'));

            using var approver = ApprovalTests.Namers.ApprovalResults.ForScenario(jpath);

            // Act
            if (File.Exists(resultFilePath))
            {
                File.Delete(resultFilePath);
            }
            JsonEditor.CopyProperty(sourceFilePath, resultFilePath, jpath);
            JsonEditor.CopyProperty(sourceFilePath, resultFilePath, jpath);

            // Assert
            File.Exists(resultFilePath).ShouldBeTrue();
            Approvals.Verify(File.ReadAllText(resultFilePath));
        }
Ejemplo n.º 23
0
        public void SetJsonValueUsingTwoLevelsOfElement()
        {
            string expectedValue = "new-value";

            Args = CreateArgsArray(
                CommandNameArgument,
                GetArgEntry(Constants.ArgumentNameConfigFilename, _PathToSampleConfigFile),
                GetArgEntry(Constants.ArgumentNameLevel1, "ConnectionStrings"),
                GetArgEntry(Constants.ArgumentNameLevel2, "DefaultConnectionString"),
                GetArgEntry(Constants.ArgumentNameValue, expectedValue));

            SystemUnderTest.Run();

            var editor = new JsonEditor(_PathToSampleConfigFile);

            var actual = editor.GetValue(
                "ConnectionStrings", "DefaultConnectionString");

            Assert.AreEqual <string>(expectedValue, actual, "Result was wrong.");
        }
Ejemplo n.º 24
0
        private void TestInsertion(string beforeText, string insertionPath, object insertionValue, string?afterText)
        {
            (int line, int column, string text)? insertion =
                new JsonEditor(beforeText).
                InsertIfNotExist(
                    insertionPath.Split('.').Where(p => p.Length > 0).ToArray(),
                    insertionValue);
            if (afterText is null)
            {
                insertion.Should().BeNull();
            }
            else
            {
                insertion.Should().NotBeNull();
                var newText = JsonEditor.ApplyInsertion(beforeText, insertion !.Value);

                newText   = newText.Replace("\r\n", "\n");
                afterText = afterText.Replace("\r\n", "\n");
                newText.Should().Be(afterText);
            }
        }
Ejemplo n.º 25
0
        public void Can_set_json_property(string[] keys)
        {
            // Arrange
            using var approver = ApprovalTests.Namers.ApprovalResults.ForScenario(string.Join("__", keys));
            var line = string.Concat(Enumerable.Repeat('-', 50));

            var sourceFile = Path.Combine(_currentWorkingDirectory, $"secrets-set-test({string.Join(" ", keys)}).json");

            // Act
            foreach (var item in keys)
            {
                JsonEditor.SetProperty(sourceFile, item, 123);

                System.Diagnostics.Debug.WriteLine($"arg: {item}");
                var result = File.ReadAllText(sourceFile);
                System.Diagnostics.Debug.WriteLine(result);
                System.Diagnostics.Debug.WriteLine(line);
                System.Diagnostics.Debug.WriteLine(string.Empty);
                System.Diagnostics.Debug.WriteLine(string.Empty);
            }

            // Assert
            Approvals.VerifyFile(sourceFile);
        }
        private void AddClaimsFromAuthMeService(
            HttpContext context, List <Claim> claims)
        {
            if (context.Request.Cookies.ContainsKey(SecurityConstants.Cookie_AppServiceAuthSession) == true)
            {
                var authMeJson = GetAuthMeInfo(context.Request);

                var jsonArray = JArray.Parse(authMeJson);

                var editor = new JsonEditor(jsonArray[0].ToString(), true);

                AddClaimIfExists(claims, editor, ClaimTypes.GivenName);
                AddClaimIfExists(claims, editor, ClaimTypes.Surname);
                if (AddClaimIfExists(claims, editor, ClaimTypes.Email) == false)
                {
                    var temp = editor.GetValue("user_id");

                    if (temp.IsNullOrWhitespace() == false)
                    {
                        claims.Add(new Claim(ClaimTypes.Email, temp));
                    }
                }
            }
        }
Ejemplo n.º 27
0
 public JsonTest()
 {
     _json = new JsonEditor();
 }
Ejemplo n.º 28
0
 private void FocusedChanged(object sender, RoutedEventArgs e)
 {
     editing.Selection.Select(editing.Document.ContentEnd, editing.Document.ContentEnd);
     editing = sender as JsonEditor;
 }
Ejemplo n.º 29
0
        private void InitializeWithEmptyJson()
        {
            _PathToSampleConfigFile = CreateSampleJsonConfigFileEmpty();

            _SystemUnderTest = new JsonEditor(_PathToSampleConfigFile);
        }
Ejemplo n.º 30
0
        // Per documentation here- https://docs.microsoft.com/en-us/azure/azure-resource-manager/bicep/parameter-files
        // parameters file should be of below format:
        //{
        //  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
        //  "contentVersion": "1.0.0.0",
        //  "parameters": {
        //    "<first-parameter-name>": {
        //      "value": "<first-value>"
        //    },
        //    "<second-parameter-name>": {
        //      "value": "<second-value>"
        //    }
        //  }
        //}
        // However, azure-sdk-for-net expects parameters to be of name and value pairs:
        // https://github.com/Azure/azure-sdk-for-net/blob/1e25b1bfc9b54df35d907aa7b2c10ff07082e845/sdk/resources/Azure.ResourceManager.Resources/src/Generated/Models/ArmDeploymentProperties.cs#L27
        // We'll work around the above issue by first detecting the format of the file.
        // If it's in the format descibed in the docs, we'll extract the parameters value and use that for actual deployment.
        // If the user chose to create a new parameters file during the deployment flow, we'll follow the format
        // mentioned in the docs as a best practise.
        public static string GetUpdatedParametersFileContents(
            string documentPath,
            string parametersFileName,
            string parametersFilePath,
            ParametersFileUpdateOption updateOrCreateParametersFile,
            IEnumerable <BicepUpdatedDeploymentParameter> updatedDeploymentParameters)
        {
            try
            {
                // Parameter file follows format mentioned here: https://docs.microsoft.com/en-us/azure/azure-resource-manager/bicep/parameter-files
                var armSchemaStyleParametersFile = @"{
  ""$schema"": ""https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#"",
  ""contentVersion"": ""1.0.0.0"",
  ""parameters"": {
  }
}";
                // We will send across the secure param values to the azure sdk that handles deployment,
                // but will avoid writing it to the parameters file for security reasons
                var updatedParametersFile = !string.IsNullOrWhiteSpace(parametersFilePath) ?
                                            File.ReadAllText(parametersFilePath) : armSchemaStyleParametersFile;
                var updatedParametersFileWithoutSecureParams = updatedParametersFile;

                var jObject = GetParametersObjectValue(updatedParametersFile, out bool isArmStyleTemplate);

                foreach (var updatedDeploymentParameter in updatedDeploymentParameters.Reverse())
                {
                    var name = updatedDeploymentParameter.name;

                    // Check to make sure parameters mentioned in parameters file are not overwritten
                    if (jObject.ContainsKey(name))
                    {
                        continue;
                    }
                    else
                    {
                        var jsonEditor = new JsonEditor(updatedParametersFile);

                        var propertyPaths = new List <string>();
                        if (isArmStyleTemplate)
                        {
                            propertyPaths.Add("parameters");
                            propertyPaths.Add(name);
                        }
                        else
                        {
                            propertyPaths.Add(name);
                        }

                        var valueObject = UpdateJObjectBasedOnParameterType(
                            updatedDeploymentParameter.parameterType,
                            updatedDeploymentParameter.value,
                            JObject.Parse("{}"));

                        (int line, int column, string text)? insertion = jsonEditor.InsertIfNotExist(propertyPaths.ToArray(), valueObject);

                        if (insertion.HasValue)
                        {
                            var(line, column, insertText) = insertion.Value;

                            updatedParametersFile = JsonEditor.ApplyInsertion(updatedParametersFile, (line, column, insertText));

                            if (!updatedDeploymentParameter.isSecure)
                            {
                                updatedParametersFileWithoutSecureParams = JsonEditor.ApplyInsertion(updatedParametersFileWithoutSecureParams, (line, column, insertText));
                            }
                        }
                    }
                }

                if (updatedDeploymentParameters.Any())
                {
                    if (updateOrCreateParametersFile == ParametersFileUpdateOption.Update)
                    {
                        File.WriteAllText(parametersFilePath, updatedParametersFileWithoutSecureParams);
                    }
                    // ParametersFileCreateOrUpdate will have a value of "Overwrite" only if the parameters
                    // file with name <bicep_file_name>.parameters.json already exists and user chose to
                    // overwrite it with values from this deployment
                    else if (updateOrCreateParametersFile == ParametersFileUpdateOption.Create ||
                             updateOrCreateParametersFile == ParametersFileUpdateOption.Overwrite)
                    {
                        var directoryContainingBicepFile = Path.GetDirectoryName(documentPath);
                        if (directoryContainingBicepFile is not null)
                        {
                            File.WriteAllText(Path.Combine(directoryContainingBicepFile, parametersFileName), updatedParametersFileWithoutSecureParams);
                        }
                    }
                }

                var updatedJObject = GetParametersObjectValue(updatedParametersFile, out _);

                return(updatedJObject.ToString());
            }
            catch (Exception e)
            {
                throw new Exception(string.Format(LangServerResources.InvalidParameterFileDeploymentFailedMessage, documentPath, parametersFilePath, e.Message));
            }
        }