private int ExecuteTestCase(string jsonName) { JsonTemplate jsonFile = _service.ParseJsonFileIntoObjects(jsonName); List <Campsite> availableCampsites = _service.FindAvailableCampsites(jsonFile); return(availableCampsites.Count); }
/// <inheritdoc/> public async Task <(string RelativePath, string JsonSchema)> CreateSchemaFromTemplate(string org, string repository, string developer, string schemaName, string relativeDirectory = "", bool altinn2Compatible = false) { var altinnGitRepository = _altinnGitRepositoryFactory.GetAltinnGitRepository(org, repository, developer); // In case of null being passed in we default it to an empty string as the default value // on the parameter does not apply if null is actually passed in. relativeDirectory ??= string.Empty; if (await altinnGitRepository.GetRepositoryType() == AltinnRepositoryType.Datamodels) { var uri = GetSchemaUri(org, repository, schemaName, relativeDirectory); JsonTemplate jsonTemplate = altinn2Compatible ? new SeresJsonTemplate(uri, schemaName) : new GeneralJsonTemplate(uri, schemaName); var jsonSchema = jsonTemplate.GetJsonString(); var relativeFilePath = Path.ChangeExtension(Path.Combine(relativeDirectory, schemaName), ".schema.json"); await altinnGitRepository.WriteTextByRelativePathAsync(relativeFilePath, jsonSchema, true); return(relativeFilePath, jsonSchema); } else { var altinnAppGitRepository = _altinnGitRepositoryFactory.GetAltinnAppGitRepository(org, repository, developer); var modelFolder = altinnAppGitRepository.GetRelativeModelFolder(); var uri = GetSchemaUri(org, repository, schemaName, modelFolder); JsonTemplate jsonTemplate = altinn2Compatible ? new SeresJsonTemplate(uri, schemaName) : new GeneralJsonTemplate(uri, schemaName); var jsonSchema = jsonTemplate.GetJsonString(); var relativePath = await altinnAppGitRepository.SaveJsonSchema(jsonSchema, schemaName); return(relativePath, jsonSchema); } }
public static bool TryParse(string json, out JsonTemplate value, out string error, out Position errorPosition) { var tokens = JsonTemplateTokenizer.Instance.TryTokenize(json); if (!tokens.HasValue) { value = null; error = tokens.ToString(); errorPosition = tokens.ErrorPosition; return(false); } var parsed = JsonTemplate.TryParse(tokens.Value); if (!parsed.HasValue) { value = null; error = parsed.ToString(); errorPosition = parsed.ErrorPosition; return(false); } value = parsed.Value; error = null; errorPosition = Position.Empty; return(true); }
public string ToJson() { return(JsonTemplate.FillTemplate(JSONTemplate, new Dictionary <string, string>() { { "@id", JsonLdId.ToString() }, { "nodeGraph", SerializeNodeTreeRecursive(Node).Replace("'", "\"") }, })); }
public void AdaptiveCard() { JsonTemplate cardTemplate = new JsonTemplate(File.ReadAllText(@"..\..\cardTemplate.json")); var cardData = JsonConvert.DeserializeObject(File.ReadAllText(@"..\..\cardData.json")); var result = cardTemplate.Bind(cardData); Debug.Print(JsonConvert.SerializeObject(result, Formatting.Indented)); }
public static bool TryEvaluate( JsonTemplate template, IReadOnlyDictionary <string, JsonTemplateFunction> functions, out JsonTemplate result, out string error) { (result, error) = Evaluate(template, functions); return(error == null); }
private static void TestValueProperty <T>(T value) { dynamic source = new JObject(); source.value = value; JsonTemplate valueTemplate = new JsonTemplate(@"{ 'prop':'{=value}'}"); dynamic result = valueTemplate.Bind(source); Assert.AreEqual((T)result.prop, value); }
public void ValueComplexStringWithArray() { dynamic source = new JObject(); source.items = new JArray(new[] { 1, 2, 3, 4 }); JsonTemplate valueTemplate = new JsonTemplate(@"{'prop':'result:{items}.'}"); dynamic result = valueTemplate.Bind(source); Assert.AreEqual("result:1, 2, 3, 4.", (string)result.prop); }
/// <summary> /// Execute the base case comparison for each provided gap rule. /// Use && because the new reservation must fit for all provided gap rules. /// If it fails for one gap rule, logical operator will return false for the entire set of gap rules. /// </summary> /// <param name="inputSearch">The potential new reservation date range.</param> /// <param name="existingReservation">The reservation we are comparing the input date range against.</param> /// <param name="gapRules">List of all provided gap rules.</param> /// <returns>bool indicating if a new reservation will fit before or after a single existing reservation for all given gap rules.</returns> public bool CompareInputRangeToReservationForEachGap(JsonTemplate inputJson, Reservation existingReservation) { var canFit = true; foreach (var gap in inputJson.GapRules) { canFit = BaseCaseCompareInputRangeToReservation(inputJson.Search, existingReservation, gap) && canFit; } return(canFit); }
public void Join() { dynamic source = new JObject(); source.items = new JArray(new[] { 1, 2, 3, 4 }); JsonTemplate valueTemplate = new JsonTemplate(@"{'template':{'prop':'{items}'}}"); dynamic result = valueTemplate.Bind(source); Assert.AreEqual("1, 2, 3, 4", (string)result.prop); }
/// <summary> /// Iterate through each existing reservation and feed to base case comparison methods. /// If the new reservation will not fit with one existing reservation, returns false. /// </summary> /// <param name="inputJson">Input test object.</param> /// <param name="tmpCampSite">The current campsite we are trying to insert the new reservation into.</param> /// <returns>bool indicating if a new reservation will fit between all existing reservation for all given gap rules.</returns> public bool CompareCampsiteReservations(JsonTemplate inputJson, Campsite tmpCampSite) { var canFit = true; foreach (var res in tmpCampSite.CampsiteReservationList) { canFit = CompareInputRangeToReservationForEachGap(inputJson, res) && canFit; } return(canFit); }
static (JsonTemplate, string) Evaluate(JsonTemplate template, IReadOnlyDictionary <string, JsonTemplateFunction> functions) { return(template switch { JsonTemplateArray a => EvaluateArray(a, functions), JsonTemplateObject o => EvaluateObject(o, functions), JsonTemplateCall c => EvaluateCall(c, functions), { } other => (other, null), null => throw new ArgumentNullException(nameof(template)) });
public void ValueComplexString() { dynamic source = new JObject(); source.value1 = "value1"; source.value2 = 2; JsonTemplate valueTemplate = new JsonTemplate(@"{'prop':'One:{value1} Two:{value2}'}"); dynamic result = valueTemplate.Bind(source); Assert.AreEqual("One:value1 Two:2", (string)result.prop); }
public void Initialize() { this.sourceJson = File.ReadAllText(@"..\..\Data.Json"); this.source = (JObject)JsonConvert.DeserializeObject(sourceJson); this.sourcePoco = JsonConvert.DeserializeObject <Source.Rootobject>(this.sourceJson); this.expectedJson = File.ReadAllText(@"..\..\expected.json"); this.expected = (JObject)JsonConvert.DeserializeObject(expectedJson); this.expectedPoco = JsonConvert.DeserializeObject <Expected.Rootobject>(this.expectedJson); complexTemplate = new JsonTemplate(File.ReadAllText(@"..\..\template.json")); }
/// <summary> /// Iterate through campsites, if all base comparisons return true then campsite is valid for new reservation. /// </summary> /// <param name="inputJson">Input test object.</param> /// <returns>List of campsites that can host the new reservation without violating a gap rule.</returns> public List <Campsite> FindAvailableCampsites(JsonTemplate inputJson) { List <Campsite> availableCampsites = new List <Campsite>(); foreach (Campsite tmpCampSite in inputJson.Campsites) { if (CompareCampsiteReservations(inputJson, tmpCampSite)) { availableCampsites.Add(tmpCampSite); } } return(availableCampsites); }
private static void PropertyTestArray <T>(T[] val) { dynamic source = new JObject(); source.value = new JArray(val); JsonTemplate valueTemplate = new JsonTemplate(@"{ 'prop':'{=value}'}"); dynamic result = valueTemplate.Bind(source); Assert.AreEqual(result.prop.Type, JTokenType.Array); for (int i = 0; i < val.Length; i++) { Assert.AreEqual((T)result.prop[i], val[i]); } }
private JsonTemplateResult GetTestResults(string fileName, int Id) { var path = System.Web.HttpContext.Current.Server.MapPath(@"~/Content/"); JsonTemplate jsonFile = _gapRuleService.ParseJsonFileIntoObjects(fileName); List <Campsite> availableCampsites = _gapRuleService.FindAvailableCampsites(jsonFile); JsonTemplateResult result = new JsonTemplateResult { ExecutionTemplate = jsonFile, TestCaseName = fileName, Id = Id, ResultingCampsites = availableCampsites }; return(result); }
/// <summary> /// Add a list of reservations to each campsite. /// This makes it easier to keep track of campsites when traversing through reservations. /// </summary> /// <param name="inputJson">input test object.</param> private void BuildCampsiteReservationList(JsonTemplate inputJson) { foreach (var res in inputJson.Reservations) { try { Campsite tmpCampSite = inputJson.Campsites.Where(x => x.Id == res.CampsiteId).First(); tmpCampSite.CampsiteReservationList.Add(res); } catch (Exception ex) { //couldn't find that campsite ID in our list of campsites throw new Exception("Invalid Campsite ID provided with reservation. " + ex.Message); } } }
public string ToJson() { return(JsonTemplate.FillTemplate(JSONTemplate, new Dictionary <string, string>() { { "id", JsonLdId.ToString() }, { "authorJSON", JsonUtility.ToJson(Author) }, { "createdTimestamp", CreatedAt.ToString() }, { "annotationText", Text }, { "targetID", Target.JsonLdId.ToString() }, { "targetNodeName", TargetNode.Name }, { "simulatedDate", AnnotationManager.Instance.SimulatedYear }, { "simulatedTimeofDay", AnnotationManager.Instance.SimulatedTimeOfDay }, { "guidPath", TargetNode.GuidPath }, { "annotationPosition", JsonUtility.ToJson(AnnotationPosition) }, { "viewPortPosition", JsonUtility.ToJson(ViewPortPosition) }, })); }
public static object Convert(JsonTemplate template) { if (template == null) { throw new ArgumentNullException(nameof(template)); } return(template switch { JsonTemplateNull _ => null, JsonTemplateBoolean b => b.Value, JsonTemplateNumber n => ConvertNumber(n), JsonTemplateString s => s.Value, JsonTemplateArray a => ConvertArray(a), JsonTemplateObject o => ConvertObject(o), JsonTemplateCall c => throw new ArgumentException($"The call `{c.Name}` was not evaluated."), _ => throw new ArgumentOutOfRangeException(nameof(template)), });
public void Join() { dynamic source = new JObject(); source.items = new JArray(new[] { 1, 2, 3, 4 }); JsonTemplate valueTemplate = new JsonTemplate(@"{'prop':'{items}'}"); dynamic result = valueTemplate.Bind(source); Assert.AreEqual("1, 2, 3, 4", (string)result.prop); //valueTemplate = new JsonTemplate(@"{'template':{'prop':'{join(items ~sep=_)}'}}"); //result = valueTemplate.Bind(source); //Assert.AreEqual("1_2_3 and 4", (string)result.prop); //valueTemplate = new JsonTemplate(@"{'template':{'prop':'{join(items ~sep=_~last= or )}'}}"); //result = valueTemplate.Bind(source); //Assert.AreEqual("1_2_3 or 4", (string)result.prop); }
public HttpResponseMessage EmailTeste() { try { var template = _service.GetTemplateByIdentifier("AGENDAMENTO_ONLINE"); if (template == null) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Não foi possivel recuperar o Templete de e-mail.")); } var obj = new JsonTemplate() { SUBJECT = new JsonTemplateSubject() { PROTOCOLO = "12346789" }, BODY = new JsonTemplateBody() { PACIENTE = "RENATO AYRES", CLINICA = "CLINICA TESTE", DATA_HORA = DateTime.Now.ToShortDateString() + " - " + DateTime.Now.ToShortTimeString(), TELEFONE = "(31) 3355-6688", PROTOCOLO = "12346789", } }; var json = new JavaScriptSerializer().Serialize(obj); _service.AddToQueue(new MailQueue(template, "*****@*****.**", json)); _service.AddToQueue(new MailQueue(template, "*****@*****.**", json)); _service.ProcessQueue(); return(Request.CreateResponse(HttpStatusCode.OK)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
public IActionResult AddProperty(EditServiceJsonViewModel viewModel) { var crossActionData = Models.EditServiceJson.CreateFrom(viewModel); var originalTemplate = JsonConvert.DeserializeObject <Models.JsonTemplate>(viewModel.CurrentJson); if (originalTemplate.ValueType != Models.ValueType.Object) { originalTemplate = new JsonTemplate(); originalTemplate.ValueType = Models.ValueType.Object; } originalTemplate.IsArray = viewModel.CurrentTemplate.IsArray; if (string.IsNullOrWhiteSpace(viewModel.NewPropertyName)) { crossActionData.ErrorMessage = "必须为JSON成员指定有效的属性名称"; } else { var duplics = from key in originalTemplate.ObjectProperties.Keys where key.Equals(viewModel.NewPropertyName.Trim(), StringComparison.OrdinalIgnoreCase) select key; if (duplics.Count() > 0) { crossActionData.ErrorMessage = "当前JSON对象已经包含了同名成员,属性名称是大小写不敏感的"; } } if (string.IsNullOrWhiteSpace(crossActionData.ErrorMessage)) { var newProperty = new JsonTemplate(); newProperty.ValueType = viewModel.NewPropertyValue; newProperty.IsArray = viewModel.NewPropertyIsArray; originalTemplate.ObjectProperties.Add(viewModel.NewPropertyName, newProperty); } crossActionData.CurrentJson = JsonConvert.SerializeObject(originalTemplate); TempData.Put(EDIT_JSON_CROSS_ACTION_DATA_KEY, crossActionData); return(RedirectToAction(nameof(EditServiceJson))); }
/// <summary> /// Get all json files from Content directory and prepare them to be executed. /// </summary> /// <returns>List containing templat of each json file.</returns> private List <JsonTemplateResult> GetTestTemplates(bool executeTests = false) { var path = System.Web.HttpContext.Current.Server.MapPath(@"~/Content/"); DirectoryInfo d = new DirectoryInfo(path); int i = 0; var returnResultList = new List <JsonTemplateResult>(); foreach (var file in d.GetFiles("*.json")) { i += 1; JsonTemplate jsonFile = _gapRuleService.ParseJsonFileIntoObjects(file.Name); List <Campsite> availableCampsites = executeTests ? _gapRuleService.FindAvailableCampsites(jsonFile) : new List <Campsite>(); JsonTemplateResult results = new JsonTemplateResult { ExecutionTemplate = jsonFile, TestCaseName = file.Name, Id = i, ResultingCampsites = availableCampsites }; returnResultList.Add(results); } return(returnResultList); }
JsonTemplate ProcessBeforeJump(ref EditServiceJson tempData, ref EditServiceJsonViewModel viewModel) { var processedTemplate = JsonConvert.DeserializeObject <Models.JsonTemplate>(viewModel.CurrentJson); bool uiChanged = false; if (processedTemplate.IsArray != viewModel.CurrentTemplate.IsArray) { //用户修改了IsArray。 processedTemplate.IsArray = viewModel.CurrentTemplate.IsArray; uiChanged = true; } if (processedTemplate.ValueType != viewModel.CurrentTemplate.ValueType) { processedTemplate = new JsonTemplate(); processedTemplate.ValueType = viewModel.CurrentTemplate.ValueType; processedTemplate.IsArray = viewModel.CurrentTemplate.IsArray; uiChanged = true; } if (uiChanged) { tempData.CurrentJson = JsonConvert.SerializeObject(processedTemplate); } return(processedTemplate); }
bool Ref(JsonTemplate[] args, [MaybeNullWhen(false)] out JsonTemplate result, [MaybeNullWhen(true)] out string err) { if (args.Length != 1 || args[0] is not JsonTemplateString { Value : { } filename })
public EntityTemplate(string resourceGroup, string name, JsonTemplate entity) { ResourceGroup = resourceGroup ?? throw new ArgumentNullException(nameof(resourceGroup)); Name = name ?? throw new ArgumentNullException(nameof(name)); Entity = entity ?? throw new ArgumentNullException(nameof(entity)); }
public HttpResponseMessage Marcado(NovoAgendamentoViewModel agenda) { try { var paciente = _cadastroService.ObterPacienteById(agenda.idpaciente); if (paciente == null) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Não foi possivel recuperar dados do paciente.")); } var clinica = _cadastroService.ObterClinicaById(base.GetUsuarioLogado().IdClinica); var unidade = _cadastroService.ObterUnidadeAtendimentoPorId(base.GetUsuarioLogado().IdUnidadeAtendimento); if (clinica == null) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Não foi possivel recuperar dados da clinica.")); } _serviceAgenda.Marcar(agenda.idagenda, agenda.idpaciente, agenda.idprofissional, agenda.idespecialidade, agenda.idprocedimento, agenda.idconvenio, agenda.tipo, agenda.observacoes, agenda.solicitante, agenda.valor, agenda.valorProfissional, agenda.idtipoatendimento, base.GetUsuarioLogado().IdUsuario, agenda.idUnidadeAtendimento); if (!String.IsNullOrEmpty(paciente.Pessoa?.Email)) { var template = _serviceAgenda.GetTemplateByIdentifier("AGENDAMENTO_ONLINE"); if (template == null) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Não foi possivel recuperar o Templete de e-mail.")); } string endereco = unidade.Logradouro + ", " + unidade.Numero + "Bairro: " + unidade.Bairro; string protocolo = agenda.idagenda.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString(); var obj = new JsonTemplate() { SUBJECT = new JsonTemplateSubject() { PROTOCOLO = protocolo }, BODY = new JsonTemplateBody() { PACIENTE = paciente.Pessoa.Nome.ToUpper(), CLINICA = clinica.Nome + " - " + endereco, DATA_HORA = DateTime.Now.ToShortDateString() + " - " + DateTime.Now.ToShortTimeString(), TELEFONE = unidade.Telefone1, PROTOCOLO = protocolo, } }; var json = new JavaScriptSerializer().Serialize(obj); _serviceAgenda.AddToQueue(new MailQueue(template, paciente.Pessoa.Email, json)); } return(Request.CreateResponse(HttpStatusCode.OK)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }