public async Task <ActionResult> Put([FromQuery] string dataType) { string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType); if (string.IsNullOrEmpty(classRef)) { return(BadRequest($"Invalid dataType {dataType} provided. Please provide a valid dataType as query parameter.")); } ModelDeserializer deserializer = new ModelDeserializer(_logger, _altinnApp.GetAppModelType(classRef)); object appModel = await deserializer.DeserializeAsync(Request.Body, Request.ContentType); if (!string.IsNullOrEmpty(deserializer.Error)) { return(BadRequest(deserializer.Error)); } if (appModel == null) { return(BadRequest("No data found in content")); } await _altinnApp.RunCalculation(appModel); return(Ok(appModel)); }
public async Task DeserializeAsync_InputValidModelAsXml_ReturnsInitializedModel_ErrorIsNull() { // Arrange Mock <ILogger> logger = new Mock <ILogger>(); ModelDeserializer target = new ModelDeserializer(logger.Object, typeof(Skjema)); string serializedModel = string.Empty + @"<?xml version=""1.0""?>" + @"<Skjema xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""" + @" skjemanummer=""1472"" spesifikasjonsnummer=""9812"" blankettnummer=""AFP-01"" tittel=""Arbeidsgiverskjema AFP"" gruppeid=""8818"">" + @" <Foretak-grp-8820 gruppeid=""8820"">" + @" <EnhetNavnEndring-datadef-31 orid=""31"">Test Test 123</EnhetNavnEndring-datadef-31>" + @" </Foretak-grp-8820>" + @"</Skjema>"; // Act object model; using (Stream stream = CreateStream(serializedModel)) { model = await target.DeserializeAsync(stream, "application/xml"); } Skjema actual = model as Skjema; // Assert Assert.NotNull(actual); Assert.Null(target.Error); Assert.Equal("Test Test 123", actual?.Foretakgrp8820?.EnhetNavnEndringdatadef31?.value); Assert.Equal(1472, actual?.skjemanummer); }
public void TestDeserializeEmpty() { string json = @" { ""objectTypes"": [], ""eventTypes"": [ { ""key"": ""event_type1"", ""description"": ""desc"", ""origin"": ""scheduled"", ""timeseries"": [] } ], ""ownerAttributes"": [], ""sessionizers"": [], ""orphans"": {} } "; Model model = ModelDeserializer.DeserializeModel(json); Assert.AreEqual(1, model.EventTypes.Count, "event types count"); Assert.AreEqual(0, model.Timeseries.Count, "timeseries count"); Assert.AreEqual(0, model.ObjectTypes.Count, "object types count"); Assert.AreEqual(0, model.ObjectAttributes.Count, "object attributes count"); Assert.AreEqual(0, model.OwnerAttributes.Count, "owner attributes count"); Assert.AreEqual(0, model.Sessionizers.Count, "sessionizers count"); }
public async Task DeserializeAsync_InputValidModelAsXml_UnexpectedExceptionDuringDeserialization_ReturnsNull_ErrorIsPopulated() { // Arrange Mock <ILogger> logger = new Mock <ILogger>(); ModelDeserializer target = new ModelDeserializer(logger.Object, typeof(Skjema)); string serializedModel = string.Empty + @"<?xml version=""1.0""?>" + @"<Skjema xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""" + @" skjemanummer=""1472"" spesifikasjonsnummer=""9812"" blankettnummer=""AFP-01"" tittel=""Arbeidsgiverskjema AFP"" gruppeid=""8818"">" + @" <Foretak-grp-8820 gruppeid=""8820"">" + @" <EnhetNavnEndring-datadef-31 orid=""31"">Test Test 123</EnhetNavnEndring-datadef-31>" + @" </Foretak-grp-8820>" + @"</Skjema>"; // Act object model; using (Stream stream = CreateStream(serializedModel)) { // Force an exception stream.Close(); model = await target.DeserializeAsync(stream, "application/xml"); } Skjema actual = model as Skjema; // Assert Assert.Null(actual); Assert.Contains("Unexpected exception when attempting to deserialize", target?.Error); }
private async Task<ActionResult> PutFormData(string org, string app, Instance instance, Guid dataGuid, string dataType) { string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType); Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); ModelDeserializer deserializer = new ModelDeserializer(_logger, _altinnApp.GetAppModelType(classRef)); object serviceModel = await deserializer.DeserializeAsync(Request.Body, Request.ContentType); if (!string.IsNullOrEmpty(deserializer.Error)) { return BadRequest(deserializer.Error); } if (serviceModel == null) { return BadRequest("No data found in content"); } string serviceModelJsonString = JsonSerializer.Serialize(serviceModel); // Trigger application business logic bool changedByCalculation = await _altinnApp.RunCalculation(serviceModel); int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); // Save Formdata to database DataElement updatedDataElement = await _dataService.UpdateData( serviceModel, instanceGuid, _altinnApp.GetAppModelType(classRef), org, app, instanceOwnerPartyId, dataGuid); SelfLinkHelper.SetDataAppSelfLinks(instanceOwnerPartyId, instanceGuid, updatedDataElement, Request); string dataUrl = updatedDataElement.SelfLinks.Apps; if (changedByCalculation) { string updatedServiceModelString = JsonSerializer.Serialize(serviceModel); CalculationResult calculationResult = new CalculationResult(updatedDataElement); try { Dictionary<string, object> changedFields = JsonHelper.FindChangedFields(serviceModelJsonString, updatedServiceModelString); calculationResult.ChangedFields = changedFields; } catch (Exception e) { _logger.LogError(e, "Unable to determine changed fields"); } return StatusCode((int)HttpStatusCode.SeeOther, calculationResult); } return Created(dataUrl, updatedDataElement); }
private async Task StorePrefillParts(Instance instance, Application appInfo, List <RequestPart> parts) { Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); int instanceOwnerIdAsInt = int.Parse(instance.InstanceOwner.PartyId); string org = instance.Org; string app = instance.AppId.Split("/")[1]; foreach (RequestPart part in parts) { DataType dataType = appInfo.DataTypes.Find(d => d.Id == part.Name); DataElement dataElement; if (dataType.AppLogic != null) { _logger.LogInformation($"Storing part {part.Name}"); Type type; try { type = _altinnApp.GetAppModelType(dataType.AppLogic.ClassRef); } catch (Exception altinnAppException) { throw new ServiceException(HttpStatusCode.InternalServerError, $"App.GetAppModelType failed: {altinnAppException.Message}", altinnAppException); } ModelDeserializer deserializer = new ModelDeserializer(_logger, type); object data = await deserializer.DeserializeAsync(part.Stream, part.ContentType); if (!string.IsNullOrEmpty(deserializer.Error)) { throw new InvalidOperationException(deserializer.Error); } await _prefillService.PrefillDataModel(instance.InstanceOwner.PartyId, part.Name, data); await _altinnApp.RunDataCreation(instance, data); dataElement = await _dataService.InsertFormData( data, instanceGuid, type, org, app, instanceOwnerIdAsInt, part.Name); } else { dataElement = await _dataService.InsertBinaryData(instance.Id, part.Name, part.ContentType, part.FileName, part.Stream); } if (dataElement == null) { throw new ServiceException(HttpStatusCode.InternalServerError, $"Data service did not return a valid instance metadata when attempt to store data element {part.Name}"); } } }
private async Task <ActionResult> CreateAppModelData( string org, string app, Instance instance, string dataType) { Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); object appModel; string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType); if (Request.ContentType == null) { appModel = _altinnApp.CreateNewAppModel(classRef); } else { ModelDeserializer deserializer = new ModelDeserializer(_logger, _altinnApp.GetAppModelType(classRef)); appModel = await deserializer.DeserializeAsync(Request.Body, Request.ContentType); if (!string.IsNullOrEmpty(deserializer.Error)) { return(BadRequest(deserializer.Error)); } } // runs prefill from repo configuration if config exists await _prefillService.PrefillDataModel(instance.InstanceOwner.PartyId, dataType, appModel); // send events to trigger application business logic await _altinnApp.RunDataCreation(instance, appModel); Dictionary <string, string> updatedValues = DataHelper.GetUpdatedDataValues( _appResourcesService.GetApplication().PresentationFields, instance.PresentationTexts, dataType, appModel); if (updatedValues.Count > 0) { await _instanceService.UpdatePresentationTexts( int.Parse(instance.InstanceOwner.PartyId), Guid.Parse(instance.Id.Split("/")[1]), new PresentationTexts { Texts = updatedValues }); } int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); DataElement dataElement = await _dataService.InsertFormData(appModel, instanceGuid, _altinnApp.GetAppModelType(classRef), org, app, instanceOwnerPartyId, dataType); SelfLinkHelper.SetDataAppSelfLinks(instanceOwnerPartyId, instanceGuid, dataElement, Request); return(Created(dataElement.SelfLinks.Apps, dataElement)); }
public async Task <ActionResult> Post( [FromRoute] string org, [FromRoute] string app, [FromQuery] string dataType) { if (string.IsNullOrEmpty(dataType)) { return(BadRequest($"Invalid dataType {dataType} provided. Please provide a valid dataType as query parameter.")); } string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType); if (string.IsNullOrEmpty(classRef)) { return(BadRequest($"Invalid dataType {dataType} provided. Please provide a valid dataType as query parameter.")); } if (GetPartyHeader(HttpContext).Count > 1) { return(BadRequest($"Invalid party. Only one allowed")); } InstanceOwner owner = await GetInstanceOwner(HttpContext); if (string.IsNullOrEmpty(owner.PartyId)) { return(StatusCode((int)HttpStatusCode.Forbidden)); } EnforcementResult enforcementResult = await AuthorizeAction(org, app, Convert.ToInt32(owner.PartyId), "read"); if (!enforcementResult.Authorized) { return(Forbidden(enforcementResult)); } ModelDeserializer deserializer = new ModelDeserializer(_logger, _altinnApp.GetAppModelType(classRef)); object appModel = await deserializer.DeserializeAsync(Request.Body, Request.ContentType); if (!string.IsNullOrEmpty(deserializer.Error)) { return(BadRequest(deserializer.Error)); } // runs prefill from repo configuration if config exists await _prefillService.PrefillDataModel(owner.PartyId, dataType, appModel); Instance virutalInstance = new Instance() { InstanceOwner = owner }; await _altinnApp.RunProcessDataRead(virutalInstance, null, appModel); return(Ok(appModel)); }
private async Task <ActionResult> PutFormData(string org, string app, Instance instance, Guid dataGuid, string dataType) { string classRef = _appResourcesService.GetClassRefForLogicDataType(dataType); Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); ModelDeserializer deserializer = new ModelDeserializer(_logger, _altinnApp.GetAppModelType(classRef)); object serviceModel = await deserializer.DeserializeAsync(Request.Body, Request.ContentType); if (!string.IsNullOrEmpty(deserializer.Error)) { return(BadRequest(deserializer.Error)); } if (serviceModel == null) { return(BadRequest("No data found in content")); } // Trigger application business logic bool changedByCalculation = await _altinnApp.RunCalculation(serviceModel); int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); // Save Formdata to database DataElement updatedDataElement = await _dataService.UpdateData( serviceModel, instanceGuid, _altinnApp.GetAppModelType(classRef), org, app, instanceOwnerPartyId, dataGuid); SelfLinkHelper.SetDataAppSelfLinks(instanceOwnerPartyId, instanceGuid, updatedDataElement, Request); string dataUrl = updatedDataElement.SelfLinks.Apps; if (changedByCalculation) { return(StatusCode((int)HttpStatusCode.SeeOther, updatedDataElement)); } return(Created(dataUrl, updatedDataElement)); }
public async Task DeserializeAsync_InputValidModelAsJson_UnexpectedExceptionDuringDeserialization_ReturnsNull_ErrorIsPopulated() { // Arrange Mock <ILogger> logger = new Mock <ILogger>(); ModelDeserializer target = new ModelDeserializer(logger.Object, typeof(Skjema)); string serializedModel = string.Empty + @"{" + @" ""skjemanummer"": ""1472""," + @" ""spesifikasjonsnummer"": ""9812""," + @" ""blankettnummer"": ""AFP-01""," + @" ""tittel"": ""Arbeidsgiverskjema AFP""," + @" ""gruppeid"": ""8818""," + @" ""foretakgrp8820"": {" + @" ""gruppeid"": ""8820""," + @" ""enhetNavnEndringdatadef31"": {" + @" ""orid"": ""31""," + @" ""value"": ""Test Test 123""" + @" }" + @" }" + @"}"; // Act object model; using (Stream stream = CreateStream(serializedModel)) { // Force an exception stream.Close(); model = await target.DeserializeAsync(stream, "application/json"); } Skjema actual = model as Skjema; // Assert Assert.Null(actual); Assert.Contains("Unexpected exception when attempting to deserialize", target?.Error); }
public async Task DeserializeAsync_InputValidModelAsJson_ReturnsInitializedModel_ErrorIsNull() { // Arrange Mock <ILogger> logger = new Mock <ILogger>(); ModelDeserializer target = new ModelDeserializer(logger.Object, typeof(Skjema)); string serializedModel = string.Empty + @"{" + @" ""skjemanummer"": ""1472""," + @" ""spesifikasjonsnummer"": ""9812""," + @" ""blankettnummer"": ""AFP-01""," + @" ""tittel"": ""Arbeidsgiverskjema AFP""," + @" ""gruppeid"": ""8818""," + @" ""foretakgrp8820"": {" + @" ""gruppeid"": ""8820""," + @" ""enhetNavnEndringdatadef31"": {" + @" ""orid"": ""31""," + @" ""value"": ""Test Test 123""" + @" }" + @" }" + @"}"; // Act object model; using (Stream stream = CreateStream(serializedModel)) { model = await target.DeserializeAsync(stream, "application/json"); } Skjema actual = model as Skjema; // Assert Assert.NotNull(actual); Assert.Null(target.Error); Assert.Equal("Test Test 123", actual?.Foretakgrp8820?.EnhetNavnEndringdatadef31?.value); Assert.Equal(1472, actual?.skjemanummer); }
public async Task DeserializeAsync_InputUnsupportedContentType_ReturnsNull_ErrorIsPopulated() { // Arrange Mock <ILogger> logger = new Mock <ILogger>(); ModelDeserializer target = new ModelDeserializer(logger.Object, typeof(Skjema)); string serializedModel = @"Text plain"; // Act object model; using (Stream stream = CreateStream(serializedModel)) { model = await target.DeserializeAsync(stream, "text/plain"); } Skjema actual = model as Skjema; // Assert Assert.Null(actual); Assert.Contains("Unknown content type ", target?.Error); }
public static SoftEtherList <T> DeserializeMany(SoftEtherParameterCollection collection, bool moreThanOne = true) { return(ModelDeserializer.DeserializeMany <T>(collection, moreThanOne)); }
public static T Deserialize(SoftEtherParameterCollection collection) { return(ModelDeserializer.Deserialize <T>(collection)); }
public void TestDeserialize() { string json = @" { ""objectTypes"": [ { ""key"": ""object_type1"", ""description"": ""desc"", ""objectAttributes"": [ { ""key"": ""object_text_attribute"", ""displayName"": ""dp object_text_attribute"", ""description"": ""desc object_text_attribute"", ""type"": { ""highLevelType"": ""TEXT"", ""containerType"": ""none"" } }, { ""key"": ""object_int_attribute"", ""displayName"": ""dp object_int_attribute"", ""description"": ""desc object_int_attribute"", ""type"": { ""highLevelType"": ""INT"", ""containerType"": ""list"" } } ] } ], ""eventTypes"": [ { ""key"": ""event_type1"", ""description"": ""desc"", ""origin"": ""scheduled"", ""timeseries"": [ { ""key"": ""ts_number_attribute"", ""displayName"": ""dp ts_number_attribute"", ""description"": ""desc ts_number_attribute"", ""type"": { ""highLevelType"": ""DOUBLE"" } }, { ""key"": ""ts_text_attribute"", ""displayName"": ""dp ts_text_attribute"", ""description"": ""desc ts_text_attribute"", ""type"": { ""highLevelType"": ""TEXT"" } } ] }, { ""key"": ""event_type2"", ""description"": ""desc"", ""origin"": ""rule"", ""timeseries"": [ { ""key"": ""ts_text_attribute"", ""displayName"": ""dp ts_text_attribute"", ""description"": ""desc ts_text_attribute"", ""type"": { ""highLevelType"": ""TEXT"" } } ] } ], ""ownerAttributes"": [ { ""key"": ""owner_text_attribute"", ""displayName"": ""dp owner_text_attribute"", ""description"": ""desc owner_text_attribute"", ""type"": { ""highLevelType"": ""TEXT"", ""containerType"": ""none"" } } ], ""sessionizers"": [ { ""key"": ""sessionizer"", ""displayName"": ""dp sessionizer"", ""description"": ""desc sessionizer"", ""startEventTypeKey"": ""event_type1"", ""endEventTypeKey"": ""event_type2"" } ], ""orphans"": { ""timeseries"": [ { ""key"": ""orphan_ts"", ""displayName"": ""dp orphan_ts"", ""description"": ""desc orphan_ts"", ""type"": { ""highLevelType"": ""ACCELERATION"" } } ], ""objectAttributes"": [ { ""key"": ""orphan_object"", ""displayName"": ""dp orphan_object"", ""description"": ""desc orphan_object"", ""type"": { ""highLevelType"": ""EMAIL"", ""containerType"": ""none"" } } ] } } "; Model model = ModelDeserializer.DeserializeModel(json); Assert.AreEqual(2, model.EventTypes.Count, "event types count"); Assert.AreEqual(2, model.Timeseries.Count, "timeseries count"); Assert.AreEqual(1, model.ObjectTypes.Count, "object types count"); Assert.AreEqual(2, model.ObjectAttributes.Count, "object attributes count"); Assert.AreEqual(1, model.OwnerAttributes.Count, "owner attributes count"); Assert.AreEqual(1, model.Sessionizers.Count, "sessionizers count"); EventType type1 = model.EventTypes[0]; Assert.AreEqual("event_type1", type1.Key); Assert.AreEqual("desc", type1.Description); Assert.AreEqual("scheduled", type1.Origin); Assert.AreEqual(new List <string>() { "ts_number_attribute", "ts_text_attribute" }, type1.TimeseriesKeys); EventType type2 = model.EventTypes[1]; Assert.AreEqual("event_type2", type2.Key); Assert.AreEqual("desc", type2.Description); Assert.AreEqual("rule", type2.Origin); Assert.AreEqual(new List <string>() { "ts_text_attribute" }, type2.TimeseriesKeys); ObjectType oType = model.ObjectTypes[0]; Assert.AreEqual("object_type1", oType.Key); Assert.AreEqual("desc", oType.Description); Assert.AreEqual(new List <string>() { "object_text_attribute", "object_int_attribute" }, oType.ObjectAttributeKeys); ObjectAttribute object1 = model.ObjectAttributes[0]; Assert.AreEqual("object_text_attribute", object1.Key); Assert.AreEqual("dp object_text_attribute", object1.DisplayName); Assert.AreEqual("desc object_text_attribute", object1.Description); Assert.AreEqual("TEXT", object1.HighLevelType); Assert.AreEqual("none", object1.ContainerType); Assert.AreEqual(new List <string>() { "object_type1" }, object1.ObjectTypeKeys); ObjectAttribute object2 = model.ObjectAttributes[1]; Assert.AreEqual("object_int_attribute", object2.Key); Assert.AreEqual("dp object_int_attribute", object2.DisplayName); Assert.AreEqual("desc object_int_attribute", object2.Description); Assert.AreEqual("INT", object2.HighLevelType); Assert.AreEqual("list", object2.ContainerType); Assert.AreEqual(new List <string>() { "object_type1" }, object2.ObjectTypeKeys); Timeseries ts1 = model.Timeseries[0]; Assert.AreEqual("ts_number_attribute", ts1.Key); Assert.AreEqual("dp ts_number_attribute", ts1.DisplayName); Assert.AreEqual("desc ts_number_attribute", ts1.Description); Assert.AreEqual("DOUBLE", ts1.HighLevelType); Assert.AreEqual(new List <string>() { "event_type1" }, ts1.EventTypeKeys); Timeseries ts2 = model.Timeseries[1]; Assert.AreEqual("ts_text_attribute", ts2.Key); Assert.AreEqual("dp ts_text_attribute", ts2.DisplayName); Assert.AreEqual("desc ts_text_attribute", ts2.Description); Assert.AreEqual("TEXT", ts2.HighLevelType); Assert.AreEqual(new List <string>() { "event_type1", "event_type2" }, ts2.EventTypeKeys); OwnerAttribute owner = model.OwnerAttributes[0]; Assert.AreEqual("owner_text_attribute", owner.Key); Assert.AreEqual("dp owner_text_attribute", owner.DisplayName); Assert.AreEqual("desc owner_text_attribute", owner.Description); Assert.AreEqual("TEXT", owner.HighLevelType); Assert.AreEqual("none", owner.ContainerType); Sessionizer sess = model.Sessionizers[0]; Assert.AreEqual("sessionizer", sess.Key); Assert.AreEqual("dp sessionizer", sess.DisplayName); Assert.AreEqual("desc sessionizer", sess.Description); Assert.AreEqual("event_type1", sess.StartEventTypeKey); Assert.AreEqual("event_type2", sess.EndEventTypeKey); ObjectAttribute orphanObj = model.Orphans.ObjectAttributes[0]; Assert.AreEqual("orphan_object", orphanObj.Key); Assert.AreEqual("dp orphan_object", orphanObj.DisplayName); Assert.AreEqual("desc orphan_object", orphanObj.Description); Assert.AreEqual("EMAIL", orphanObj.HighLevelType); Assert.AreEqual("none", orphanObj.ContainerType); Assert.AreEqual(new List <string>(), orphanObj.ObjectTypeKeys); Timeseries orphanTs = model.Orphans.Timeseries[0]; Assert.AreEqual("orphan_ts", orphanTs.Key); Assert.AreEqual("dp orphan_ts", orphanTs.DisplayName); Assert.AreEqual("desc orphan_ts", orphanTs.Description); Assert.AreEqual("ACCELERATION", orphanTs.HighLevelType); Assert.AreEqual(new List <string>(), orphanTs.EventTypeKeys); }