public string HijackedCountsLine(string domainName, string start, string end) { var hijackedEvent = chartDataService.SingleDomainLineChart(domainName, Convert.ToDateTime(start), Convert.ToDateTime(end)).OrderBy(s => s.CreateDate); dynamic returnData = new ExpandoObject(); if (hijackedEvent.Any()) { try { var hijackedCountLineChart = this.HijackedCounts(hijackedEvent); var hijackedIspCount = this.IspHijackedCount(hijackedEvent); var hijackedDestinationCount = this.HijackedDestinationCounts(hijackedEvent); var hijackedDestinationEach = this.HijackedDestinationEach(hijackedEvent); var hijackeProvinceDns = this.HijackedProvinceCountDns(hijackedEvent); var hijackedProvinceHttp = this.HijackedProvinceCountHttp(hijackedEvent); var hijackedResolutionTime = this.ResolutionAverage(hijackedEvent); returnData.HijackedLine = hijackedCountLineChart; returnData.HijackedIspLinePie = hijackedIspCount; returnData.HijackedSmallPie = hijackedDestinationCount; returnData.HijackedBigPie = hijackedDestinationEach; returnData.HijackedProvinceDns = hijackeProvinceDns; returnData.HijackedProvinceHttp = hijackedProvinceHttp; returnData.HijackedResolutionTime = hijackedResolutionTime; } catch (Exception ex) { log.Error(ex); } } return(JsonConvert.SerializeObject(returnData)); }
public static void Save(string fileName, object value) { using (var sw = new System.IO.StreamWriter(fileName)) { sw.Write(JC.SerializeObject(value)); } }
public void given_the_matProcessData_domain_object_when_postInitialProcessDocument_gateway_method_is_called_then_the_number_of_documents_in_the_database_increases_by_one() //test that checks whether the db doesn't get cleared or overwritten somehow upon insertion { //arrange var unclearedDocumentCount = collection.CountDocuments(Builders <BsonDocument> .Filter.Empty); //did some testing around this, seems like the database doesn't get cleared after every test. Depending on the ordering, it might not actually be empty at the start of this test. When this is unaccounted for, it makes this test fail. //pre-insert between 0 and 7 documents into database, so that it wouldn't be necessarily empty (triangulation) int preInsertedDocumentCount = _faker.Random.Int(0, 7); for (int i = preInsertedDocumentCount; i > 0; i--) { MatProcessData preInsertedDomainObject = ProcessDataFactory.CreateProcessDataObject(MatProcessDataHelper.CreatePostInitialProcessDocumentRequestObject()); collection.InsertOne(BsonDocument.Parse(JsonConvert.SerializeObject(preInsertedDomainObject))); } //a new object that will be inserted upon gateway call MatProcessData toBeInsertedDomainObject = ProcessDataFactory.CreateProcessDataObject(MatProcessDataHelper.CreatePostInitialProcessDocumentRequestObject()); //act processDataGateway.PostInitialProcessDocument(toBeInsertedDomainObject); //assert var startingDocumentCount = unclearedDocumentCount + preInsertedDocumentCount; Assert.AreEqual(startingDocumentCount + 1, collection.CountDocuments(Builders <BsonDocument> .Filter.Empty)); }
public string DomainPermission() { string currentId = CurrentAccount.CustomerId; var domainList = new List <HijackingDomainDto>(); var allowedDomain = new List <DomainTag>(); try { if (currentId.Equals("TOFFSTECH")) { domainList = hijackingDomainService.GetAll(); } else { domainList = hijackingDomainService.Find(p => p.CustomerId.Equals(currentId)); } allowedDomain.AddRange(domainList.Select(s => new DomainTag { value = s.Protocol + s.Domain, text = s.Protocol + s.Domain })); } catch (Exception ex) { log.Error(ex); } return(JsonConvert.SerializeObject(allowedDomain)); }
public void test_that_object_can_be_successfully_updated() { //arrange MatProcessData processData = MatProcessDataHelper.CreateProcessDataObject(); var bsonObject = BsonDocument.Parse(JsonConvert.SerializeObject(processData)); collection.InsertOne(bsonObject); //object to update var objectToUpdate = new MatUpdateProcessData(); var processRef = processData.Id; objectToUpdate.DateLastModified = _faker.Date.Recent(); objectToUpdate.ProcessData = new { firstField = _faker.Random.Word(), anyField = _faker.Random.Words(), numberField = _faker.Random.Number() }; //get update definition var updateDefinition = UpdateProcessDocumentHelper.PrepareFieldsToBeUpdated(objectToUpdate); //act var result = processDataGateway.UpdateProcessData(updateDefinition, processRef); //assert Assert.AreEqual(processRef, result.Id); Assert.AreEqual(JsonConvert.SerializeObject(objectToUpdate.ProcessData), JsonConvert.SerializeObject(result.ProcessData)); Assert.AreEqual(objectToUpdate.DateLastModified.ToShortDateString(), result.DateLastModified.ToShortDateString()); Assert.IsInstanceOf <MatProcessData>(result); }
static void Main(string[] args) { People Haigang = GeneratePeople(); People xiaohong = new People(); xiaohong.Age = 16; People xiaoli = new People(); xiaoli.Age = 17; People xiaozhang = new People(); xiaozhang.Age = 20; PeopleCurRepository database = new PeopleCurRepository(); database.Add(Haigang); database.Add(xiaozhang); database.Add(xiaoli); database.Add(xiaohong); //序列化 Console.WriteLine(JsonConvert.SerializeObject(database.GetAll())); ////反序列化 //People Haigang2 = JsonConvert.DeserializeObject<People>("asdfafdadfa"); // Clone 深拷贝 //People Haigang2 = JsonConvert.DeserializeObject<People>(JsonConvert.SerializeObject(Haigang)); }
public void test_that_gateway_return_object_matches_object_in_database() { //arrange MatProcessData processData = MatProcessDataHelper.CreateProcessDataObject(); var bsonObject = BsonDocument.Parse(JsonConvert.SerializeObject(processData)); collection.InsertOne(bsonObject); //act var result = processDataGateway.GetProcessData(processData.Id); //assert Assert.AreEqual(processData.Id, result.Id); Assert.AreEqual(processData.ProcessType.value, result.ProcessType.value); Assert.AreEqual(processData.ProcessType.name, result.ProcessType.name); Assert.AreEqual(processData.DateCreated, result.DateCreated); Assert.AreEqual(processData.DateLastModified, result.DateLastModified); Assert.AreEqual(processData.DateCompleted, result.DateCompleted); Assert.AreEqual(processData.ProcessDataAvailable, result.ProcessDataAvailable); Assert.AreEqual(processData.ProcessDataSchemaVersion, result.ProcessDataSchemaVersion); Assert.AreEqual(processData.ProcessStage, result.ProcessStage); Assert.AreEqual(processData.LinkedProcessId, result.LinkedProcessId); Assert.AreEqual(processData.PreProcessData, result.PreProcessData); Assert.AreEqual(processData.ProcessData, result.ProcessData); Assert.AreEqual(processData.PostProcessData, result.PostProcessData); Assert.IsInstanceOf <MatProcessData>(result); }
public override object Serialize <T>(T value) { if (value == null) { return(null); } return(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(value, JsonSerializerSettings), value.GetType(), JsonSerializerSettings)); }
/// <summary> /// Save configuration to file. /// </summary> /// <param name="obj"></param> /// <param name="fileName"></param> /// <param name="appendFolder"></param> public static void SaveConfiguration(AppSettings obj, string fileName = DefaultConfigurationFile, bool appendFolder = true) { if (appendFolder) { fileName = Path.Combine(Environment.CurrentDirectory, fileName); } File.WriteAllText(fileName, JsonConvert.SerializeObject(obj, Formatting.Indented)); }
public override object Serialize <T>(T value) { if (value == null) { return(null); } return(JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(value, _jsonSerializerSettings))); }
public static BasicContentBlock ParseContentBlock(dynamic contentBlock) { var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; if (contentBlock != null) { try { Enum.TryParse <ContentBlockType>(contentBlock.type.Value.ToString(), out ContentBlockType contentBlockType); switch (contentBlockType) { case ContentBlockType.text: return(JsonConvert.DeserializeObject <TextContentBlock>(JsonConvert.SerializeObject(contentBlock, settings))); case ContentBlockType.image: if (contentBlock.HorizontalAlignment == "") { contentBlock.HorizontalAlignment = "Center"; } return(JsonConvert.DeserializeObject <ImageContentBlock>(JsonConvert.SerializeObject(contentBlock, settings))); case ContentBlockType.Remark: return(JsonConvert.DeserializeObject <RemarkContentBlock>(JsonConvert.SerializeObject(contentBlock, settings))); case ContentBlockType.function: var list = new List <BasicContentBlock>(); foreach (var content in contentBlock["contentBlocks"]) { list.Add(ParseContentBlock(content)); } var function = new FunctionContentBlock() { FunctionID = contentBlock["functionid"], FunctionName = contentBlock["title"], InputRange = contentBlock["inputRange"], Content = list }; return(function); case ContentBlockType.path: return(JsonConvert.DeserializeObject <PathContentBlock>(JsonConvert.SerializeObject(contentBlock, settings))); default: return(null); } } catch (Exception) { return(null); } } return(null); }
private BsonDocument ParseBson(AuditEvent auditEvent) { if (SerializeAsBson) { return(auditEvent.ToBsonDocument()); } else { return(BsonDocument.Parse(JsonConvert.SerializeObject(auditEvent, JsonSerializerSettings))); } }
/// <summary> /// 转为JSON字符串 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string AsJson(this object obj) { string result = string.Empty; try { result = NJJ.SerializeObject(obj); } catch { } return(result); }
private async Task <ImageResponse> UpdateImage(ImageUpdateDto image) { var content = new StringContent(JsonConvert.SerializeObject(image), Encoding.UTF8, "application/json"); var response = await _httpClient.PutAsync("v2/Images", content).ConfigureAwait(false); var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (!response.IsSuccessStatusCode) { throw new Exception($"Error in {nameof(UpdateImage)}. Status code: {response.StatusCode}. Error: {stringResponse}"); } return(JsonConvert.DeserializeObject <ImageResponse>(stringResponse)); }
private string serializeVariablesFromObject(Datapoint obj, int add_files = 0) { string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { ContractResolver = new UnderscorePropertyNamesContractResolver() }); //List<System.Reflection.PropertyInfo> problist = obj.GetType().GetProperties().ToList(); //List<String> newlist = problist.Select(x => x.Name).ToList(); //newlist.ForEach(x => json = json.Replace(x, x.ToUnderscoreCase())); json = "\"variables\": " + json; return(json.Replace("}", ",\"files\": [null, null] }")); }
private static string FormatEntity <T>(T entity, OperationType type) { var regex = new Regex("ISODate[(](.+?)[)]"); var result = JsonConvert.SerializeObject(new { Service = ServiceInfo.Name, OperationType = Enum.GetName(typeof(OperationType), type), Entity = entity, EntityType = typeof(T).Name, Date = DateTime.UtcNow }, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }); return(regex.Replace(result, "$1")); }
public override object Serialize <T>(T value) { if (value == null) { return(null); } if (SerializeAsBson) { if (value is BsonDocument) { return(value); } return(value.ToBsonDocument(typeof(object))); } else { return(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(value, JsonSerializerSettings), value.GetType(), JsonSerializerSettings)); } }
private static void AppendTypescript(ResourceNode node, StringBuilder typescript, HashSet <string> formatTemplates) { var text = node.Text ?? string.Empty; var key = node.Key; var value = JsonConvert.SerializeObject(text); var placeholders = ExtractPlaceholders(text).ToList(); if (placeholders.Any()) { formatTemplates.Add(key); var args = string.Join(", ", placeholders.Select(item => $@"{item}: string")); typescript.AppendLine($" private {key}{FormatTemplateSuffix} = {value};"); typescript.AppendLine($" {key} = (args: {{ {args} }}) => {{\r\n return formatString(this.{key}{FormatTemplateSuffix}, args);\r\n }}"); } else { typescript.AppendLine($@" {key} = {value};"); } }
void SaveLocalData(string sprintId, string comment) { try { IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.Machine, null, null); if (isoStore.FileExists(fileName)) { isoStore.DeleteFile(fileName); } using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.CreateNew, isoStore)) { using (StreamWriter writer = new StreamWriter(isoStream)) { writer.Write(JsonConvert.SerializeObject(new[] { sprintId, comment })); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
static public string CreateSession(string json) { var obj = JSON.DeserializeObject(json); json = JSON.SerializeObject(obj); // reduces request size using (HttpClient client = new HttpClient()) { var content1 = new ByteArrayContent(Encoding.UTF8.GetBytes(json)); content1.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); content1.Headers.Add("Content-Disposition", "form-data; name=\"config\"; filename=\"config.json\""); MultipartFormDataContent content2 = new MultipartFormDataContent(); content2.Add(content1, "config"); string q = content2.ReadAsStringAsync().Result; q = HttpUtility.UrlDecode(q); HttpResponseMessage response = client.PostAsync("http://fontello.com/", content2).Result; response.EnsureSuccessStatusCode(); return(response.Content.ReadAsStringAsync().Result); } }
/// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, IOneOf value) { var bsonDocument = BsonDocument.Parse(JsonConvert.SerializeObject(value, ActualType, JsonSerializerSettings)); context.Writer.WriteRawBsonDocument(new RawBsonDocument(bsonDocument.ToBson()).Slice); }
public static string GetString(object value) { return(JC.SerializeObject(value)); }
public string ToJson() { return(JsonC.SerializeObject(this, Formatting.Indented)); }
public static string ToCompactString(this JObject jobject) { return(JsonConvert.SerializeObject(jobject, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); }
private BsonDocument ParseBson(AuditEvent auditEvent) { return(BsonDocument.Parse(JsonConvert.SerializeObject(auditEvent, JsonSerializerSettings))); }