예제 #1
0
        public void PatchWorksWithListInRoot()
        {
            var originalProperties = new[] { 1, 2, 3 };

            var originalPropertiesSerialized = JsonConvert.SerializeObject(originalProperties, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling       = TypeNameHandling.None
            });

            var patchProperties = new[] { 4, 5, 6 };

            var patchPropertiesSerialized = JsonConvert.SerializeObject(patchProperties, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling       = TypeNameHandling.None
            });

            var actual = JsonUtilities.Patch(originalPropertiesSerialized, patchPropertiesSerialized);

            Assert.Equal("[4,5,6]", actual);
        }
예제 #2
0
        public void ChildrenTests()
        {
            string         json      = ReflectionUtilities.GetResourceAsString("UnitTests.Core.ApsimFile.JsonUtilitiesTestsEnsureChildrenWorks.json");
            JObject        rootNode  = JObject.Parse(json);
            List <JObject> children  = JsonUtilities.Children(rootNode);
            List <JObject> emptyList = new List <JObject>();

            // Ensure children is not null.
            Assert.NotNull(children);

            // Ensure number of children is correct.
            Assert.AreEqual(4, children.Count);

            // Ensure children of null is an empty list.
            Assert.AreEqual(emptyList, JsonUtilities.Children(null));

            // Ensure children of a node with empty children property is empty list.
            Assert.AreEqual(emptyList, JsonUtilities.Children(children[0] as JObject));

            // Ensure children of a node with no children property is an empty list.
            Assert.AreEqual(emptyList, JsonUtilities.Children(children[1] as JObject));
        }
예제 #3
0
        public void PatchWorksWithValueInRoot()
        {
            var originalProperties = "foo";

            var originalPropertiesSerialized = JsonConvert.SerializeObject(originalProperties, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling       = TypeNameHandling.None
            });

            var patchProperties = "bar";

            var patchPropertiesSerialized = JsonConvert.SerializeObject(patchProperties, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling       = TypeNameHandling.None
            });

            var actual = JsonUtilities.Patch(originalPropertiesSerialized, patchPropertiesSerialized);

            Assert.AreEqual("\"bar\"", actual);
        }
예제 #4
0
        public void EnsureReleasedModelsAreNotSaved()
        {
            string json       = ReflectionUtilities.GetResourceAsString("UnitTests.Resources.WheatModel.apsimx");
            IModel topLevel   = FileFormat.ReadFromString <Simulations>(json, out List <Exception> errors);
            string serialized = FileFormat.WriteToString(topLevel);

            JObject root = JObject.Parse(serialized);

            // This file contains 2 wheat models - one under replacements, and one under a folder.
            JObject fullWheat = JsonUtilities.ChildWithName(JsonUtilities.ChildWithName(root, "Replacements"), "Wheat");
            JObject wheat     = JsonUtilities.ChildWithName(JsonUtilities.ChildWithName(root, "Folder"), "Wheat");

            // The wheat model under replacements should have its full
            // model structure (properties + children) serialized.
            Assert.NotNull(fullWheat);
            Assert.AreNotEqual(0, JsonUtilities.Children(fullWheat).Count);

            // The wheat model under the folder should *not* have its
            // full model structure (properties + children) serialized.
            Assert.NotNull(wheat);
            Assert.AreEqual(0, JsonUtilities.Children(wheat).Count);
        }
예제 #5
0
        public async Task <ShareViewModel> CheckPermaLinkDataAsync(ShareInput shareInput)
        {
            dynamic userSharedResourcesDBData          = null;
            List <SharedResources> userSharedResources = new List <SharedResources>();

            if (shareInput.UserId == null || shareInput.Url == null)
            {
                return(null);
            }
            UserProfile userProfile = await dbUserProfile.GetUserProfileDataAsync(shareInput.UserId);

            if (userProfile == null)
            {
                return(null);
            }
            else
            {
                if (userProfile?.SharedResourceId != null && userProfile.SharedResourceId != Guid.Empty)
                {
                    userSharedResourcesDBData = await dbClient.FindItemsWhereAsync(dbSettings.UserResourcesCollectionId, Constants.Id, Convert.ToString(userProfile.SharedResourceId, CultureInfo.InvariantCulture));
                }
                if (userSharedResourcesDBData != null && userSharedResourcesDBData?.Count > 0)
                {
                    userSharedResources = JsonUtilities.DeserializeDynamicObject <List <SharedResources> >(userSharedResourcesDBData);
                }
                else
                {
                    return(null);
                }
            }
            var resource = userSharedResources[0].SharedResource.FindAll(a => a.Url.OriginalString.
                                                                         Contains(shareInput.Url.OriginalString) &&
                                                                         DateTime.Compare(a.ExpirationDate, DateTime.UtcNow) >= 0);

            return(resource.Count == 0 ? null : new ShareViewModel
            {
                PermaLink = GetPermaLink(resource.Select(a => a.PermaLink).First())
            });
        }
예제 #6
0
        /// <summary>
        /// Returns private configuration as string
        /// </summary>
        /// <returns></returns>
        protected string GetPrivateConfiguration()
        {
            PrivateKeyVaultCredentialSettings akvPrivateSettings = null;

            if (this.KeyVaultCredentialSettings != null)
            {
                akvPrivateSettings = new PrivateKeyVaultCredentialSettings {
                    AzureKeyVaultUrl       = this.KeyVaultCredentialSettings.AzureKeyVaultUrl,
                    ServicePrincipalName   = this.KeyVaultCredentialSettings.ServicePrincipalName,
                    ServicePrincipalSecret = this.KeyVaultCredentialSettings.ServicePrincipalSecret
                };
            }

            return(JsonUtilities.TryFormatJson(JsonConvert.SerializeObject(
                                                   new SqlServerPrivateSettings
            {
                StorageUrl = (this.AutoBackupSettings == null) ? string.Empty : this.AutoBackupSettings.StorageUrl,
                StorageAccessKey = (this.AutoBackupSettings == null) ? string.Empty : this.AutoBackupSettings.StorageAccessKey,
                Password = (this.AutoBackupSettings == null) ? string.Empty : this.AutoBackupSettings.Password,
                PrivateKeyVaultCredentialSettings = (akvPrivateSettings == null) ? null : akvPrivateSettings
            })));
        }
        static public void BaseTestJson(string text, bool ignoreEmptyLines = false)
        {
            var actual   = BaseTest(text);
            var expected = text;

            //Fix sorting. But missing properties in the model will be hidden.
            var database = JsonUtilities.Deserialize(expected);

            expected = JsonUtilities.Serialize(database);

            if (ignoreEmptyLines)
            {
                //Ignore empty lines. Parser not support whitespaces before expressions.
                WindiffAssert.AreEqualIgnoreEmptyLinesInExpressions(expected, actual);
            }
            else
            {
                WindiffAssert.AreEqual(expected, actual);
            }

            ValidateDatabase(text);
        }
예제 #8
0
        public void PatchWorksWithMismatchInBody()
        {
            var originalProperties = new Dictionary <string, object>
            {
                { "name", "site1" },
                { "siteMode", "Standard" },
                { "computeMode", "Dedicated" },
                { "list", new [] { 1, 2, 3 } },
                { "misc", new Dictionary <string, object>
                  {
                      { "key1", "value1" },
                      { "key2", "value2" }
                  } }
            };

            var originalPropertiesSerialized = JsonConvert.SerializeObject(originalProperties, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling       = TypeNameHandling.None
            });

            var patchProperties = new Dictionary <string, object>
            {
                { "siteMode", "Dedicated" },
                { "list", "foo" },
                { "misc", new Dictionary <string, object>
                  {
                      { "key3", "value3" }
                  } }
            };

            var patchPropertiesSerialized = JsonConvert.SerializeObject(patchProperties, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling       = TypeNameHandling.None
            });

            Assert.Throws <ArgumentException>(() => JToken.Parse(JsonUtilities.Patch(originalPropertiesSerialized, patchPropertiesSerialized)));
        }
예제 #9
0
        public async Task <bool> DeleteItem(string id, string itemId)
        {
            var filter = new QueryFilter();

            filter.AddCondition("id", QueryOperator.Equal, id);

            var search   = _table.Query(filter);
            var querySet = await search.GetNextSetAsync();

            var document = querySet.First();

            var items = JsonUtilities.Deserialize <List <CartItem> >(document["items"].AsString());
            var item  = items.FirstOrDefault(x => x.Id.ToString() == itemId);

            items.Remove(item);

            await _table.UpdateItemAsync(document);

            var result = await GetById(id);

            return(result.Items.All(x => x.Id.ToString() != itemId));
        }
예제 #10
0
        public async Task <IEnumerable <NoteModel> > GetPatientHistoryAsync(int patientId)
        {
            IEnumerable <NoteModel> result = null;

            var retry = Policy.Handle <HttpRequestException>()
                        .WaitAndRetry(new[]
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(3),
                TimeSpan.FromSeconds(5)
            });

            try
            {
                await retry.Execute(async() =>
                {
                    var response =
                        await _httpClient.GetAsync($"/api/history/patient/{patientId}");

                    if (response.IsSuccessStatusCode)
                    {
                        var stream = await response.Content.ReadAsStreamAsync();
                        result     = JsonUtilities.DeserializeJsonFromStream <IEnumerable <NoteModel> >(stream);
                    }
                    else
                    {
                        result = new List <NoteModel>();
                    }
                });
            }
            catch (Exception e)
            {
                Log.Error("An error occurred while attempting to fetch data from an external API.", e.Message);
                throw;
            }

            return(result);
        }
예제 #11
0
        public void OutputStrelkaSnvRelevantFields()
        {
            var json =
                JsonUtilities.GetJson(
                    "2	167760371	rs267598980	G	A	.	PASS	SOMATIC;QSS=34;TQSS=1;NT=ref;QSS_NT=34;TQSS_NT=1;SGT=GG->AG;DP=45;MQ=60.00;MQ0=0;ALTPOS=43;ALTMAP=19;ReadPosRankSum=-1.64;SNVSB=0.00;PNOISE=0.00;PNOISE2=0.00;VQSR=5.54;cosmic=COSM36673;clinvar=other;CSQT=A|XIRP2|ENST00000409195|missense_variant	DP:FDP:SDP:SUBDP:AU:CU:GU:TU	19:0:0:0:0,0:0,0:19,19:0,0	26:0:0:0:6,6:0,0:20,20:0,0", _renamer);

            Assert.NotNull(json);

            const string expectedRecalibratedQuality = "5.54";

            Assert.Equal(expectedRecalibratedQuality, json.RecalibratedQuality);

            const string expectedJointSomaticNormalQuality = "34";

            Assert.Equal(expectedJointSomaticNormalQuality, json.JointSomaticNormalQuality);


            var expectedJointSomaticNormalQualityEntry = $"\"jointSomaticNormalQuality\":{expectedJointSomaticNormalQuality}";
            var expectedRecalibratedQualityEntry       = $"\"recalibratedQuality\":{expectedRecalibratedQuality}";

            Assert.Contains(expectedRecalibratedQualityEntry, json.ToString());
            Assert.Contains(expectedJointSomaticNormalQualityEntry, json.ToString());
        }
예제 #12
0
        public void ChildrenRecursivelyTests()
        {
            string         json        = ReflectionUtilities.GetResourceAsString("UnitTests.Core.ApsimFile.JsonUtilitiesTestsEnsureChildrenRecursivelyWorks.json");
            JObject        rootNode    = JObject.Parse(json);
            List <JObject> children    = JsonUtilities.Children(rootNode);
            List <JObject> descendants = JsonUtilities.ChildrenRecursively(rootNode);
            List <JObject> emptyList   = new List <JObject>();

            // Ensure descendants is not null.
            Assert.NotNull(descendants);

            // Ensure number of descendants is correct.
            Assert.AreEqual(6, descendants.Count);

            // Ensure descendants of null is an empty list (not null).
            Assert.AreEqual(emptyList, JsonUtilities.ChildrenRecursively(null));

            // Ensure descendants of a node with an empty children property is an empty list.
            Assert.AreEqual(emptyList, JsonUtilities.ChildrenRecursively(children[0] as JObject));

            // Ensure descendants of a node with no children property is an empty list.
            Assert.AreEqual(emptyList, JsonUtilities.ChildrenRecursively(children[1] as JObject));
        }
예제 #13
0
        public void RefNoCallStrelkaFields()
        {
            var json =
                JsonUtilities.GetJson(
                    "1	205664649	.	C	.	.	LowQscore	SOMATIC;QSS=3;TQSS=1;NT=ref;QSS_NT=3;TQSS_NT=1;SGT=CC->CC;DP=116;MQ=57.63;MQ0=9;ALTPOS=89;ALTMAP=55;ReadPosRankSum=-1.14;SNVSB=6.63;PNOISE=0.00;PNOISE2=0.00;VQSR=0.15	DP:FDP:SDP:SUBDP:AU:CU:GU:TU	11:4:0:0:0,0:7,8:0,0:0,0	92:28:0:0:5,17:58,62:1,1:0,0", _renamer);

            Assert.NotNull(json);

            const string expectedRecalibratedQuality = "0.15";

            Assert.Equal(expectedRecalibratedQuality, json.RecalibratedQuality);

            const string expectedJointSomaticNormalQuality = "3";

            Assert.Equal(expectedJointSomaticNormalQuality, json.JointSomaticNormalQuality);


            var expectedJointSomaticNormalQualityEntry = $"\"jointSomaticNormalQuality\":{expectedJointSomaticNormalQuality}";
            var expectedRecalibratedQualityEntry       = $"\"recalibratedQuality\":{expectedRecalibratedQuality}";

            Assert.Contains(expectedRecalibratedQualityEntry, json.ToString());
            Assert.Contains(expectedJointSomaticNormalQualityEntry, json.ToString());
        }
예제 #14
0
        public void PatchWorksWithNullSourceValue()
        {
            var patchProperties = new Dictionary <string, object>
            {
                { "siteMode", "Dedicated" },
                { "newMode", "NewValue" },
                { "list", new [] { 4, 5, 6 } },
                { "misc", new Dictionary <string, object>
                  {
                      { "key3", "value3" }
                  } }
            };

            var patchPropertiesSerialized = JsonConvert.SerializeObject(patchProperties, new JsonSerializerSettings
            {
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
                TypeNameHandling       = TypeNameHandling.None
            });

            var actual = JsonUtilities.Patch("", patchPropertiesSerialized);

            Assert.Equal(patchPropertiesSerialized, actual);
        }
예제 #15
0
        public async Task <object> GetPermaLinkDataAsync(string permaLink)
        {
            if (string.IsNullOrEmpty(permaLink))
            {
                return(null);
            }
            var response = await dbClient.FindFieldWhereArrayContainsAsync(dbSettings.UserResourcesCollectionId,
                                                                           Constants.SharedResource, Constants.PermaLink, permaLink, Constants.ExpirationDate);

            if (response == null)
            {
                return(null);
            }
            List <ShareProfileDetails> shareProfileDetails = JsonUtilities.DeserializeDynamicObject <List <ShareProfileDetails> >(response);
            ShareProfileViewModel      profileViewModel    = new ShareProfileViewModel();

            if (shareProfileDetails.Count() > 0)
            {
                var userprofileResponse = await dbClient.FindFieldWhereArrayContainsAsync(dbSettings.ProfilesCollectionId, Constants.sharedResourceId, shareProfileDetails[0].Id);

                List <ShareProfileResponse> shareProfileResponse = JsonUtilities.DeserializeDynamicObject <List <ShareProfileResponse> >(userprofileResponse);
                if (shareProfileResponse?.Count > 0)
                {
                    shareProfileResponse[0].Link = shareProfileDetails.FirstOrDefault().Link;
                    foreach (var profile in shareProfileResponse)
                    {
                        if (profile.Link == Constants.ProfileLink)
                        {
                            profileViewModel.UserName = profile.Name;
                            profileViewModel.UserId   = profile.OId;
                        }
                        profileViewModel.ResourceLink = profile.Link;
                    }
                }
            }
            return(profileViewModel);
        }
예제 #16
0
        /// <summary>
        /// Returns the public configuration as string
        /// </summary>
        /// <returns></returns>
        protected string GetPublicConfiguration()
        {
            // Create auto backup settings if set
            PublicAutoBackupSettings autoBackupSettings = null;

            if (this.AutoBackupSettings != null)
            {
                autoBackupSettings = new PublicAutoBackupSettings()
                {
                    Enable           = this.AutoBackupSettings.Enable,
                    EnableEncryption = this.AutoBackupSettings.EnableEncryption,
                    RetentionPeriod  = this.AutoBackupSettings.RetentionPeriod
                };
            }

            // Create Key vault settings if set
            PublicKeyVaultCredentialSettings akvSettings = null;

            if (this.KeyVaultCredentialSettings != null)
            {
                akvSettings = new PublicKeyVaultCredentialSettings()
                {
                    Enable         = this.KeyVaultCredentialSettings == null ? false : this.KeyVaultCredentialSettings.Enable,
                    CredentialName = this.KeyVaultCredentialSettings == null ? null : this.KeyVaultCredentialSettings.CredentialName
                };
            }

            return(JsonUtilities.TryFormatJson(JsonConvert.SerializeObject(
                                                   new SqlServerPublicSettings
            {
                AutoPatchingSettings = this.AutoPatchingSettings,
                AutoTelemetrySettings = this.AutoTelemetrySettings,
                AutoBackupSettings = autoBackupSettings,
                KeyVaultCredentialSettings = akvSettings
            })));
        }
        public async Task <dynamic> GetPagedResourceAsync(ResourceFilter resourceFilter)
        {
            PagedResourceViewModel pagedResourceViewModel = new PagedResourceViewModel();

            if (resourceFilter.IsResourceCountRequired)
            {
                var groupedResourceType = await GetResourcesCountAsync(resourceFilter);

                pagedResourceViewModel.ResourceTypeFilter = JsonUtilities.DeserializeDynamicObject <dynamic>(groupedResourceType);
            }
            dynamic searchFilter = new JObject();

            searchFilter.OrderByField = resourceFilter.OrderByField;
            searchFilter.OrderBy      = resourceFilter.OrderBy;
            PagedResources pagedResources = await ApplyPaginationAsync(resourceFilter);

            dynamic serializedToken = pagedResources?.ContinuationToken ?? Constants.EmptyArray;

            pagedResourceViewModel.Resources         = JsonUtilities.DeserializeDynamicObject <dynamic>(pagedResources?.Results);
            pagedResourceViewModel.ContinuationToken = JsonConvert.DeserializeObject(serializedToken);
            pagedResourceViewModel.TopicIds          = JsonUtilities.DeserializeDynamicObject <dynamic>(pagedResources?.TopicIds);
            pagedResourceViewModel.SearchFilter      = searchFilter;
            return(JObject.FromObject(pagedResourceViewModel).ToString());
        }
예제 #18
0
        public void AnnotationCarryover()
        {
            var annotatedVariant = DataUtilities.GetVariant(DataUtilities.EmptyCachePrefix, Resources.MiniSuppAnnot("chr2_90472571_90472592.nsa"),
                                                            "2	90472571	.	AAAAAAAAAAAAAAAAAAGTCC	AGTCT	177	PASS	CIGAR=1M21D4I;RU=.;REFREP=.;IDREP=.	GT:GQ:GQX:DPI:AD	0/1:220:177:46:40,7");

            Assert.NotNull(annotatedVariant);

            var altAllele = JsonUtilities.GetFirstAlleleJson(annotatedVariant);

            Assert.NotNull(altAllele);

            Assert.Equal("{\"altAllele\":\"GTCT\",\"refAllele\":\"AAAAAAAAAAAAAAAAAGTCC\",\"begin\":90472572,\"chromosome\":\"2\",\"end\":90472592,\"variantType\":\"indel\",\"vid\":\"2:90472572:90472592:GTCT\"}", altAllele);

            var annotatedVariant2 = DataUtilities.GetVariant(DataUtilities.EmptyCachePrefix, Resources.MiniSuppAnnot("chr2_90472571_90472592.nsa"),
                                                             "2	90472592	.	C	.	.	PASS	RefMinor	GT:GQX:DP:DPF:AD	0:96:33:15:33");

            Assert.NotNull(annotatedVariant2);

            var altAllele2 = JsonUtilities.GetFirstAlleleJson(annotatedVariant2);

            Assert.NotNull(altAllele2);

            Assert.Equal("{\"refAllele\":\"C\",\"begin\":90472592,\"chromosome\":\"2\",\"end\":90472592,\"globalMinorAllele\":\"C\",\"gmaf\":0.006989,\"isReferenceMinorAllele\":true,\"variantType\":\"SNV\",\"vid\":\"2:90472592:C\"}", altAllele2);
        }
예제 #19
0
        public void OutputCanvasCnvRelevantField()
        {
            var vcfLine = "1	9314201	Canvas:GAIN:1:9314202:9404148	N	<CNV>	36	PASS	SVTYPE=CNV;END=9404148;ensembl_gene_id=ENSG00000049239,ENSG00000252841,ENSG00000171621	RC:BC:CN:MCC	.	151:108:6:4";

            var annotatedVariant = DataUtilities.GetVariant(Resources.CacheGRCh37("ENST00000377403_chr1_Ensembl84"), null, vcfLine);

            Assert.NotNull(annotatedVariant);

            JsonUtilities.AlleleEquals(annotatedVariant,
                                       "{\"altAllele\":\"CNV\",\"refAllele\":\"N\",\"begin\":9314202,\"chromosome\":\"1\",\"end\":9404148,\"variantType\":\"copy_number_variation\",\"vid\":\"1:9314202:9404148:6\",\"overlappingGenes\":[\"H6PD\"],\"transcripts\":{\"ensembl\":[{\"transcript\":\"ENST00000377403.2\",\"bioType\":\"protein_coding\",\"exons\":\"4-5/5\",\"introns\":\"3-4/4\",\"geneId\":\"ENSG00000049239\",\"hgnc\":\"H6PD\",\"consequence\":[\"copy_number_increase\"],\"isCanonical\":true,\"proteinId\":\"ENSP00000366620.1\"}]}}");

            var cols = vcfLine.Split('\t');

            var extractor = new SampleFieldExtractor(cols);
            var samples   = extractor.ExtractSamples();

            Assert.Equal(2, samples.Count);

            var sample = samples[1];

            var observedCn = sample?.CopyNumber;

            Assert.Equal("6", observedCn);
        }
예제 #20
0
        public Blob(Dictionary <string, object> dico, Column column, Row row, Server server)
        {
            if (dico == null)
            {
                throw new ArgumentNullException(nameof(dico));
            }
            if (column == null)
            {
                throw new ArgumentNullException(nameof(column));
            }
            if (row == null)
            {
                throw new ArgumentNullException(nameof(row));
            }
            if (server == null)
            {
                throw new ArgumentNullException(nameof(server));
            }

            JsonUtilities.Apply(dico, this, new JsonUtilitiesOptions());
            _column = column;
            _row    = row;
            _server = server;
        }
예제 #21
0
        /// <summary>
        /// For now, the 2nd message KVP inside "details" contains useful info about the failure. Eventually, a code KVP
        /// will be added such that we can search on that directly.
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        internal static string FindDetailedMessage(string content)
        {
            string message = null;

            if (JsonUtilities.IsJson(content))
            {
                var response = JObject.Parse(content);

                // check that we have a details section
                var detailsToken = response["details"];

                if (detailsToken != null)
                {
                    var details = detailsToken as JArray;
                    if (details != null && details.Count > 1)
                    {
                        // for now, 2nd entry in array is the one we're interested in. Need a better way of identifying the
                        // detailed error message
                        var dObj = detailsToken[1] as JObject;
                        var code = dObj.GetValue("code", StringComparison.CurrentCultureIgnoreCase);
                        if (code != null)
                        {
                            message = code.ToString() + ": ";
                        }

                        var detailedMsg = dObj.GetValue("message", StringComparison.CurrentCultureIgnoreCase);
                        if (detailedMsg != null)
                        {
                            message += detailedMsg.ToString();
                        }
                    }
                }
            }

            return(message);
        }
예제 #22
0
        public async Task <JsonResult> IndexAsync()
        {
            Reporte        reportItem;
            List <Reporte> listaReport = new List <Reporte>();
            //Recuperamos información de guías desde un archivo en formato JSON
            var itemsInJsonFile = JsonUtilities.readJsonFile("Data\\labels.json");

            //Cálculo de peso volumétrico de cáda item que se encuentra en el Json, este cálculo se guarda un la propiedad del objeto llamada volumetricWeight
            foreach (var shipment in itemsInJsonFile)
            {
                shipment.volumetricWeight = WeightUtilitties.calculateVolumetricWeight(shipment.parcel.width, shipment.parcel.height, shipment.parcel.length);
                //Decidimos el peso total del item y lo metemos en el reporte
                reportItem = new Reporte {
                    ticketWeight = WeightUtilitties.calculateTotalWeight(shipment.volumetricWeight, shipment.parcel.weight)
                };
                //Llamada al servicio asyncrona
                Task <string> soapRequest = CreateSoapEnvelopeAsync(
                    _configuration.GetValue <string>("Key"),
                    _configuration.GetValue <string>("Password"),
                    _configuration.GetValue <string>("AccountNumber"),
                    _configuration.GetValue <string>("MeterNumber"),
                    shipment.tracking_number
                    );
                //Recuperamos informacion del peso real del servicio
                reportItem.realWeight = await soapRequest;
                //Calculamos si existe el sobre peso
                reportItem.sobrePeso = WeightUtilitties.calculateSobrePeso(reportItem.ticketWeight, reportItem.realWeight);
                if (reportItem.sobrePeso > 0)
                {
                    reportItem.hasSobrePeso = true;
                }
                listaReport.Add(reportItem);
            }

            return(Json(new { listaReport }));
        }
    protected override void ParseParameters(JsonData parameters)
    {
        base.ParseParameters(parameters);

        MobId = JsonUtilities.ParseInt(parameters, "mob_id");
    }
예제 #24
0
        static Item()
        {
            var data = JsonUtilities.Deserialize <ItemData[]>("Items.json");

            dataMap = data.ToDictionary(d => d.Id, d => d);
        }
예제 #25
0
 public PathRepository()
 {
     _jsonUtilities = new JsonUtilities();
 }
예제 #26
0
 public void CosmicInsDel()
 {
     JsonUtilities.AlleleContains(
         "3	10188320	COSM18152	G	A	.	.	GENE=VHL;STRAND=+;CDS=c.463G>A;AA=p.V155M;CNT=7",
         Resources.MiniSuppAnnot("chr3_10188320_10188321.nsa"), "\"id\":\"COSM14426\",\"refAllele\":\"GGTACTGAC\",\"altAllele\":\"A\"");
 }
예제 #27
0
 public void CosmicTsvChrXname23()
 {
     JsonUtilities.AlleleContains("X	2856155	COSM5003595	C	T	.	.	GENE=ARSE", Resources.MiniSuppAnnot("chrX_2856155_2856156.nsa"),
                                  "\"cosmic\":[{\"id\":\"COSM5003595\",\"isAlleleSpecific\":true,\"refAllele\":\"C\",\"altAllele\":\"T\",\"gene\":\"ARSE\",\"sampleCount\":1,\"studies\":[{\"histology\":\"carcinoma\",\"primarySite\":\"pancreas\"}]},{\"id\":\"COSM5003596\",\"isAlleleSpecific\":true,\"refAllele\":\"C\",\"altAllele\":\"T\",\"gene\":\"ARSE_ENST00000540563\",\"sampleCount\":1,\"studies\":[{\"histology\":\"carcinoma\",\"primarySite\":\"pancreas\"}]}]");
 }
예제 #28
0
        // TODO: (richardross) investigate this.
        // Obj-C type -> .NET type is impossible to do flawlessly (especially
        // on NSNumber). We can't transform NSDictionary into string because of this reason.

        internal ParsePushNotificationEvent(string stringPayload)
        {
            TextContent = stringPayload;
            Content     = JsonUtilities.Parse(stringPayload) as IDictionary <string, object>;
        }
예제 #29
0
 internal ParsePushNotificationEvent(IDictionary <string, object> content)
 {
     Content     = content;
     TextContent = JsonUtilities.Encode(content);
 }
예제 #30
0
 public override string ToString() => JsonUtilities.SerializeObject(this);