Example #1
0
        public async Task SerializeAsync()
        {
            var serializer = new JsonSerializer();
            var obj = new TestEntity
                          {
                              Name = "John Doe"
                          };
            var serializedObj = await serializer.SerializeAsync(obj);

            Assert.AreEqual(@"{""$type"":""Kephas.Serialization.Json.Tests.JsonSerializerTest+TestEntity, Kephas.Serialization.Json.Tests"",""name"":""John Doe""}", serializedObj);
        }
Example #2
0
        public async static Task <bool> WriteToJsonFile(string rulesetsDirectory, string fileName, JsonRuleset ruleset)
        {
            var path = fileName.EndsWith(".json") ? $"{rulesetsDirectory}\\{fileName}" : $"{rulesetsDirectory}\\{fileName}.json";

            try
            {
                using (FileStream fileStream = File.Create(path))
                {
                    var options = new JsonSerializerOptions
                    {
                        WriteIndented = true
                    };

                    await JsonSerializer.SerializeAsync(fileStream, ruleset, options);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #3
0
        private static async Task RequestBenchmark(PullRequest pr, string newJobFileName)
        {
            await using var baseJobStream = File.OpenRead(BaseJobPath);

            var jsonDictionary = await JsonSerializer.DeserializeAsync <Dictionary <string, object> >(baseJobStream);

            jsonDictionary["BuildInstructions"] = new BuildInstructions
            {
                BuildCommands  = BuildCommands,
                BaselineSHA    = pr.Base.Sha,
                PullRequestSHA = pr.Head.Sha,
            };

            using var newJobStream = new MemoryStream();
            await JsonSerializer.SerializeAsync(newJobStream, jsonDictionary, new JsonSerializerOptions
            {
                WriteIndented = true,
            });

            newJobStream.Position = 0;

            await JobFileSystem.WriteFile(newJobStream, newJobFileName);
        }
Example #4
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });

                endpoints.MapPost("/list", async context =>
                {
                    context.Response.ContentType = "application/json";
                    await JsonSerializer.SerializeAsync(context.Response.Body, AllProducts, options: options);
                });
            });
        }
Example #5
0
        /// <summary>
        /// Asynchronously creates a registry image which contains a <see cref="DeveloperDisk"/>.
        /// </summary>
        /// <param name="developerDisk">
        /// The <see cref="DeveloperDisk"/> for which to create the image.
        /// </param>
        /// <param name="cancellationToken">
        /// A <see cref="CancellationToken"/> which can be used to cancel the asynchronous operation.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> which represents the asynchronous operation, and, when completed, returns the image manifest,
        /// image configuration and RootFS layer for the registry image containing the devleoper disk image.
        /// </returns>
        public async Task <(Manifest manifest, Stream configStream, Stream layer)> CreateRegistryImageAsync(DeveloperDisk developerDisk, CancellationToken cancellationToken)
        {
            if (developerDisk == null)
            {
                throw new ArgumentNullException(nameof(developerDisk));
            }

            var layer = await CreateLayerAsync(developerDisk, cancellationToken);

            var layerDescriptor = await Descriptor.CreateAsync(layer, "application/vnd.oci.image.layer.nondistributable.v1.tar", cancellationToken).ConfigureAwait(false);

            var    config       = CreateConfig(layerDescriptor.Digest);
            Stream configStream = new MemoryStream();
            await JsonSerializer.SerializeAsync(configStream, config, cancellationToken : cancellationToken).ConfigureAwait(false);

            configStream.Seek(0, SeekOrigin.Begin);

            var configDescriptor = await Descriptor.CreateAsync(configStream, "application/vnd.oci.image.config.v1+json", cancellationToken).ConfigureAwait(false);

            var manifest = CreateManifest(configDescriptor, layerDescriptor, developerDisk);

            return(manifest, configStream, layer);
        }
Example #6
0
        static async Task Main(string[] args)
        {
            string archivePath = args.Length > 0?args[0]:"ArchiveUsageRecords.json";

            using Stream stream = File.OpenRead(archivePath);
            ArchiveUsageRecord[] archiveItems = (await JsonSerializer.DeserializeAsync <ArchiveUsageRecord[]>(stream)) !;

            string outputPath = args.Length > 1?args[1]:"OutputUsageRecords.json";

            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }
            using Stream outputStream = File.OpenWrite(outputPath);
            MigrationService          migrationService = new();
            IEnumerable <UsageRecord> items            = migrationService.Convert(archiveItems);

            await JsonSerializer.SerializeAsync <IEnumerable <UsageRecord> >(outputStream, items, new JsonSerializerOptions {
                WriteIndented = true
            });

            Console.WriteLine("Convert Done");
        }
Example #7
0
        // TODO: fix rewrite behavior
        public async Task Initialize()
        {
            Option = new WorkspaceOption();
            DB     = new DB();
            await Save();

            FSBuilder builder = new FSBuilder(Environment.CurrentDirectory);

            builder.EnsureDirectoryExists("posts");
            builder.EnsureDirectoryExists("pages");
            builder.EnsureDirectoryExists("layouts");
            builder.EnsureDirectoryExists(AssetsPath);

            {
                await using var st = builder.GetFileRewriteStream(BlogOptionPath);
                await JsonSerializer.SerializeAsync(st, new BlogOptions(), options : new JsonSerializerOptions
                {
                    WriteIndented = true
                });
            }

            await Clean();
        }
Example #8
0
        public static async Task ChangePasswordRequirement(User user)
        {
            Console.WriteLine("Enter User Name");
            string userName = Console.ReadLine();

            using (FileStream fs = new FileStream("user.json", FileMode.OpenOrCreate))
            {
                List <User> restoredUsers = await JsonSerializer.DeserializeAsync <List <User> >(fs);

                fs.SetLength(0); foreach (User item in restoredUsers)
                {
                    Console.WriteLine($"Login: {item.Login},Type of user: {item.Type},Is banned: {item.BanStatus},has password requirements: {item.PasswordRequirement}");
                }
                restoredUsers.Where(x => x.Login == userName).ToList().ForEach(b => b.PasswordRequirement = 1);
                User newUser = restoredUsers.Find(i => i.Login == user.Login);
                await JsonSerializer.SerializeAsync <List <User> >(fs, restoredUsers);

                Console.ReadLine();
                Console.Clear();
                fs.Close();
                AdminCanDo(newUser);
            }
        }
Example #9
0
        internal static Task InvokeAsync(HttpContext context)
        {
            var service = context.RequestServices;
            var logger  = service.GetRequiredService <ILogger <GetAllThings> >();
            var things  = service.GetRequiredService <IEnumerable <Thing> >();

            logger.LogDebug("Verify if Things have prefix");
            foreach (var thing in things)
            {
                if (thing.Prefix == null)
                {
                    logger.LogDebug("Thing without prefix. [Name: {name}]", thing.Name);
                    thing.Prefix = new Uri(UriHelper.BuildAbsolute(context.Request.Scheme,
                                                                   context.Request.Host));
                }
            }

            logger.LogTrace("Found {counter} things", things.Count());
            context.Response.StatusCode  = (int)HttpStatusCode.OK;
            context.Response.ContentType = Const.ContentType;

            return(JsonSerializer.SerializeAsync(context.Response.Body, things, ThingConverter.Options, context.RequestAborted));
        }
Example #10
0
        public async Task <Document> Protect(Document value, ProtectionKey key, CancellationToken cancellationToken = default)
        {
            try
            {
                var    res = new Document();
                byte[] bs;
                await using (var ms = new MemoryStream())
                {
                    await JsonSerializer.SerializeAsync(ms, value, cancellationToken : cancellationToken);

                    bs = ms.ToArray();
                }

                res.Tag = _protectFlag;
                // var ky = Encoding.UTF8.GetBytes(key.Password); AesEncrypt(bs, ky)
                res.Raw = Convert.ToBase64String(bs);
                return(res);
            }
            catch (Exception ex)
            {
                throw new ProtectionException("Protect failed.", ex);
            }
        }
Example #11
0
        private static async Task PerformSerialization <TElement>(object obj, Type type, JsonSerializerOptions options)
        {
            string expectedjson = JsonSerializer.Serialize(obj, options);

            using var memoryStream = new MemoryStream();
            await JsonSerializer.SerializeAsync(memoryStream, obj, options);

            string serialized = Encoding.UTF8.GetString(memoryStream.ToArray());

            JsonTestHelper.AssertJsonEqual(expectedjson, serialized);

            memoryStream.Position = 0;

            if (options.ReferenceHandler == null || !GetTypesNonRoundtrippableWithReferenceHandler().Contains(type))
            {
                await TestDeserialization <TElement>(memoryStream, expectedjson, type, options);

                // Deserialize with extra whitespace
                string jsonWithWhiteSpace = GetPayloadWithWhiteSpace(expectedjson);
                using var memoryStreamWithWhiteSpace = new MemoryStream(Encoding.UTF8.GetBytes(jsonWithWhiteSpace));
                await TestDeserialization <TElement>(memoryStreamWithWhiteSpace, expectedjson, type, options);
            }
        }
Example #12
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (ValidationException validationException)
            {
                var errors = validationException.Errors
                             .Select(e => new Error {
                    Property = e.PropertyName, ErrorMessage = e.ErrorMessage
                })
                             .ToArray();

                context.Response.StatusCode = 400;

                context.Response.Headers.Add("content-type", "application/json");

                await JsonSerializer.SerializeAsync(context.Response.Body, errors, errors.GetType(), null, context.RequestAborted);

                await context.Response.Body.FlushAsync(context.RequestAborted);
            }
        }
        public async Task <bool> WriteToStorage()
        {
            var tempEntries = Entries.ConvertAll(entry => (FormYear)entry);

            try
            {
                tempEntries.ForEach(entry =>
                {
                    entry.JsonCoursUUID = entry.Courses.ConvertAll(course => course.UUID);
                });

                await using FileStream fs = File.Open(filePath, FileMode.Create, FileAccess.Write);

                var options = new JsonSerializerOptions {
                    WriteIndented = true
                };

                await JsonSerializer.SerializeAsync(fs, tempEntries, options);
            }
            catch (Exception) { return(false); }

            return(true);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async(context) =>
                {
                    context.Response.StatusCode = StatusCodes.Status200OK;
                    await JsonSerializer.SerializeAsync(context.Response.Body, new { Message = "We are here..." });
                });
                endpoints.MapControllers();
            });
        }
Example #15
0
        public async Task AddSurveyResponse(SurveyResponse response)
        {
            var filePath = _configuration.GetValue <string>("Survey:FilePath");

            using var stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            var responses = new List <SurveyResponse>();

            try
            {
                responses = await JsonSerializer.DeserializeAsync <List <SurveyResponse> >(stream);
            }
            catch
            {
                // broken json, or empty file. We don't care.
            }
            finally
            {
                responses.Add(response);
            }

            stream.Seek(0, SeekOrigin.Begin);
            await JsonSerializer.SerializeAsync(stream, responses);
        }
Example #16
0
        public static void SerializedToJson()
        {
            Console.WriteLine($"===========Attributes example(HW10 SerializedToJson)============");

            Console.WriteLine("Create new object exampleClass");
            ExampleClass exampleClass = new ExampleClass {
                ClassName = "ExampleClass1"
            };

            exampleClass.MyClassExec();
            exampleClass.UpdateExecDate(new DateTime(2020, 01, 01));
            exampleClass.MyClassExec();

            using (FileStream stream = new FileStream(@"D:\ExampleClass.txt", FileMode.OpenOrCreate))
            {
                JsonSerializer.SerializeAsync <ExampleClass>(stream, exampleClass,
                                                             new JsonSerializerOptions {
                    IncludeFields = true
                });
            }

            Console.WriteLine("Object was serialized to Json");
        }
        public async Task WithJsonSchemaGeneratorSettingsSerDe(EnumHandling enumHandling, EnumType value, string expectedJson)
        {
            var jsonSchemaGeneratorSettings = new JsonSchemaGeneratorSettings
            {
                DefaultEnumHandling = enumHandling
            };

            var jsonSerializer   = new JsonSerializer <EnumObject>(schemaRegistryClient, jsonSchemaGeneratorSettings: jsonSchemaGeneratorSettings);
            var jsonDeserializer = new JsonDeserializer <EnumObject>(jsonSchemaGeneratorSettings: jsonSchemaGeneratorSettings);

            var v = new EnumObject {
                Value = value
            };
            var bytes = await jsonSerializer.SerializeAsync(v, new SerializationContext(MessageComponentType.Value, testTopic));

            Assert.NotNull(bytes);
            Assert.Equal(expectedJson, Encoding.UTF8.GetString(bytes.AsSpan().Slice(5)));

            var actual = await jsonDeserializer.DeserializeAsync(bytes, false, new SerializationContext(MessageComponentType.Value, testTopic));

            Assert.NotNull(actual);
            Assert.Equal(actual.Value, value);
        }
Example #18
0
        public async Task GetCryptoData(string apiKey)
        {
            var coinApiClient = new CoinApiRestClient(apiKey);
            var result        = await coinApiClient.Metadata_list_assetsAsync();

            var mappedResult = _mapper.Map <List <CryptoCoin> >(result);

            if (mappedResult is null)
            {
                return;
            }

            foreach (var crypto in mappedResult)
            {
                crypto.Id = Guid.NewGuid()
                            .ToString();
            }

            var filePath = Path.Join(_currentDir, "Data", "Static", "CryptoCoins.json");

            await using var stream = File.Create(filePath);
            await JsonSerializer.SerializeAsync(stream, mappedResult);
        }
        public static Task WriteAsJsonAsync(
            this HttpResponse response,
            object?value,
            Type type,
            JsonSerializerOptions?options,
            string?contentType,
            CancellationToken cancellationToken = default)
        {
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            options ??= ResolveSerializerOptions(response.HttpContext);

            response.ContentType = contentType ?? JsonConstants.JsonContentTypeWithCharset;
            response.StatusCode  = StatusCodes.Status200OK;
            return(JsonSerializer.SerializeAsync(response.Body, value, type, options, cancellationToken));
        }
Example #20
0
        public static async Task RunAsync()
        {
            string          fileName        = "WeatherForecastAsync.json";
            WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();

            weatherForecast.DisplayPropertyValues();

            // <SnippetSerialize>
            using (FileStream fs = File.Create(fileName))
            {
                await JsonSerializer.SerializeAsync(fs, weatherForecast);
            }
            // </SnippetSerialize>
            Console.WriteLine($"The result is in {fileName}\n");

            // <SnippetDeserialize>
            using (FileStream fs = File.OpenRead(fileName))
            {
                weatherForecast = await JsonSerializer.DeserializeAsync <WeatherForecast>(fs);
            }
            // </SnippetDeserialize>
            weatherForecast.DisplayPropertyValues();
        }
    public static Task WriteAsJsonAsync <TValue>(
        this HttpResponse response,
        TValue value,
        JsonSerializerOptions?options,
        string?contentType,
        CancellationToken cancellationToken = default)
    {
        if (response == null)
        {
            throw new ArgumentNullException(nameof(response));
        }

        options ??= ResolveSerializerOptions(response.HttpContext);

        response.ContentType = contentType ?? JsonConstants.JsonContentTypeWithCharset;
        // if no user provided token, pass the RequestAborted token and ignore OperationCanceledException
        if (!cancellationToken.CanBeCanceled)
        {
            return(WriteAsJsonAsyncSlow <TValue>(response.Body, value, options, response.HttpContext.RequestAborted));
        }

        return(JsonSerializer.SerializeAsync <TValue>(response.Body, value, options, cancellationToken));
    }
Example #22
0
        /// <summary>
        /// Configures Application Builder and WebHost environment.
        /// </summary>
        /// <param name="app">Application builder.</param>
        /// <param name="env">Webhost environment.</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("secret", Secret);
            });

            async Task Secret(HttpContext context)
            {
                // Get secret from configuration!!!
                var secretValue = Configuration["super-secret"];

                context.Response.ContentType = "application/json";
                await JsonSerializer.SerializeAsync(context.Response.Body, secretValue);
            }
        }
Example #23
0
        private static async Task PerformSerialization <TElement>(object obj, Type type, JsonSerializerOptions options)
        {
            string expectedjson = JsonSerializer.Serialize(obj, options);

            using (var memoryStream = new MemoryStream())
            {
                await JsonSerializer.SerializeAsync(memoryStream, obj, options);

                string serialized = Encoding.UTF8.GetString(memoryStream.ToArray());
                JsonTestHelper.AssertJsonEqual(expectedjson, serialized);

                memoryStream.Position = 0;
                await TestDeserialization <TElement>(memoryStream, expectedjson, type, options);
            }

            // Deserialize with extra whitespace
            string jsonWithWhiteSpace = GetPayloadWithWhiteSpace(expectedjson);

            using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonWithWhiteSpace)))
            {
                await TestDeserialization <TElement>(memoryStream, expectedjson, type, options);
            }
        }
        private static async Task WriteResponse(HttpContext httpContext, bool includeDetails)
        {
            // Retrieve the error from the ExceptionHandler middleware
            var exceptionDetails = httpContext.Features.Get <IExceptionHandlerFeature>();
            var ex = exceptionDetails?.Error;

            httpContext.Response.ContentType = "application/problem+json";

            // Get the details to display, depending on whether we want to expose the raw exception
            var title   = includeDetails ? "An error occured: " + ex.Message : "An error occured";
            var details = includeDetails ? ex.ToString() : null;

            var problem = new ProblemDetails
            {
                Status = 500,
                Title  = title,
                Detail = details
            };

            //Serialize the problem details object to the Response as JSON (using System.Text.Json)
            var stream = httpContext.Response.Body;
            await JsonSerializer.SerializeAsync(stream, problem);
        }
Example #25
0
        public async static void NullValueWithNullableSuccess()
        {
            byte[] nullUtf8Literal = Encoding.UTF8.GetBytes("null");

            var            stream = new MemoryStream();
            Utf8JsonWriter writer = new Utf8JsonWriter(stream);

            JsonSerializer.Serialize(writer: writer, value: null, inputType: typeof(int?));
            byte[] jsonBytes = stream.ToArray();
            Assert.Equal(nullUtf8Literal, jsonBytes);

            string jsonString = JsonSerializer.Serialize(value: null, inputType: typeof(int?));

            Assert.Equal("null", jsonString);

            jsonBytes = JsonSerializer.SerializeToUtf8Bytes(value: null, inputType: typeof(int?));
            Assert.Equal(nullUtf8Literal, jsonBytes);

            stream = new MemoryStream();
            await JsonSerializer.SerializeAsync(stream, value : null, inputType : typeof(int?));

            Assert.Equal(nullUtf8Literal, stream.ToArray());
        }
Example #26
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.Map("", builder => {
                builder.Run(async context => {
                    var userList = Enumerable.Range(1, random.Next(5, 15)).Select(index => new {
                        Id                = index,
                        Name              = dictionary[index],
                        BirthDate         = DateTime.Now.AddDays(index),
                        Salary            = ((random.NextDouble() * 100000) + 50000).ToString("0.##"),
                        ProfilePictureUrl = $"https://i.pravatar.cc/50?{random.Next(1, 1000)}"
                    });

                    await JsonSerializer.SerializeAsync(context.Response.Body, userList);
                });
            });
        }
Example #27
0
        private async Task <string> EnsureSeasonInfo(string seriesImdbId, int seasonId, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(seriesImdbId))
            {
                throw new ArgumentException("The series IMDb ID was null or whitespace.", nameof(seriesImdbId));
            }

            var imdbParam = seriesImdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? seriesImdbId : "tt" + seriesImdbId;

            var path = GetSeasonFilePath(imdbParam, seasonId);

            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            if (fileInfo.Exists)
            {
                // If it's recent or automatic updates are enabled, don't re-download
                if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
                {
                    return(path);
                }
            }

            var url = GetOmdbUrl(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "i={0}&season={1}&detail=full",
                    imdbParam,
                    seasonId));

            var rootObject = await GetDeserializedOmdbResponse <SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);

            Directory.CreateDirectory(Path.GetDirectoryName(path));
            await using FileStream jsonFileStream = File.OpenWrite(path);
            await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);

            return(path);
        }
Example #28
0
        public async Task GenerateTokenAsync(UserManager <TodoUser> userManager, HttpContext context)
        {
            var loginInfo = await JsonSerializer.DeserializeAsync <LoginInfo>(context.Request.Body, _options);

            var user = await userManager.FindByNameAsync(loginInfo?.UserName);

            if (user == null || !await userManager.CheckPasswordAsync(user, loginInfo.Password))
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return;
            }

            var claims = new List <Claim>();

            claims.Add(new Claim("can_view", "true"));

            if (user.IsAdmin)
            {
                claims.Add(new Claim("can_delete", "true"));
            }

            var key   = new SymmetricSecurityKey(_jwtSettings.Key);
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: _jwtSettings.Issuer,
                audience: _jwtSettings.Audience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds
                );

            context.Response.ContentType = "application/json";
            await JsonSerializer.SerializeAsync(context.Response.Body, new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            });
        }
Example #29
0
        public async Task <Response <BlobContentInfo> > UploadEncryptedAsync(string blobName, Stream stream, BlobHttpHeaders headers)
        {
            using var all = new MemoryStream();
            await stream.CopyToAsync(all);

            using var aes = new AesManaged();
            aes.GenerateKey();
            aes.GenerateIV();

            var keyIdentifier = new KeyIdentifier($"https://{Configuration["KeyVaultName"].ToLower()}.vault.azure.net", EncryptionKeyName).ToString();

            var keyVersion = (await KeyVault.GetKeyAsync(keyIdentifier)).KeyIdentifier.Version;

            var envelope = new Envelope()
            {
                Key     = await WrapKey(aes.Key, keyIdentifier),
                IV      = await WrapKey(aes.IV, keyIdentifier),
                Content = Convert.ToBase64String(PerformCryptography(all.ToArray(), aes.CreateEncryptor()))
            };

            using var upstream = new MemoryStream();
            var serializedEnvelope = JsonSerializer.SerializeAsync(upstream, envelope);

            upstream.Position = 0;

            var blob   = Container.GetBlobClient(blobName);
            var result = await blob.UploadAsync(upstream,
                                                metadata : new Dictionary <string, string>()
            {
                { "EBP_KeyName", EncryptionKeyName },
                { "EBP_KeyVersion", keyVersion },
                { "EBP_WrapAlgorithm", JsonWebKeyEncryptionAlgorithm.RSAOAEP256 },
                { "EBP_ContentType", headers.ContentType }
            });

            return(result);
        }
Example #30
0
        public async void WriteCommandSettingsAsync()
        {
            while (this.CommandSettingsFileLocked)
            {
                await Task.Delay(500);
            }
            this.CommandSettingsFileLocked = true;
            List <ConfiguredCommand> configuredCommandsToSave = new List <ConfiguredCommand>();

            using (FileStream stream = new FileStream(Path.Combine(path, "configured-commands.json"), FileMode.Open))
            {
                stream.SetLength(0);
                Log.Logger.Information($"writing configured commands to: {stream.Name}");
                foreach (AbstractCommand command in this.ConfiguredCommands)
                {
                    if (command is CustomCommand customCommand)
                    {
                        configuredCommandsToSave.Add(new ConfiguredCommand()
                        {
                            Id = customCommand.Id, Name = customCommand.Name, Type = customCommand.GetType().Name, Command = customCommand.Command
                        });
                    }
                    if (command is KeyCommand customKeyCommand)
                    {
                        configuredCommandsToSave.Add(new ConfiguredCommand()
                        {
                            Id = customKeyCommand.Id, Name = customKeyCommand.Name, Type = customKeyCommand.GetType().Name, KeyCode = customKeyCommand.KeyCode
                        });
                    }
                }

                await JsonSerializer.SerializeAsync(stream, configuredCommandsToSave);

                stream.Close();
            }
            this.CommandSettingsFileLocked = false;
        }
Example #31
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.Map("/random", builder => {
                builder.Run(async context => {
                    var product = new {
                        Id         = random.Next(1, 50),
                        Date       = DateTime.Now.AddDays(random.Next(-20, 20)),
                        Price      = (random.NextDouble() * 100).ToString("0.##"),
                        StockCount = random.Next(5, 50),
                        PictureUrl = $"https://picsum.photos/50?{random.Next(1, 1000)}"
                    };

                    await JsonSerializer.SerializeAsync(context.Response.Body, product);
                });
            });

            app.Map("", builder => {
                builder.Run(async context => {
                    var productList = Enumerable.Range(1, random.Next(1, 20)).Select(index => new {
                        Id         = index,
                        Date       = DateTime.Now.AddDays(index),
                        Price      = (random.NextDouble() * 100).ToString("0.##"),
                        StockCount = random.Next(5, 50),
                        PictureUrl = $"https://picsum.photos/50?{random.Next(1, 1000)}"
                    });

                    await JsonSerializer.SerializeAsync(context.Response.Body, productList);
                });
            });
        }