Example #1
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);
        }
Example #2
0
 public static T Read <T>(string fileName)
 {
     using (var sr = new System.IO.StreamReader(fileName))
     {
         return(JC.DeserializeObject <T>(sr.ReadToEnd()));
     }
 }
Example #3
0
 public override object Serialize <T>(T value)
 {
     if (value == null)
     {
         return(null);
     }
     return(JsonConvert.DeserializeObject <T>(JsonConvert.SerializeObject(value, _jsonSerializerSettings)));
 }
Example #4
0
 public override object Serialize <T>(T value)
 {
     if (value == null)
     {
         return(null);
     }
     return(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(value, JsonSerializerSettings), value.GetType(), JsonSerializerSettings));
 }
 /// <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)));
 }
Example #6
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));
        }
Example #7
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));
        }
Example #8
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);
        }
Example #9
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);
        }
Example #10
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);
        }
Example #11
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);
        }
Example #12
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));
        }
Example #13
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);
        }
Example #14
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);
        }
Example #15
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);
        }
Example #16
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);
        }
Example #17
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()));
        }
Example #18
0
 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));
     }
 }
Example #19
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);
        }
Example #20
0
        public async Task <Cities> GetCities()
        {
            var response = await _httpClient.GetAsync($"cities");

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

            var cities = JsonConvert.DeserializeObject <Cities>(result);

            if (!cities.Status)
            {
                // todo : throw an exception
            }

            return(cities);
        }
        //private readonly IdentityService _identityService;
        //private readonly ICurrencyProvider _currencyProvider;
        //private const string IDRCurrencyCode = "IDR";

        public DetailCreditBalanceReportFacade(IServiceProvider serviceProvider)
        {
            _dbContext = serviceProvider.GetService <PurchasingDbContext>();
            var cache               = serviceProvider.GetService <IDistributedCache>();
            var jsonUnits           = cache.GetString(MemoryCacheConstant.Units);
            var jsonCategories      = cache.GetString(MemoryCacheConstant.Categories);
            var jsonAccountingUnits = cache.GetString(MemoryCacheConstant.AccountingUnits);

            _units = JsonConvert.DeserializeObject <List <UnitDto> >(jsonUnits, new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore
            });

            _accountingUnits = JsonConvert.DeserializeObject <List <AccountingUnitDto> >(jsonAccountingUnits, new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore
            });

            _categories = JsonConvert.DeserializeObject <List <CategoryDto> >(jsonCategories, new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore
            });
        }
Example #22
0
        //REVISIONS

        private async Task <Revision> CreateRevision(string id, string description = "", string base64image = _newRevisionImageBase64)
        {
            var content = new MultipartFormDataContent();

            content.Add(new ByteArrayContent(Convert.FromBase64String(base64image)), "file", "file.png");
            content.Add(new StringContent(description), "description");
            content.Add(new StringContent(id), "imageId");
            content.Add(new StringContent(new ConfigurationManager(new LocalFile()).GetPassword()), "password");
            var response = await _httpClient.PostAsync("v2/Images/Revision", content).ConfigureAwait(false);

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

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

            var image    = JsonConvert.DeserializeObject <ImageResponse>(stringResponse);
            var revision = image.Image.Revisions.OrderByDescending(x => x.RevisionDate).First();

            RevisionToDelete.Add(new Tuple <string, string>(id, revision.RevisionId));
            return(revision);
        }
    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);
        }
    }
Example #24
0
 public static ClientConfig FromJson(string str)
 {
     return(JsonC.DeserializeObject <ClientConfig>(str));
 }
Example #25
0
 public static T GetObject <T>(string text)
 {
     return(JC.DeserializeObject <T>(text));
 }
Example #26
0
 public static object GetObject(string text)
 {
     return(JC.DeserializeObject(text));
 }
Example #27
0
        private void Export()
        {
            try
            {
                var solutionFolder = _resourceManager.SolutionFolder;
                if (solutionFolder == null)
                {
                    return;
                }

                var configFilePath = Path.Combine(solutionFolder, "resx-manager.webexport.config");
                if (!File.Exists(configFilePath))
                {
                    return;
                }

                var config = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText(configFilePath));

                var typeScriptFileDir = config.TypeScriptFileDir;
                var jsonFileDir       = config.JsonFileDir;

                if (string.IsNullOrEmpty(typeScriptFileDir) || string.IsNullOrEmpty(jsonFileDir))
                {
                    return;
                }

                typeScriptFileDir = Directory.CreateDirectory(Path.Combine(solutionFolder, typeScriptFileDir)).FullName;
                jsonFileDir       = Directory.CreateDirectory(Path.Combine(solutionFolder, jsonFileDir)).FullName;

                var typescript  = new StringBuilder(TypescriptFileHeader);
                var jsonObjects = new Dictionary <CultureKey, JObject>();

                foreach (var entity in _resourceManager.ResourceEntities)
                {
                    var formatTemplates = new HashSet <string>();

                    var entityName      = entity.BaseName;
                    var neutralLanguage = entity.Languages.FirstOrDefault();
                    if (neutralLanguage == null)
                    {
                        continue;
                    }

                    typescript.AppendLine($@"export class {entityName} {{");

                    foreach (var node in neutralLanguage.GetNodes())
                    {
                        AppendTypescript(node, typescript, formatTemplates);
                    }

                    typescript.AppendLine(@"}");
                    typescript.AppendLine();

                    foreach (var language in entity.Languages.Skip(config.ExportNeutralJson ? 0 : 1))
                    {
                        var node = new JObject();

                        foreach (var resourceNode in language.GetNodes())
                        {
                            var key = resourceNode.Key;
                            if (formatTemplates.Contains(key))
                            {
                                key += FormatTemplateSuffix;
                            }

                            node.Add(key, JToken.FromObject(resourceNode.Text));
                        }

                        jsonObjects
                        .ForceValue(language.CultureKey, _ => GenerateJsonObjectWithComment())?
                        .Add(entityName, node);
                    }
                }

                var typeScriptFilePath = Path.Combine(typeScriptFileDir, "resources.ts");
                File.WriteAllText(typeScriptFilePath, typescript.ToString());

                foreach (var jsonObjectEntry in jsonObjects)
                {
                    var key   = jsonObjectEntry.Key;
                    var value = jsonObjectEntry.Value.ToString();

                    var jsonFilePath = Path.Combine(jsonFileDir, $"resources{key}.json");
                    File.WriteAllText(jsonFilePath, value);
                }
            }
            catch (Exception ex)
            {
                _tracer.TraceError(ex.ToString());
            }
        }