예제 #1
0
 public static void Save(string fileName, object value)
 {
     using (var sw = new System.IO.StreamWriter(fileName))
     {
         sw.Write(JC.SerializeObject(value));
     }
 }
        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));
        }
예제 #3
0
 public static T Read <T>(string fileName)
 {
     using (var sr = new System.IO.StreamReader(fileName))
     {
         return(JC.DeserializeObject <T>(sr.ReadToEnd()));
     }
 }
예제 #4
0
파일: Program.cs 프로젝트: hellohaigang/OOP
        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_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);
        }
        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 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));
        }
예제 #8
0
        //HELPERS

        //IMAGE

        private async Task <ImageResponse> CreateNewImage(string tags = "image", string imageBase64 = _newImageBase64)
        {
            var content = new MultipartFormDataContent();

            content.Add(new ByteArrayContent(Convert.FromBase64String(imageBase64)), "file", "file.png");
            content.Add(new StringContent(_newImage.title), "title");
            content.Add(new StringContent(_newImage.description ?? string.Empty), "description");
            content.Add(new StringContent(tags), "tags");
            content.Add(new StringContent(_newImage.date ?? string.Empty), "date");
            content.Add(new StringContent(_newImage.annotation ?? string.Empty), "annotation");
            content.Add(new StringContent(_newImage.inverted ?? string.Empty), "inverted");
            content.Add(new StringContent(new ConfigurationManager(new LocalFile()).GetPassword()), "password");
            var response = await _httpClient.PostAsync("v2/Images", content).ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"Error in {nameof(CreateNewImage)}. Status code: {response.StatusCode}");
            }

            var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var savedImage = JsonConvert.DeserializeObject <ImageResponse>(stringResponse);

            ImagesToDelete.Add(savedImage.Image.Id);
            return(savedImage);
        }
        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));
        }
예제 #10
0
 /// <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));
 }
예제 #11
0
 /// <summary>
 /// Load configuration from file.
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="appendFolder"></param>
 /// <returns></returns>
 public static AppSettings LoadConfiguration(string fileName = DefaultConfigurationFile, bool appendFolder = true)
 {
     if (appendFolder)
     {
         fileName = Path.Combine(Environment.CurrentDirectory, fileName);
     }
     return(JsonConvert.DeserializeObject <AppSettings>(File.ReadAllText(fileName)));
 }
예제 #12
0
 public override object Serialize <T>(T value)
 {
     if (value == null)
     {
         return(null);
     }
     return(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(value, JsonSerializerSettings), value.GetType(), JsonSerializerSettings));
 }
예제 #13
0
 public override object Serialize <T>(T value)
 {
     if (value == null)
     {
         return(null);
     }
     return(JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(value, _jsonSerializerSettings)));
 }
예제 #14
0
        public override async Task <T> GetEventAsync <T>(object eventId)
        {
            var client = new MongoClient(_connectionString);
            var db     = client.GetDatabase(_database);
            var filter = Builders <BsonDocument> .Filter.Eq("_id", (BsonObjectId)eventId);

            var doc = await(await db.GetCollection <BsonDocument>(_collection).FindAsync(filter)).FirstOrDefaultAsync();

            return(doc == null ? null : JsonConvert.DeserializeObject <T>(doc.ToJson(_jsonWriterSettings), _jsonSerializerSettings));
        }
예제 #15
0
        // public methods
        /// <summary>
        /// Deserializes a value.
        /// </summary>
        /// <param name="context">The deserialization context.</param>
        /// <param name="args">The deserialization args.</param>
        /// <returns>A deserialized value.</returns>
        public override IOneOf Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var serializer = BsonSerializer.LookupSerializer(typeof(BsonDocument));

            var oneOfContainer = (BsonDocument)serializer.Deserialize(context, args);

            var json = oneOfContainer.ToJson();

            return((IOneOf)JsonConvert.DeserializeObject(json, ActualType, JsonSerializerSettings));
        }
예제 #16
0
        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);
        }
예제 #17
0
 private BsonDocument ParseBson(AuditEvent auditEvent)
 {
     if (SerializeAsBson)
     {
         return(auditEvent.ToBsonDocument());
     }
     else
     {
         return(BsonDocument.Parse(JsonConvert.SerializeObject(auditEvent, JsonSerializerSettings)));
     }
 }
예제 #18
0
        //public async Task CacheDataAsync<T>(
        //    IEnumerable<T> items,
        //    Func<T, string> keyExtractor,
        //    string prefix)
        //{
        //    var tasks = new List<Task>();
        //    foreach (var item in items)
        //    {
        //        var key = keyExtractor(item);
        //        tasks.Add(Task.Run(async () =>
        //        {
        //            var cacheKey = GetCacheKey($"{prefix}:{key}");
        //            if (!await _redisDatabase.KeyExistsAsync(cacheKey))
        //                await _redisDatabase.StringSetAsync(cacheKey, CacheSerializer.Serialize(item), _expiration);
        //        }));
        //        if (tasks.Count >= MaxConcurrentTasksCount)
        //        {
        //            await Task.WhenAll(tasks);
        //            tasks.Clear();
        //        }
        //    }
        //    if (tasks.Count > 0)
        //        await Task.WhenAll(tasks);
        //}

        public async Task CacheDataAsync <Y>(string key, IEnumerable <Y> items)
        {
            lock (_dataList)
            {
                var json = items.ToJson();
                var data = JsonConvert.DeserializeObject <List <T> >(json);
                _dataList[GetCacheKey(key)] = data;
                CacheItemCount.WithLabels(_name, "list-item").Set(_dataList.Count);
            }

            //return _redisDatabase.StringSetAsync(GetCacheKey(key), CacheSerializer.Serialize(items), _expiration);
        }
예제 #19
0
        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));
        }
예제 #20
0
        /// <summary>
        /// 转为实体类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T To <T>(this string json) where T : class
        {
            T t = default(T);

            try
            {
                t = NJJ.DeserializeObject <T>(json);
            }
            catch
            {
            }

            return(t);
        }
예제 #21
0
        /// <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);
        }
예제 #22
0
        public async Task <Neighborhoods> GetAllNeighborhoods(int skip)
        {
            var response = await _httpClient.GetAsync($"neighborhoods?limit=100&skip={skip}");

            if (!response.IsSuccessStatusCode)
            {
                //todo : throw exception
            }
            var result = await response.Content.ReadAsStringAsync();

            var neighborhoods = JsonConvert.DeserializeObject <Neighborhoods>(result);

            return(neighborhoods);
        }
예제 #23
0
        public async Task <Neighborhoods> GetNeighborhoods(string districtId)
        {
            var response = await _httpClient.GetAsync($"towns/{districtId}/neighborhoods");

            if (!response.IsSuccessStatusCode)
            {
                //todo : throw exception
            }
            var result = await response.Content.ReadAsStringAsync();

            var neighborhoods = JsonConvert.DeserializeObject <Neighborhoods>(result);

            return(neighborhoods);
        }
예제 #24
0
        public async Task <Districts> GetDistricts(string townId)
        {
            var response = await _httpClient.GetAsync($"towns/{townId}/districts");

            if (!response.IsSuccessStatusCode)
            {
                //todo : throw exception
            }
            var result = await response.Content.ReadAsStringAsync();

            var districts = JsonConvert.DeserializeObject <Districts>(result);

            return(districts);
        }
예제 #25
0
        public async Task <Towns> GetTowns(string cityId)
        {
            var response = await _httpClient.GetAsync($"cities/{cityId}/towns");

            if (!response.IsSuccessStatusCode)
            {
                //todo : throw exception
            }
            var result = await response.Content.ReadAsStringAsync();

            var towns = JsonConvert.DeserializeObject <Towns>(result);

            return(towns);
        }
예제 #26
0
        private async Task <ImageResponse> GetImage(string imageId)
        {
            var response = await _httpClient.GetAsync($"v2/Images/{imageId}").ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"Error in {nameof(GetImage)}. Status code: {response.StatusCode}");
            }

            var responseJson = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var responseImage = JsonConvert.DeserializeObject <ImageResponse>(responseJson);

            return(responseImage);
        }
예제 #27
0
        public async Task GetFeaturedImageReturnsTheOneThatWasSet()
        {
            var password     = new ConfigurationManager(new LocalFile()).GetPassword();
            var imageId      = ObjectId.GenerateNewId();
            var postResponse = await _httpClient.PostAsync($"v2/Images/Featured/{imageId}/{password}", new StringContent("")).ConfigureAwait(false);

            var getResponse = await _httpClient.GetAsync($"v2/Images/Featured").ConfigureAwait(false);

            var json = await getResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            var featuredImage = JsonConvert.DeserializeObject <FeaturedImageViewModel>(json);

            Assert.That(postResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(getResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(featuredImage.ImageId, Is.EqualTo(imageId.ToString()));
        }
예제 #28
0
        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] }"));
        }
예제 #29
0
        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"));
        }
예제 #30
0
        //Deserializes the JSON to a.NET object

        public static List <BasicContentBlock> ParseContentBlocksFromJson(string listContentBlockJson)
        {
            var     contentBlockList = new List <BasicContentBlock>();
            dynamic jObject          = JsonConvert.DeserializeObject(listContentBlockJson);
            var     startPosition    = jObject;

            if (listContentBlockJson.Contains("contentBlocks"))
            {
                startPosition = jObject["contentBlocks"];
            }


            foreach (var contentBlock in startPosition)
            {
                contentBlockList.Add(ParseContentBlock(contentBlock));
            }

            return(contentBlockList);
        }
예제 #31
0
 public void DelFeedBackLog()
 {
     try
     {
         string ids = _request["IDs"];
         if (!string.IsNullOrWhiteSpace(ids))
         {
             List<string> list = ids.Split(',').ToList<string>();
             foreach (string id in list)
             {
                 _feedBackLogBll.Delete(id.ToInt32(0));
             }
             JsonConvert<string> jc = new JsonConvert<string>();
             _response.Write(jc.ToStatus(1));
         }
     }
     catch (Exception ex)
     {
         ErrorHandler.ExceptionHandlerForWeb("FeedBackLogAjax.DelFeedBackLog", ex.ToString());
         _response.Write("保存失败!");
     }
 }
예제 #32
0
 public void GetFeedBackLog()
 {
     Expression<Func<FeedBackLog, bool>> exp = GetCondition();
     List<FeedBackLog> list = _feedBackLogBll.FindAll(_rows, _page, exp).ToList();
     int count = _feedBackLogBll.GetCount(exp);
     JsonConvert<FeedBackLog> jc = new JsonConvert<FeedBackLog>();
     _response.Write(jc.ToDataGrid(list, count));
 }
예제 #33
0
        public void SaveFeedBackLog()
        {
            try
            {
                FeedBackLog fb;
                JsonConvert<string> jc = new JsonConvert<string>();
                if(_request["Mode"]=="1")
                {
                    fb = new FeedBackLog();
                }
                else
                {
                    fb=_feedBackLogBll.FindByID(_request["ID"].ToInt32(0));
                }

                if (fb != null)
                {
                    fb.KfZrr = _request["KfZrr"];
                    fb.IsKfCl = _request["IsKfCl"];
                    fb.FeedBackDate = _request["FeedBackDate"].ToDateTime(DateTime.Now);
                    fb.CstName = _request["CstName"];
                    fb.CsYzResult = _request["CsYzResult"];
                    fb.EndDate = _request["EndDate"].ToDateTime(DateTime.Now);
                    fb.CsZrr = _request["CsZrr"];
                    fb.FeedBackContent = _request["FeedBackContent"];
                    fb.KfClDate = _request["KfClDate"];
                    fb.TaskNo = _request["TaskNo"];
                    fb.Wtyy = _request["Wtyy"];
                }

                if (_request["Mode"] == "1")
                {
                    _feedBackLogBll.Add(fb);
                    _response.Write(jc.ToStatus(1));
                }
                else
                {
                    _feedBackLogBll.Update(fb);
                    _response.Write(jc.ToStatus(1));
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.ExceptionHandlerForWeb("FeedBackLogAjax.SaveFeedBackLog", ex.ToString());
                _response.Write("保存失败!");
            }
        }