コード例 #1
0
 override public string AsJson()
 {
     return("\"" + id + "\"" + ":" + val.GetRawText());
 }
コード例 #2
0
        public override void SerializeObjectArray()
        {
            IndexViewModel           index           = CreateIndexViewModel();
            CampaignSummaryViewModel campaignSummary = CreateCampaignSummaryViewModel();

            string json = JsonSerializer.Serialize(new object[] { index, campaignSummary }, DefaultContext.ObjectArray);

            object[] arr = JsonSerializer.Deserialize(json, ((ITestContext)MetadataWithPerTypeAttributeContext.Default).ObjectArray);

            JsonElement indexAsJsonElement           = (JsonElement)arr[0];
            JsonElement campaignSummeryAsJsonElement = (JsonElement)arr[1];

            VerifyIndexViewModel(index, JsonSerializer.Deserialize(indexAsJsonElement.GetRawText(), ((ITestContext)MetadataWithPerTypeAttributeContext.Default).IndexViewModel));
            VerifyCampaignSummaryViewModel(campaignSummary, JsonSerializer.Deserialize(campaignSummeryAsJsonElement.GetRawText(), ((ITestContext)MetadataWithPerTypeAttributeContext.Default).CampaignSummaryViewModel));
        }
コード例 #3
0
        public static T ToObject <T>(this JsonElement element)
        {
            var json = element.GetRawText();

            return(JsonSerializer.Deserialize <T>(json, _jsonOpts));
        }
コード例 #4
0
 /// <summary>
 /// Get a stream representation of a JsonElement.  This is an
 /// inefficient hack to let us rip out nested sub-documents
 /// representing different model types and pass them to
 /// ObjectSerializer.
 /// </summary>
 /// <param name="element">The JsonElement.</param>
 /// <returns>The JsonElement's content wrapped in a Stream.</returns>
 public static Stream ToStream(this JsonElement element) =>
 new MemoryStream(
     Encoding.UTF8.GetBytes(
         element.GetRawText()));
コード例 #5
0
 public static object ToObject(this JsonElement element, Type type, JsonSerializerOptions options = null)
 => JsonSerializer.Deserialize(element.GetRawText(), type, options ?? DefaultJsonSerializerOptions);
コード例 #6
0
ファイル: JsonConverter.cs プロジェクト: rvnlord/BlazorDemo
 public static JToken ToJToken(this JsonElement je) => je.GetRawText().JsonDeserialize();
コード例 #7
0
ファイル: JsonExtensions.cs プロジェクト: alethic/MassTransit
        public static object ToObject(this JsonElement element, Type returnType, JsonSerializerOptions options = null)
        {
            var json = element.GetRawText();

            return(JsonSerializer.Deserialize(json, returnType, options));
        }
コード例 #8
0
        /// <summary>Convert a JsonElement into its underlying object of a given type.</summary>
        public static T GetObject <T>(this JsonElement jsonElement)
        {
            var jsonString = jsonElement.GetRawText();

            return(JsonSerializer.Deserialize <T>(jsonString));
        }
コード例 #9
0
        public static T ToOjbect <T>(this JsonElement element)
        {
            var rawText = element.GetRawText();

            return(JsonSerializer.Deserialize <T>(rawText));
        }
コード例 #10
0
        private void SetPropertyValue(Component component, PropertyInfo propertyInfo, JsonElement jsonElement)
        {
            var value = JsonSerializer.Deserialize(jsonElement.GetRawText(), propertyInfo.PropertyType);

            propertyInfo.SetValue(component, value);
        }
コード例 #11
0
ファイル: Helper.cs プロジェクト: zouql/runtime
        private static bool JsonEqual(JsonElement expected, JsonElement actual)
        {
            JsonValueKind valueKind = expected.ValueKind;

            if (valueKind != actual.ValueKind)
            {
                return(false);
            }

            switch (valueKind)
            {
            case JsonValueKind.Object:
                var propertyNames = new HashSet <string>();

                foreach (JsonProperty property in expected.EnumerateObject())
                {
                    propertyNames.Add(property.Name);
                }

                foreach (JsonProperty property in actual.EnumerateObject())
                {
                    propertyNames.Add(property.Name);
                }

                foreach (string name in propertyNames)
                {
                    if (!JsonEqual(expected.GetProperty(name), actual.GetProperty(name)))
                    {
                        return(false);
                    }
                }

                return(true);

            case JsonValueKind.Array:
                JsonElement.ArrayEnumerator expectedEnumerator = actual.EnumerateArray();
                JsonElement.ArrayEnumerator actualEnumerator   = expected.EnumerateArray();

                while (expectedEnumerator.MoveNext())
                {
                    if (!actualEnumerator.MoveNext())
                    {
                        return(false);
                    }

                    if (!JsonEqual(expectedEnumerator.Current, actualEnumerator.Current))
                    {
                        return(false);
                    }
                }

                return(!actualEnumerator.MoveNext());

            case JsonValueKind.String:
                return(expected.GetString() == actual.GetString());

            case JsonValueKind.Number:
            case JsonValueKind.True:
            case JsonValueKind.False:
            case JsonValueKind.Null:
                return(expected.GetRawText() == actual.GetRawText());

            default:
                throw new NotSupportedException($"Unexpected JsonValueKind: JsonValueKind.{valueKind}.");
            }
        }
コード例 #12
0
        public async Task <List <Collateral> > GetByLoanId(int loanId)
        {
            if (loanId <= 0)
            {
                throw new ArgumentException("loan id less than or equal to zero");
            }

            using (HttpClient client = _clientFactory.CreateClient())
            {
                HttpRequestMessage request = new HttpRequestMessage()
                {
                    Method     = HttpMethod.Get,
                    RequestUri = new Uri($"{_collateralApiBaseUrl}/api/collateral?pageno=1&pagesize=100&loanid={loanId}"),
                };

                HttpResponseMessage response;
                response = await client.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    _logger.LogInformation("something went wrong in CollateralManagementApi. StatusCode: " + response.StatusCode);
                    throw new UnexpectedResponseException("something went wrong in CollateralManagementApi");
                }

                JsonElement responseBodyJson = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
                if (responseBodyJson.ValueKind != JsonValueKind.Array)
                {
                    _logger.LogInformation("response body was not an json array");
                    throw new UnexpectedResponseException("response body was not an json array");
                }

                List <Collateral> collaterals = new List <Collateral>();
                for (int index = 0; index < responseBodyJson.GetArrayLength(); index++)
                {
                    JsonElement collateralJson = responseBodyJson[index];
                    if (collateralJson.ValueKind != JsonValueKind.Object)
                    {
                        _logger.LogInformation($"ignoring collateral at index {index}, value kind is not json object");
                        continue;
                    }

                    JsonElement type;
                    if (!collateralJson.TryGetProperty(nameof(Collateral.Type).Trim(), out type) && !collateralJson.TryGetProperty(nameof(Collateral.Type).ToLower().Trim(), out type))
                    {
                        _logger.LogInformation($"ignoring collateral at index {index}, no type property found");
                        continue;
                    }
                    if (type.ValueKind != JsonValueKind.String)
                    {
                        _logger.LogInformation($"ignoring collateral at index {index}, type property is not a json string");
                        continue;
                    }

                    JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions {
                        PropertyNameCaseInsensitive = true
                    };
                    if (type.GetString().ToLower() == nameof(Land).ToLower())
                    {
                        collaterals.Add(JsonSerializer.Deserialize <Land>(collateralJson.GetRawText(), jsonSerializerOptions));
                    }
                    else if (type.GetString().ToLower() == nameof(RealEstate).ToLower())
                    {
                        collaterals.Add(JsonSerializer.Deserialize <RealEstate>(collateralJson.GetRawText(), jsonSerializerOptions));
                    }
                    else
                    {
                        _logger.LogInformation($"ignoring collateral at index {index}, unknown type: {type}");
                        continue;
                    }
                }

                return(collaterals);
            }
        }
コード例 #13
0
        public override void SerializeObjectArray_WithCustomOptions()
        {
            IndexViewModel           index           = CreateIndexViewModel();
            CampaignSummaryViewModel campaignSummary = CreateCampaignSummaryViewModel();

            ITestContext context = SerializationContextWithCamelCase.Default;

            Assert.Same(JsonNamingPolicy.CamelCase, ((JsonSerializerContext)context).Options.PropertyNamingPolicy);

            string json = JsonSerializer.Serialize(new object[] { index, campaignSummary }, context.ObjectArray);

            // Verify JSON was written with camel casing.
            Assert.Contains("activeOrUpcomingEvents", json);
            Assert.Contains("featuredCampaign", json);
            Assert.Contains("description", json);
            Assert.Contains("organizationName", json);

            object[] arr = JsonSerializer.Deserialize(json, ((ITestContext)MetadataContext.Default).ObjectArray);

            JsonElement indexAsJsonElement           = (JsonElement)arr[0];
            JsonElement campaignSummeryAsJsonElement = (JsonElement)arr[1];

            ITestContext metadataContext = new MetadataContext(new JsonSerializerOptions {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            VerifyIndexViewModel(index, JsonSerializer.Deserialize(indexAsJsonElement.GetRawText(), metadataContext.IndexViewModel));
            VerifyCampaignSummaryViewModel(campaignSummary, JsonSerializer.Deserialize(campaignSummeryAsJsonElement.GetRawText(), metadataContext.CampaignSummaryViewModel));
        }
コード例 #14
0
        public object insert([FromBody] JsonElement json)
        {
            var model = JsonConvert.DeserializeObject <UserDTO>(json.GetRawText());

            if (model == null)
            {
                return(CreatedAtAction(nameof(insert), new { result = ResultCode.InputHasNotFound, message = ResultMessage.InputHasNotFound }));
            }

            var users    = _context.Users.Count() + 1;
            var username = "******" + users.ToString("0000");

            model.username = username;

            var u = new User();

            u.UserName        = model.username;
            u.Password        = DataEncryptor.Encrypt(model.username);
            u.ConfirmPassword = DataEncryptor.Encrypt(model.username);
            u.Create_On       = DateUtil.Now();
            u.Create_By       = model.update_by;
            u.Update_On       = DateUtil.Now();
            u.Update_By       = model.update_by;
            u.isAdmin         = true;

            var staff = new Staff();

            staff.FirstName            = model.firstname;
            staff.LastName             = model.lastname;
            staff.Prefix               = model.prefix.toPrefix();
            staff.Address              = model.address;
            staff.Email                = model.email;
            staff.Phone                = model.phone;
            staff.Phone2               = model.phone2;
            staff.Passport             = model.passport;
            staff.IDCard               = model.idcard;
            staff.OpenDate             = DateUtil.ToDate(model.opendate);
            staff.ExpiryDate           = DateUtil.ToDate(model.expirydate);
            staff.Status               = model.status.toStatus();
            staff.Create_On            = DateUtil.Now();
            staff.Create_By            = model.update_by;
            staff.Update_On            = DateUtil.Now();
            staff.Update_By            = model.update_by;
            staff.isAdmin              = model.isadmin.HasValue ? model.isadmin.Value : false;
            staff.isMasterAdmin        = model.ismasteradmin.HasValue ? model.ismasteradmin.Value : false;
            staff.isQuestionAppr       = model.isquestionappr.HasValue ? model.isquestionappr.Value : false;
            staff.isMasterQuestionAppr = model.ismasterquestionappr.HasValue ? model.ismasterquestionappr.Value : false;
            staff.isTestAppr           = model.istestappr.HasValue ? model.istestappr.Value : false;
            staff.isMasterTestAppr     = model.ismastertestappr.HasValue ? model.ismastertestappr.Value : false;
            staff.User = u;

            _context.Staffs.Add(staff);
            _context.SaveChanges();

            username   = "******" + u.ID.ToString("0000");
            u.UserName = username;
            u.Password = DataEncryptor.Encrypt(u.UserName);
            _context.SaveChanges();

            return(CreatedAtAction(nameof(insert), new { result = ResultCode.Success, message = ResultMessage.Success }));
        }
コード例 #15
0
        public void JsonDeserialize(JsonElement jsonElement)
        {
            var json = jsonElement.GetRawText();

            formCreateViewModel = JsonSerializer.Deserialize <FormCreateViewModel>(json);
        }
コード例 #16
0
        /// <summary>
        /// Update a list from a given JSON array
        /// </summary>
        /// <param name="list">List to update</param>
        /// <param name="itemType">Item type</param>
        /// <param name="jsonElement">Element to update the intance from</param>
        /// <param name="ignoreSbcProperties">Whether SBC properties are ignored</param>
        /// <param name="offset">Index offset</param>
        /// <param name="last">Whether this is the last update call</param>
        public static void UpdateFromJson(IList list, Type itemType, JsonElement jsonElement, bool ignoreSbcProperties, int offset = 0, bool last = true)
        {
            int arrayLength = jsonElement.GetArrayLength();

            // Delete obsolete items when the last update has been processed
            if (last)
            {
                for (int i = list.Count; i > offset + arrayLength; i--)
                {
                    list.RemoveAt(i - 1);
                }
            }

            if (itemType.IsSubclassOf(typeof(ModelObject)))
            {
                // Update model items
                for (int i = offset; i < Math.Min(list.Count, offset + arrayLength); i++)
                {
                    ModelObject item     = (ModelObject)list[i];
                    JsonElement jsonItem = jsonElement[i - offset];
                    if (jsonItem.ValueKind == JsonValueKind.Null)
                    {
                        if (list[i] != null)
                        {
                            list[i] = null;
                        }
                    }
                    else if (item == null)
                    {
                        item    = (ModelObject)Activator.CreateInstance(itemType);
                        list[i] = item.UpdateFromJson(jsonItem, ignoreSbcProperties);
                    }
                    else
                    {
                        ModelObject updatedInstance = item.UpdateFromJson(jsonItem, ignoreSbcProperties);
                        if (updatedInstance != item)
                        {
                            list[i] = updatedInstance;
                        }
                    }
                }

                // Add missing items
                for (int i = list.Count; i < offset + arrayLength; i++)
                {
                    JsonElement jsonItem = jsonElement[i - offset];
                    if (jsonItem.ValueKind == JsonValueKind.Null)
                    {
                        list.Add(null);
                    }
                    else
                    {
                        ModelObject newItem = (ModelObject)Activator.CreateInstance(itemType);
                        newItem = newItem.UpdateFromJson(jsonElement[i], ignoreSbcProperties);
                        list.Add(newItem);
                    }
                }
            }
            else
            {
                // Update items
                for (int i = 0; i < Math.Min(list.Count, offset + arrayLength); i++)
                {
                    JsonElement jsonItem = jsonElement[i - offset];
                    if (jsonItem.ValueKind == JsonValueKind.Null)
                    {
                        if (list[i] != null)
                        {
                            list[i] = null;
                        }
                    }
                    else if (itemType == typeof(bool) && jsonItem.ValueKind == JsonValueKind.Number)
                    {
                        try
                        {
                            bool itemValue = Convert.ToBoolean(jsonItem.GetInt32());
                            if (!Equals(list[i], itemValue))
                            {
                                list[i] = itemValue;
                            }
                        }
                        catch (FormatException e)
                        {
                            throw new JsonException($"Failed to deserialize item type bool from JSON {jsonItem.GetRawText()}", e);
                        }
                    }
                    else
                    {
                        try
                        {
                            object itemValue = JsonSerializer.Deserialize(jsonItem.GetRawText(), itemType);
                            if (itemType.IsArray)
                            {
                                IList listItem = (IList)list[i], newItem = (IList)itemValue;
                                if (listItem == null || listItem.Count != newItem.Count)
                                {
                                    list[i] = itemValue;
                                }
                                else
                                {
                                    for (int k = 0; k < listItem.Count; k++)
                                    {
                                        if (!Equals(listItem[k], newItem[k]))
                                        {
                                            list[i] = itemValue;
                                            break;
                                        }
                                    }
                                }
                            }
                            else if (!Equals(list[i], itemValue))
                            {
                                list[i] = itemValue;
                            }
                        }
                        catch (JsonException e)
                        {
                            throw new JsonException($"Failed to deserialize item type {itemType.Name} from JSON {jsonItem.GetRawText()}", e);
                        }
                    }
                }

                // Add missing items
                for (int i = list.Count; i < offset + arrayLength; i++)
                {
                    JsonElement jsonItem = jsonElement[i - offset];
                    if (itemType == typeof(bool) && jsonItem.ValueKind == JsonValueKind.Number)
                    {
                        try
                        {
                            list.Add(Convert.ToBoolean(jsonItem.GetInt32()));
                        }
                        catch (FormatException e)
                        {
                            throw new JsonException($"Failed to deserialize item type bool from JSON {jsonItem.GetRawText()}", e);
                        }
                    }
                    else
                    {
                        try
                        {
                            object newItem = JsonSerializer.Deserialize(jsonItem.GetRawText(), itemType);
                            list.Add(newItem);
                        }
                        catch (JsonException e)
                        {
                            throw new JsonException($"Failed to deserialize item type {itemType.Name} from JSON {jsonItem.GetRawText()}", e);
                        }
                    }
                }
            }
        }
コード例 #17
0
        object ToObject(JsonElement element, Type returnType)
        {
            var json = element.GetRawText();

            return(JsonSerializer.Deserialize(json, returnType));
        }
コード例 #18
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            StringBuilder sb = new();

            sb.AppendLine("# Results");

            string[] resultDirectories = Directory.GetDirectories(ResultsDir);
            foreach (string directory in resultDirectories)
            {
                sb.AppendLine();

                string[] dirComponents = directory.Split('\\');
                string   specification = dirComponents[dirComponents.Length - 1];

                string[] specComponents = specification.Split("-");

                string numPocos      = specComponents[0].Split("_")[1];
                string numProps      = specComponents[1].Split("_")[1];
                bool   useAttributes = bool.Parse(specComponents[2].Split("_")[1]);
                string process       = specComponents[3].Split("_")[1];

                string processToDisplay = process == "Write"
                    ? "Serialize"
                    : "Deserialize";

                sb.AppendLine($"## {processToDisplay} | Num POCOs: {numPocos}, Num properties: {numProps}, Use attributes: {useAttributes}");

                sb.AppendLine();

                sb.AppendLine($"| Processor | Build time (ms) | Overhead start-up time (ms) | Serialization start-up time (ms) | Net start-up time (ms) | Private bytes (KB) |");
                sb.AppendLine($"|-|-|-|-|-|-|");

                string[] resultFiles = Directory.GetFiles(directory);

                foreach (string file in resultFiles)
                {
                    string[] fileComponents = file.Split('\\');
                    string   processor      = fileComponents[fileComponents.Length - 1];

                    string[] processorComponents = processor.Split('.');
                    string   processorName       = processorComponents[0];

                    using (FileStream stream = File.OpenRead(file))
                    {
                        using (JsonDocument dom = await JsonDocument.ParseAsync(stream))
                        {
                            JsonElement element = dom.RootElement.GetProperty("jobResults").GetProperty("jobs").GetProperty("application").GetProperty("results");

                            try
                            {
                                string buildTime                = GetDoubleAsStr(element.GetProperty("benchmarks/build-time").GetRawText());
                                string overheadStartupTime      = GetDoubleAsStr(element.GetProperty("benchmarks/start-time").GetRawText());
                                string serializationStartupTime = GetDoubleAsStr(element.GetProperty("application/elapsed-time").GetRawText());
                                string netStartupTime           = GetDoubleAsStr(element.GetProperty("application/net-start-time").GetRawText());
                                string privateBytes             = GetDoubleAsStr(element.GetProperty("runtime/private-bytes").GetRawText());

                                sb.AppendLine($@"| {processorName} | {buildTime} | {overheadStartupTime} | {serializationStartupTime} | {netStartupTime} | {privateBytes} |");
                            }
                            catch
                            {
                                Console.WriteLine("Error parsing results:");
                                Console.WriteLine(file);
                                Console.WriteLine(element.GetRawText());
                                return;
                            }
                        }
                    }
                }
            }

            //Console.WriteLine(sb.ToString());
            await File.WriteAllTextAsync(Path.Combine(ResultsDir, "Summary.md"), sb.ToString());
        }
コード例 #19
0
 /// <summary>
 /// Tries to deserialize an object serialized to JSON accoring to its type.
 /// Custom Extension method used to deserialize grouped data descriptors in this project.
 /// </summary>
 /// <typeparam name="T">Type to deserialize to</typeparam>
 /// <param name="element">The serialized object</param>
 /// <param name="options">Deserialization options. In the project this originates from - usually case-insensitive</param>
 /// <returns></returns>
 public static object Deserialize <T>(this JsonElement element, JsonSerializerOptions options = null)
 {
     return(JsonSerializer.Deserialize(element.GetRawText(), typeof(T), options));
 }
コード例 #20
0
 public static object ToObject(this JsonElement element, Type type)
 => JsonSerializer.Deserialize(element.GetRawText(), type, JsonHelper.DefaultChromiumJsonSerializerOptions);
コード例 #21
0
        public static T ToObject <T>(this JsonElement element, JsonSerializerOptions?serializerOptions = null) where T : new()
        {
            var json = element.GetRawText();

            return(JsonSerializer.Deserialize <T>(json, serializerOptions ?? JsonSettings.Default) ?? new T());
        }
コード例 #22
0
 public static T ToObject <T>(this JsonElement element)
 => JsonSerializer.Deserialize <T>(element.GetRawText(), JsonHelper.DefaultChromiumJsonSerializerOptions);
コード例 #23
0
 public static T ToObject <T>(this JsonElement element, JsonSerializerOptions options = null)
 => JsonSerializer.Deserialize <T>(element.GetRawText(), options ?? DefaultJsonSerializerOptions);
コード例 #24
0
 public string PostNewTravelLocation(string username, string travelplan, string travelroute, [FromBody] JsonElement value)
 {
     if (_userRepository.GetAllUsersShort().Where(u => u.UserName == username).Count() < 1)
     {
         return("Error: Unknown user");
     }
     else
     {
         User user = _userRepository.GetByName(username);
         if (user.Travelplans.Where(t => t.Name == travelplan).Count() < 1)
         {
             return("Error: Unknown travelplan");
         }
         if (user.Travelplans.Where(t => t.Name == travelplan).First().RouteList.Where(i => i.Name == travelroute).Count() < 1)
         {
             return("Error: Unknown travelroute");
         }
         TravelLocation response = JsonConvert.DeserializeObject <TravelLocation>(value.GetRawText());
         if (user.Travelplans.Where(t => t.Name == travelplan).First().RouteList.Where(i => i.Name == travelroute).First().Locations.Where(l => l.Name == response.Name).Count() > 0)
         {
             return("Error: TravelRoute already has this location");
         }
         user.Travelplans.Where(t => t.Name == travelplan).First().RouteList.Where(i => i.Name == travelroute).First().AddTravelLocation(response);
         _userRepository.Update(user);
         _userRepository.SaveChanges();
         return(response.Name + " succesfully added to " + username + "'s TravelRoute \"" + travelroute + "\"");
     }
 }
コード例 #25
0
 protected TObject GetId <TObject>(JsonElement id) =>
 typeof(TObject) == typeof(Guid) ? (TObject)(object)id.GetGuid() : JsonSerializer.Deserialize <TObject>(id.GetRawText());
コード例 #26
0
            private static async Task <TournamentApiResult> ParseTournamentApiResultAsync(string responseString, bool includeMatches, bool includeParticipants)
            {
                TournamentApiResult result = new TournamentApiResult();

                JsonElement rootElement = JsonDocument.Parse(responseString).RootElement;

                if (includeMatches)
                {
                    JsonElement matchesElement = rootElement.GetProperty("tournament").GetProperty("matches");

                    MemoryStream reader = new MemoryStream(Encoding.UTF8.GetBytes(matchesElement.GetRawText()));

                    MatchData[] matches = await JsonSerializer.DeserializeAsync <MatchData[]>(reader);

                    Match[] matchesResult = new Match[matches.Length];

                    for (int i = 0; i < matches.Length; i++)
                    {
                        matchesResult[i] = matches[i].Match;
                    }

                    result.Matches = matchesResult;
                }
                else
                {
                    result.Matches = null;
                }

                if (includeParticipants)
                {
                    JsonElement participantsElement = rootElement.GetProperty("tournament").GetProperty("participants");

                    MemoryStream      reader       = new MemoryStream(Encoding.UTF8.GetBytes(participantsElement.GetRawText()));
                    ParticipantData[] participants = await JsonSerializer.DeserializeAsync <ParticipantData[]>(reader);

                    Participant[] participantsResult = new Participant[participants.Length];

                    for (int i = 0; i < participants.Length; i++)
                    {
                        participantsResult[i] = participants[i].Participant;
                    }

                    result.Participants = participantsResult;
                }
                else
                {
                    result.Participants = null;
                }

                MemoryStream   stream         = new MemoryStream(Encoding.UTF8.GetBytes(responseString));
                TournamentData tournamentData = await JsonSerializer.DeserializeAsync <TournamentData>(stream);

                result.Tournament = tournamentData.Tournament;

                return(result);
            }
コード例 #27
0
        public override void SerializeObjectArray_WithCustomOptions()
        {
            IndexViewModel           index           = CreateIndexViewModel();
            CampaignSummaryViewModel campaignSummary = CreateCampaignSummaryViewModel();

            ITestContext context = SerializationContextWithCamelCase.Default;

            Assert.Same(JsonNamingPolicy.CamelCase, ((JsonSerializerContext)context).Options.PropertyNamingPolicy);

            string json = JsonSerializer.Serialize(new object[] { index, campaignSummary }, context.ObjectArray);

            object[] arr = JsonSerializer.Deserialize(json, ((ITestContext)MetadataWithPerTypeAttributeContext.Default).ObjectArray);

            JsonElement indexAsJsonElement           = (JsonElement)arr[0];
            JsonElement campaignSummeryAsJsonElement = (JsonElement)arr[1];

            ITestContext metadataContext = new MetadataContext(new JsonSerializerOptions {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            VerifyIndexViewModel(index, JsonSerializer.Deserialize(indexAsJsonElement.GetRawText(), metadataContext.IndexViewModel));
            VerifyCampaignSummaryViewModel(campaignSummary, JsonSerializer.Deserialize(campaignSummeryAsJsonElement.GetRawText(), metadataContext.CampaignSummaryViewModel));
        }
コード例 #28
0
        /// <summary>
        /// Optimized method to directly query the machine model UTF-8 JSON
        /// </summary>
        /// <param name="cancellationToken">Optional cancellation token</param>
        /// <returns>Machine model JSON</returns>
        /// <exception cref="OperationCanceledException">Operation has been cancelled</exception>
        /// <exception cref="SocketException">Command could not be processed</exception>
        /// <seealso cref="SbcPermissions.ObjectModelRead"/>
        /// <seealso cref="SbcPermissions.ObjectModelReadWrite"/>
        public async Task <string> GetSerializedObjectModel(CancellationToken cancellationToken = default)
        {
            JsonElement jsonDocument = await PerformCommand <JsonElement>(new GetObjectModel(), cancellationToken);

            return(jsonDocument.GetRawText());
        }
コード例 #29
0
        public dynamic Objectify(JsonElement graphson, GraphSONReader reader)
        {
            var bigInteger = graphson.ValueKind == JsonValueKind.String ? graphson.GetString() : graphson.GetRawText();

            return(BigInteger.Parse(bigInteger));
        }
コード例 #30
0
        public object upload([FromBody] JsonElement json)
        {
            var model = JsonConvert.DeserializeObject <ImportExamRegisterDTO>(json.GetRawText());

            if (model != null && model.fileupload != null)
            {
                var file = Convert.FromBase64String(model.fileupload.value);
                using (MemoryStream ms = new MemoryStream(file))
                {
                    using (ExcelPackage package = new ExcelPackage(ms))
                    {
                        if (package.Workbook.Worksheets.Count == 0)
                        {
                            return(CreatedAtAction(nameof(upload), new { result = ResultCode.InputHasNotFound, message = ResultMessage.InputHasNotFound }));
                        }
                        else
                        {
                            var worksheet = package.Workbook.Worksheets.First();
                            int totalRows = worksheet.Dimension.End.Row;
                            for (int i = 2; i <= totalRows; i++)
                            {
                                var txt = worksheet.Cells[i, 1].Text.ToString();
                                if (!string.IsNullOrEmpty(txt))
                                {
                                    var student = _context.Students.Where(w => w.StudentCode == txt).FirstOrDefault();
                                    if (student != null)
                                    {
                                        var examidint = NumUtil.ParseInteger(model.examid);
                                        var reged     = _context.ExamRegisters.Where(w => w.StudentID == student.ID & w.ExamID == examidint).FirstOrDefault();
                                        if (reged == null)
                                        {
                                            var register = new ExamRegister();
                                            register.StudentID        = student.ID;
                                            register.ExamID           = examidint;
                                            register.ExamRegisterType = ExamRegisterType.Advance;
                                            register.Create_On        = DateUtil.Now();
                                            register.Update_On        = DateUtil.Now();
                                            register.Create_By        = model.update_by;
                                            register.Update_By        = model.update_by;
                                            _context.ExamRegisters.Add(register);
                                        }
                                    }
                                }
                            }
                            _context.SaveChanges();
                            var examid = NumUtil.ParseInteger(model.examid);
                            var exam   = _context.Exams.Where(w => w.ID == examid).FirstOrDefault();
                            if (exam != null)
                            {
                                exam.Update_On   = DateUtil.Now();
                                exam.Update_By   = model.update_by;
                                exam.RegisterCnt = _context.ExamRegisters.Where(w => w.ExamID == examid).Count();
                                _context.SaveChanges();
                                return(CreatedAtAction(nameof(upload), new { result = ResultCode.Success, message = ResultMessage.Success, registercnt = exam.RegisterCnt }));
                            }
                        }
                    }
                }
            }
            return(CreatedAtAction(nameof(upload), new { result = ResultCode.InvalidInput, message = ResultMessage.InvalidInput }));
        }