Example #1
0
        /// <summary>
        /// Sends an EOL-terminated message to the server (\n is appended by this method)
        /// </summary>
        /// <param name="format">Format of message to send</param>
        /// <param name="formatParameters">Format parameters</param>
        /// <returns></returns>
        public async Task <bool> SendRawMessage(String message)
        {
            try
            {
                await _streamSemaphore.WaitAsync();

                await streamWriter.WriteLineAsync(message);

                await streamWriter.FlushAsync();
            }
            catch (Exception e)
            {
                Exception = e;
                if (OnException != null)
                {
                    foreach (var d in OnException.GetInvocationList())
                    {
                        var task = Task.Run(() => d.DynamicInvoke(this, e));
                    }
                }
                return(false);
            }
            finally { _streamSemaphore.Release(); }

            if (OnRawMessageSent != null)
            {
                foreach (var d in OnRawMessageSent.GetInvocationList())
                {
                    var task = Task.Run(() => d.DynamicInvoke(this, message));
                }
            }

            return(true);
        }
        public async Task RunAsyncMethod(bool isValid, bool isValidDevice, string submissionNumber, string userUuid)
        {
            // preparation
            var config = new Mock <IConfiguration>();

            config.Setup(_ => _["SupportRegions"]).Returns("Region1,Region2");
            var diagnosisRepo = new Mock <IDiagnosisRepository>();

            diagnosisRepo.Setup(_ => _.SubmitDiagnosisAsync(It.IsAny <string>(),
                                                            It.IsAny <DateTimeOffset>(),
                                                            It.IsAny <string>(),
                                                            It.IsAny <TemporaryExposureKeyModel[]>()))
            .Returns(Task.CompletedTask);
            var tekRepo          = new Mock <ITemporaryExposureKeyRepository>();
            var validation       = new Mock <IValidationUserService>();
            var validationResult = new IValidationUserService.ValidateResult()
            {
                IsValid = isValid
            };

            validation.Setup(_ => _.ValidateAsync(It.IsAny <HttpRequest>(), It.IsAny <IUser>())).ReturnsAsync(validationResult);
            var deviceCheck = new Mock <IDeviceValidationService>();

            deviceCheck.Setup(_ => _.Validation(It.IsAny <DiagnosisSubmissionParameter>())).ReturnsAsync(isValidDevice);
            var logger       = new Mock.LoggerMock <Covid19Radar.Api.DiagnosisApi>();
            var diagnosisApi = new DiagnosisApi(config.Object,
                                                diagnosisRepo.Object,
                                                tekRepo.Object,
                                                validation.Object,
                                                deviceCheck.Object,
                                                logger);
            var context  = new Mock <HttpContext>();
            var bodyJson = new DiagnosisSubmissionParameter()
            {
                SubmissionNumber = submissionNumber,
                UserUuid         = userUuid,
                Keys             = new DiagnosisSubmissionParameter.Key[] {
                    new DiagnosisSubmissionParameter.Key()
                    {
                        KeyData = "", RollingPeriod = 1, RollingStartNumber = 1
                    }
                }
            };
            var bodyString = Newtonsoft.Json.JsonConvert.SerializeObject(bodyJson);

            using var stream = new System.IO.MemoryStream();
            using (var writer = new System.IO.StreamWriter(stream, leaveOpen: true))
            {
                await writer.WriteAsync(bodyString);

                await writer.FlushAsync();
            }
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            context.Setup(_ => _.Request.Body).Returns(stream);
            // action
            await diagnosisApi.RunAsync(context.Object.Request);

            // assert
        }
Example #3
0
        protected async Task <System.IO.Stream> GetStreamFromStringAsync(string inputString)
        {
            await using var stream = new System.IO.MemoryStream();
            await using var writer = new System.IO.StreamWriter(stream);
            await writer.WriteAsync(inputString).ConfigureAwait(true);

            await writer.FlushAsync();

            stream.Position = 0;
            return(stream);
        }
Example #4
0
        public async Task Start()
        {
            Log(LogTypes.Info, $"Osu! Random Beatmap - {Engine.Version}");
            Log(LogTypes.Info, $"The main logger has been started.");

            _running             = true;
            _queueUpdaterRunning = true;
            while (_running)
            {
                _queueUpdaterRunning = true;
                if (_logQueue.Count > 0)
                {
                    KeyValuePair <LogTypes, object> pair = _logQueue.Dequeue();
                    await _writer.WriteLineAsync($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss.fffffff")}] [{pair.Key.ToString().ToUpper()}] {pair.Value}");

                    await _writer.FlushAsync();
                }

                await Task.Delay(1);
            }

            _queueUpdaterRunning = false;
        }
        public async Task RunAsyncMethod(string title, string message, System.Type ResultType)
        {
            // preparation
            var result = new Mock <ItemResponse <NotificationMessageModel> >();

            result.SetupGet(_ => _.Resource)
            .Returns(new NotificationMessageModel()
            {
                Message = message
            });
            var cosmosNotification = new Mock <Container>();

            cosmosNotification.Setup(_ => _.CreateItemAsync(It.IsAny <NotificationMessageModel>(),
                                                            It.IsAny <PartitionKey?>(),
                                                            It.IsAny <ItemRequestOptions>(),
                                                            It.IsAny <CancellationToken>()))
            .ReturnsAsync(result.Object);
            var cosmos = new Mock <ICosmos>();

            cosmos.SetupGet(_ => _.Notification)
            .Returns(cosmosNotification.Object);
            var notification          = new Mock <INotificationService>();
            var logger                = new Mock.LoggerMock <Covid19Radar.Api.External.NotificationCreateApi>();
            var notificationCreateApi = new Covid19Radar.Api.External.NotificationCreateApi(cosmos.Object, notification.Object, logger);
            var context               = new Mock.HttpContextMock();
            var param = new Api.External.Models.NotificationCreateParameter()
            {
                Title   = title,
                Message = message
            };
            var bodyString = Newtonsoft.Json.JsonConvert.SerializeObject(param);

            using var stream = new System.IO.MemoryStream();
            using (var writer = new System.IO.StreamWriter(stream, leaveOpen: true))
            {
                await writer.WriteAsync(bodyString);

                await writer.FlushAsync();
            }
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            context._Request.Body = stream;

            // action
            var actual = await notificationCreateApi.RunAsync(context.Request);

            // assert
            Assert.IsInstanceOfType(actual, ResultType);
        }
        public static void Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name        = "Random People Generator",
                Description = "Creates lists of randomised people for testing purposes"
            };

            app.HelpOption();

            var formatOption = app.Option("-f|--format <Format>", "Output format (csv|json)", CommandOptionType.SingleValue);
            var outputOption = app.Option("-o|--output <Filename>", "Output filename", CommandOptionType.SingleValue);
            var numberOption = app.Option <int>("-n|--number <Count>", "Number of people to generate", CommandOptionType.SingleValue);
            var randomOption = app.Option("-r|--random", "Creates random list, or seeded list (same each time)", CommandOptionType.NoValue);

            app.OnExecuteAsync(async(token) =>
            {
                var numPeople = numberOption.HasValue() ? numberOption.ParsedValue : 10;
                var format    = formatOption.HasValue() ? formatOption.Value() : "json";
                var random    = randomOption.HasValue() ? true : false;
                var filename  = outputOption.HasValue() ? outputOption.Value() : $"{AppDomain.CurrentDomain.BaseDirectory}people.{format}";

                var people = RandomPersonFactory.GetPeople(numPeople, random);

                using (System.IO.StreamWriter file = new System.IO.StreamWriter($"{filename}"))
                {
                    if (format == "json")
                    {
                        await file.WriteAsync(JsonConvert.SerializeObject(people));
                    }
                    else
                    {
                        file.WriteLine(new PersonalDetails().HeaderRow);
                        people.ForEach(p => file.WriteLine(p.ToCSV()));
                        await file.FlushAsync();
                    }
                }

                Console.WriteLine($"Wrote {numPeople} {(random ? "random" : "seeded")} people to {filename}");

                return(0);
            });

            app.Execute(args);
        }
        public async Task <byte[]> ToCsvAsync()
        {
            var branches = await _siteService.GetAllBranches();

            using var memoryStream = new System.IO.MemoryStream();
            using var writer       = new System.IO.StreamWriter(memoryStream);
            using var csv          = new CsvHelper.CsvWriter(writer,
                                                             new CsvConfiguration(CultureInfo.InvariantCulture));
            csv.Context.RegisterClassMap <Maps.BranchMap>();

            await csv.WriteRecordsAsync(branches.OrderBy(_ => _.SystemName).ThenBy(_ => _.Name));

            await csv.FlushAsync();

            await writer.FlushAsync();

            await memoryStream.FlushAsync();

            return(memoryStream.ToArray());
        }
Example #8
0
        static StackObject *FlushAsync_17(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.StreamWriter instance_of_this_method = (System.IO.StreamWriter) typeof(System.IO.StreamWriter).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.FlushAsync();

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Example #9
0
        public static async Task WriteFile(String data, File file)
        {
            using (AtomicFile mFile = new AtomicFile(file))
            {
                // Wait for file to be free
                while (IsFileLocked(file))
                {
                    await Task.Delay(100);
                }

                using (System.IO.Stream outputStream = mFile.StartWrite())
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(outputStream))
                    {
                        // Clear file before writing
                        outputStream.SetLength(0);

                        await writer.WriteAsync(data);

                        await writer.FlushAsync();

                        mFile.FinishWrite(outputStream);
                    }
            }
        }
Example #10
0
        async System.Threading.Tasks.Task Microsoft.AspNetCore.Mvc.IActionResult.ExecuteResultAsync(
            Microsoft.AspNetCore.Mvc.ActionContext context)
        {
            if (context == null)
            {
                throw new System.ArgumentNullException("context");
            }

            if (JsonRequestBehavior == JsonRequestBehavior_t.DenyGet &&
                string.Equals(context.HttpContext.Request.Method, "GET", System.StringComparison.OrdinalIgnoreCase))
            {
                throw new System.InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            Microsoft.AspNetCore.Http.HttpResponse response = context.HttpContext.Response;
            // https://stackoverflow.com/questions/9254891/what-does-content-type-application-json-charset-utf-8-really-mean
            response.ContentType = this.ContentType + "; charset=" + this.ContentEncoding.WebName;

            if (Data == null)
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.Body, this.ContentEncoding))
                {
                    // await writer.WriteLineAsync("null");
                    await writer.WriteLineAsync("{}");
                } // End Using writer

                return;
            } // End if (Data == null)


#if false
            Newtonsoft.Json.JsonSerializerSettings jsonSerializerSettings =
                new Newtonsoft.Json.JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };


            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.Body, this.ContentEncoding))
            {
                using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(writer))
                {
                    Newtonsoft.Json.JsonSerializer ser = Newtonsoft.Json.JsonSerializer.Create(jsonSerializerSettings);

                    ser.Serialize(jsonWriter, Data);
                    await jsonWriter.FlushAsync();
                } // End Using jsonWriter

                await writer.FlushAsync();
            } // End Using writer
#endif


            System.Text.Json.JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions()
            {
                IncludeFields        = true,
                WriteIndented        = true,
                PropertyNamingPolicy = this.NamingPolicy
                                       // PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
            };

            await System.Text.Json.JsonSerializer.SerializeAsync(response.Body, Data, options);
        } // End Task ExecuteResultAsync
Example #11
0
        public static async System.Threading.Tasks.Task AnyDataReaderToXml(this System.Data.IDbConnection cnn
                                                                           , string sql
                                                                           , object param                  = null
                                                                           , string tableSchema            = null
                                                                           , string tableName              = null
                                                                           , System.Text.Encoding encoding = null
                                                                           , XmlRenderType_t format        = XmlRenderType_t.Default
                                                                           , Microsoft.AspNetCore.Http.HttpContext context = null
                                                                           , System.Data.IDbTransaction transaction        = null
                                                                           , int?commandTimeout = null
                                                                           , System.Data.CommandType?commandType = null)
        {
            if (encoding == null)
            {
                encoding = System.Text.Encoding.UTF8;
            }

            if (string.IsNullOrEmpty(sql))
            {
                if (string.IsNullOrEmpty(tableName))
                {
                    throw new System.ArgumentException("Parameter " + nameof(tableName) + " is NULL or empty.");
                }

                if (string.IsNullOrEmpty(tableSchema))
                {
                    sql = $"SELECT * FROM " + QuoteObject(tableName) + " ;";
                }
                else
                {
                    sql = $"SELECT * FROM " + QuoteObject(tableSchema) + "." + QuoteObject(tableName) + " ;";
                }
            } // End if (string.IsNullOrEmpty(sql))

            if (string.IsNullOrEmpty(sql))
            {
                throw new System.ArgumentException("Parameter " + nameof(sql) + " is NULL or empty.");
            }

            // DynamicParameters dbArgs = new DynamicParameters();

            System.Text.StringBuilder xmlBuilder = new System.Text.StringBuilder();

            using (System.IO.StreamWriter output =
                       new System.IO.StreamWriter(context.Response.Body, encoding))
            {
                // using (System.Xml.XmlWriter writer = CreateXmlWriter(xmlBuilder, format))
                using (System.Xml.XmlWriter writer = CreateXmlWriter(output, format))
                {
                    try
                    {
                        using (System.Data.Common.DbDataReader dr = await cnn.ExecuteDbReaderAsync(sql, param, transaction, commandTimeout, commandType))
                        {
                            if (context != null)
                            {
                                context.Response.StatusCode  = (int)System.Net.HttpStatusCode.OK;
                                context.Response.ContentType = "application/xml; charset=" + encoding.WebName;
                                // context.Response.Headers["Transfer-Encoding"] = "chunked";
                            } // End if (context != null)

                            await WriteAsXmlAsync(tableSchema, tableName, format, writer, dr);
                        } // End Using dr
                    }
                    catch (System.Exception ex)
                    {
                        context.Response.StatusCode  = (int)System.Net.HttpStatusCode.InternalServerError;
                        context.Response.ContentType = "application/xml; charset=" + encoding.WebName;

                        bool dataAsAttributes = format.HasFlag(XmlRenderType_t.DataInAttributes);


                        await writer.WriteStartDocumentAsync(true);

                        await writer.WriteStartElementAsync(null, "error", null);

                        if (dataAsAttributes)
                        {
                            await writer.WriteAttributeStringAsync(null, "Message", null, ex.Message);
                        }
                        else
                        {
                            await writer.WriteStartElementAsync(null, "Message", null);

                            writer.WriteValue(ex.Message);
                            await writer.WriteEndElementAsync(); // Message
                        }

                        if (dataAsAttributes)
                        {
                            await writer.WriteAttributeStringAsync(null, "StackTrace", null, ex.StackTrace);
                        }
                        else
                        {
                            await writer.WriteStartElementAsync(null, "StackTrace", null);

                            writer.WriteValue(ex.StackTrace);
                            await writer.WriteEndElementAsync(); // StackTrace
                        }

                        await writer.WriteEndElementAsync(); // error
                    }

                    await writer.FlushAsync();

                    await output.FlushAsync();

                    await context.Response.CompleteAsync();
                } // End Using writer
            }     // Wnd Using output
        }         // End Task AnyDataReaderToXml
Example #12
0
        public async Task RunAsyncMethod(bool isValid,
                                         bool isValidDevice,
                                         string region,
                                         string verificationPayload,
                                         string platform,
                                         string userUuid)
        {
            // preparation
            var config = new Mock <IConfiguration>();

            config.Setup(_ => _["SupportRegions"]).Returns("Region1,Region2");
            var diagnosisRepo = new Mock <IDiagnosisRepository>();

            diagnosisRepo.Setup(_ => _.SubmitDiagnosisAsync(It.IsAny <string>(),
                                                            It.IsAny <DateTimeOffset>(),
                                                            It.IsAny <string>(),
                                                            It.IsAny <TemporaryExposureKeyModel[]>()))
            .ReturnsAsync(new DiagnosisModel());
            var tekRepo          = new Mock <ITemporaryExposureKeyRepository>();
            var validation       = new Mock <IValidationUserService>();
            var validationServer = new Mock <IValidationServerService>();

            validationServer.Setup(_ => _.Validate(It.IsAny <HttpRequest>())).Returns(IValidationServerService.ValidateResult.Success);

            var validationResult = new IValidationUserService.ValidateResult()
            {
                IsValid = isValid
            };

            validation.Setup(_ => _.ValidateAsync(It.IsAny <HttpRequest>(), It.IsAny <IUser>())).ReturnsAsync(validationResult);
            var deviceCheck = new Mock <IV1DeviceValidationService>();

            deviceCheck.Setup(_ => _.Validation(It.IsAny <V1DiagnosisSubmissionParameter>(), It.IsAny <DateTimeOffset>())).ReturnsAsync(isValidDevice);
            var verification = new Mock <IVerificationService>();
            var logger       = new Mock.LoggerMock <Covid19Radar.Api.DiagnosisApi>();
            var diagnosisApi = new DiagnosisApi(config.Object,
                                                diagnosisRepo.Object,
                                                tekRepo.Object,
                                                validation.Object,
                                                deviceCheck.Object,
                                                verification.Object,
                                                validationServer.Object,
                                                logger);
            var context = new Mock <HttpContext>();
            var keydata = new byte[16];

            RandomNumberGenerator.Create().GetBytes(keydata);
            var keyDataString = Convert.ToBase64String(keydata);
            var startNumber   = (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 600;
            var bodyJson      = new V1DiagnosisSubmissionParameter()
            {
                VerificationPayload       = verificationPayload,
                Regions                   = new[] { region },
                UserUuid                  = userUuid,
                Platform                  = platform,
                DeviceVerificationPayload = "DeviceVerificationPayload",
                AppPackageName            = "Covid19Radar",
                Keys = new V1DiagnosisSubmissionParameter.Key[] {
                    new V1DiagnosisSubmissionParameter.Key()
                    {
                        KeyData = keyDataString, RollingPeriod = 0, RollingStartNumber = startNumber
                    },
                    new V1DiagnosisSubmissionParameter.Key()
                    {
                        KeyData = keyDataString, RollingPeriod = 0, RollingStartNumber = startNumber
                    }
                }
            };
            var bodyString = Newtonsoft.Json.JsonConvert.SerializeObject(bodyJson);

            using var stream = new System.IO.MemoryStream();
            using (var writer = new System.IO.StreamWriter(stream, leaveOpen: true))
            {
                await writer.WriteAsync(bodyString);

                await writer.FlushAsync();
            }
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            context.Setup(_ => _.Request.Body).Returns(stream);
            // action
            await diagnosisApi.RunAsync(context.Object.Request);

            // assert
        }
        } // End Sub WriteArray

        public static async System.Threading.Tasks.Task AnyDataReaderToJson(
            System.Data.Common.DbConnection cnn
            , string sql
            , RenderType_t format
            , Microsoft.AspNetCore.Http.HttpContext context
            , System.Text.Encoding encoding
            , object parameters = null
            , System.Data.IDbTransaction transaction = null
            , int?commandTimeout = null
            , System.Data.CommandType?commandType = null
            )
        {
            // DynamicParameters dbArgs = new DynamicParameters();


            using (System.IO.StreamWriter responseWriter = new System.IO.StreamWriter(context.Response.Body, encoding))
            {
                using (Newtonsoft.Json.JsonTextWriter jsonWriter =
                           new Newtonsoft.Json.JsonTextWriter(responseWriter))
                {
                    if (format.HasFlag(RenderType_t.Indented))
                    {
                        jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
                    }


                    try
                    {
                        using (System.Data.Common.DbDataReader dr = await cnn.ExecuteDbReaderAsync(sql, parameters, transaction, commandTimeout, commandType))
                        {
                            context.Response.StatusCode  = (int)System.Net.HttpStatusCode.OK;
                            context.Response.ContentType = "application/json; charset=" + encoding.WebName;

                            await jsonWriter.WriteStartObjectAsync();

                            await jsonWriter.WritePropertyNameAsync("tables");

                            await jsonWriter.WriteStartArrayAsync();

                            do
                            {
                                if (!format.HasFlag(RenderType_t.Data_Only) &&
                                    !format.HasFlag(RenderType_t.DataTable))
                                {
                                    await jsonWriter.WriteStartObjectAsync();

                                    await jsonWriter.WritePropertyNameAsync("columns");

                                    if (format.HasFlag(RenderType_t.Columns_Associative))
                                    {
                                        await WriteAssociativeColumnsArray(jsonWriter, dr, format);
                                    }
                                    else if (format.HasFlag(RenderType_t.Columns_ObjectArray))
                                    {
                                        await WriteComplexArray(jsonWriter, dr, format);
                                    }
                                    else // (format.HasFlag(RenderType_t.Array))
                                    {
                                        await WriteArray(jsonWriter, dr);
                                    }
                                } // End if (!format.HasFlag(RenderType_t.Data_Only))


                                if (!format.HasFlag(RenderType_t.Data_Only) &&
                                    !format.HasFlag(RenderType_t.DataTable))
                                {
                                    await jsonWriter.WritePropertyNameAsync("rows");
                                } // End if (!format.HasFlag(RenderType_t.Data_Only))

                                await jsonWriter.WriteStartArrayAsync();

                                string[] columns = null;
                                if (format.HasFlag(RenderType_t.DataTable))
                                {
                                    columns = new string[dr.FieldCount];
                                    for (int i = 0; i < dr.FieldCount; i++)
                                    {
                                        columns[i] = dr.GetName(i);
                                    } // Next i
                                }     // End if (format.HasFlag(RenderType_t.DataTable))

                                while (await dr.ReadAsync())
                                {
                                    if (format.HasFlag(RenderType_t.DataTable))
                                    {
                                        await jsonWriter.WriteStartObjectAsync();
                                    }
                                    else
                                    {
                                        await jsonWriter.WriteStartArrayAsync();
                                    }

                                    for (int i = 0; i <= dr.FieldCount - 1; i++)
                                    {
                                        object obj = await dr.GetFieldValueAsync <object>(i);

                                        if (obj == System.DBNull.Value)
                                        {
                                            obj = null;
                                        }

                                        if (columns != null && format.HasFlag(RenderType_t.DataTable))
                                        {
                                            await jsonWriter.WritePropertyNameAsync(columns[i]);
                                        }

                                        await jsonWriter.WriteValueAsync(obj);
                                    } // Next i

                                    if (format.HasFlag(RenderType_t.DataTable))
                                    {
                                        await jsonWriter.WriteEndObjectAsync();
                                    }
                                    else
                                    {
                                        await jsonWriter.WriteEndArrayAsync();
                                    }
                                } // Whend

                                await jsonWriter.WriteEndArrayAsync();

                                if (!format.HasFlag(RenderType_t.Data_Only) &&
                                    !format.HasFlag(RenderType_t.DataTable))
                                {
                                    await jsonWriter.WriteEndObjectAsync();
                                } // End if (!format.HasFlag(RenderType_t.Data_Only))

                                await jsonWriter.FlushAsync();

                                await responseWriter.FlushAsync();
                            } while (await dr.NextResultAsync());

                            await jsonWriter.WriteEndArrayAsync();

                            await jsonWriter.WriteEndObjectAsync();

                            await jsonWriter.FlushAsync();

                            await responseWriter.FlushAsync();
                        } // End Using dr
                    }
                    catch (System.Exception ex)
                    {
                        context.Response.StatusCode  = (int)System.Net.HttpStatusCode.InternalServerError;
                        context.Response.ContentType = "application/json; charset=" + encoding.WebName;

                        await jsonWriter.WriteStartObjectAsync();

                        await jsonWriter.WritePropertyNameAsync("Error");

                        await jsonWriter.WriteStartObjectAsync();

                        await jsonWriter.WritePropertyNameAsync("Message");

                        await jsonWriter.WriteValueAsync(ex.Message);

                        await jsonWriter.WritePropertyNameAsync("StackTrace");

                        await jsonWriter.WriteValueAsync(ex.StackTrace);

                        await jsonWriter.WriteEndObjectAsync();

                        await jsonWriter.WriteEndObjectAsync();
                    }

                    await jsonWriter.FlushAsync();

                    await responseWriter.FlushAsync();

                    await context.Response.CompleteAsync();
                } // End Using jsonWriter
            }     // End Using responseWriter
        }         // End Sub AnyDataReaderToJson
Example #14
0
        } // End Sub WriteArray 


        public static async System.Threading.Tasks.Task AnyDataReaderToJson(
            string sql
            , System.Collections.Generic.Dictionary<string, object> pars
            , Microsoft.AspNetCore.Http.HttpContext context
            , RenderType_t format)
        {
            SqlService service = (SqlService) context.RequestServices.GetService(typeof(SqlService));

            using (System.Data.Common.DbConnection con = service.Connection)
            {
                using (System.Data.Common.DbCommand cmd = con.CreateCommand())
                {
                    cmd.CommandText = sql;
                    // cmd.CommandText = "SELECT  * FROM T_Benutzer; SELECT * FROM T_Benutzergruppen;";

                    service.AddParameterList(pars, cmd);
                    // cmd.ExecuteNonQueryAsync
                    // cmd.ExecuteReaderAsync
                    // cmd.ExecuteScalarAsync

                    using (System.Data.Common.DbDataReader dr = await cmd.ExecuteReaderAsync(
                        System.Data.CommandBehavior.SequentialAccess
                        | System.Data.CommandBehavior.CloseConnection))
                    {
                        using (System.IO.StreamWriter output = new System.IO.StreamWriter(context.Response.Body))
                        {
                            using (Newtonsoft.Json.JsonTextWriter jsonWriter =
                                new Newtonsoft.Json.JsonTextWriter(output)) // context.Response.Output)
                            {
                                if (format.HasFlag(RenderType_t.Indented))
                                    jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;


                                context.Response.StatusCode = (int) System.Net.HttpStatusCode.OK;
                                context.Response.ContentType = "application/json";


                                await jsonWriter.WriteStartObjectAsync();

                                await jsonWriter.WritePropertyNameAsync("tables");
                                await jsonWriter.WriteStartArrayAsync();

                                do
                                {
                                    if (!format.HasFlag(RenderType_t.Data_Only) &&
                                        !format.HasFlag(RenderType_t.DataTable))
                                    {
                                        await jsonWriter.WriteStartObjectAsync();
                                        await jsonWriter.WritePropertyNameAsync("columns");

                                        if (format.HasFlag(RenderType_t.Columns_Associative))
                                        {
                                            await WriteAssociativeColumnsArray(jsonWriter, dr, format);
                                        }
                                        else if (format.HasFlag(RenderType_t.Columns_ObjectArray))
                                        {
                                            await WriteComplexArray(jsonWriter, dr, format);
                                        }
                                        else // (format.HasFlag(RenderType_t.Array))
                                        {
                                            await WriteArray(jsonWriter, dr);
                                        }
                                    } // End if (!format.HasFlag(RenderType_t.Data_Only)) 


                                    if (!format.HasFlag(RenderType_t.Data_Only) &&
                                        !format.HasFlag(RenderType_t.DataTable))
                                    {
                                        await jsonWriter.WritePropertyNameAsync("rows");
                                    } // End if (!format.HasFlag(RenderType_t.Data_Only))
                                    
                                    await jsonWriter.WriteStartArrayAsync();
                                    
                                    string[] columns = null;
                                    if (format.HasFlag(RenderType_t.DataTable))
                                    {
                                        columns = new string[dr.FieldCount];
                                        for (int i = 0; i < dr.FieldCount; i++)
                                        {
                                            columns[i] = dr.GetName(i);
                                        } // Next i 
                                    } // End if (format.HasFlag(RenderType_t.DataTable)) 

                                    while (await dr.ReadAsync())
                                    {
                                        if (format.HasFlag(RenderType_t.DataTable))
                                            await jsonWriter.WriteStartObjectAsync();
                                        else
                                            await jsonWriter.WriteStartArrayAsync();

                                        for (int i = 0; i <= dr.FieldCount - 1; i++)
                                        {
                                            object obj = await dr.GetFieldValueAsync<object>(i);
                                            if (obj == System.DBNull.Value)
                                                obj = null;

                                            if (columns != null && format.HasFlag(RenderType_t.DataTable))
                                            {
                                                await jsonWriter.WritePropertyNameAsync(columns[i]);
                                            }

                                            await jsonWriter.WriteValueAsync(obj);
                                        } // Next i 

                                        if (format.HasFlag(RenderType_t.DataTable))
                                            await jsonWriter.WriteEndObjectAsync();
                                        else
                                            await jsonWriter.WriteEndArrayAsync();
                                    } // Whend 

                                    await jsonWriter.WriteEndArrayAsync();

                                    if (!format.HasFlag(RenderType_t.Data_Only) &&
                                        !format.HasFlag(RenderType_t.DataTable))
                                    {
                                        await jsonWriter.WriteEndObjectAsync();
                                    } // End if (!format.HasFlag(RenderType_t.Data_Only)) 
                                } while (await dr.NextResultAsync());

                                await jsonWriter.WriteEndArrayAsync();
                                await jsonWriter.WriteEndObjectAsync();

                                await jsonWriter.FlushAsync();
                                await output.FlushAsync();
                            } // jsonWriter 
                        } // output 
                    } // dr 
                } // End Using cmd 

                if (con.State != System.Data.ConnectionState.Closed)
                    con.Close();
            } // con 
        } // End Sub WriteArray 
Example #15
0
        public async Task RunAsyncMethod(bool isValid,
                                         bool isValidDevice,
                                         string region,
                                         string verificationPayload,
                                         string platform,
                                         bool isChaffRequest,
                                         HttpStatusCode expectedStatusCode
                                         )
        {
            // preparation
            var config = new Mock <IConfiguration>();

            config.Setup(_ => _["SupportRegions"]).Returns("Region1,Region2");

            var tekRepo          = new Mock <ITemporaryExposureKeyRepository>();
            var validationServer = new Mock <IValidationServerService>();

            validationServer.Setup(_ => _.Validate(It.IsAny <HttpRequest>())).Returns(IValidationServerService.ValidateResult.Success);


            var deviceCheck = new Mock <IDeviceValidationService>();

            deviceCheck.Setup(_ => _.Validation(It.IsAny <string>(), It.IsAny <V2DiagnosisSubmissionParameter>(), It.IsAny <DateTimeOffset>())).ReturnsAsync(isValidDevice);
            var verification = new Mock <IVerificationService>();
            var logger       = new Mock.LoggerMock <Covid19Radar.Api.V2DiagnosisApi>();
            var diagnosisApi = new V2DiagnosisApi(config.Object,
                                                  tekRepo.Object,
                                                  deviceCheck.Object,
                                                  verification.Object,
                                                  validationServer.Object,
                                                  logger);
            var context = new Mock <HttpContext>();
            var keydata = new byte[16];

            RandomNumberGenerator.Create().GetBytes(keydata);
            var keyDataString = Convert.ToBase64String(keydata);
            var startNumber   = (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 600;
            var bodyJson      = new V2DiagnosisSubmissionParameter()
            {
                VerificationPayload       = verificationPayload,
                Regions                   = new[] { region },
                Platform                  = platform,
                DeviceVerificationPayload = "DeviceVerificationPayload",
                AppPackageName            = "Covid19Radar",
                Keys = new V2DiagnosisSubmissionParameter.Key[] {
                    new V2DiagnosisSubmissionParameter.Key()
                    {
                        KeyData = keyDataString, RollingPeriod = 0, RollingStartNumber = startNumber
                    },
                    new V2DiagnosisSubmissionParameter.Key()
                    {
                        KeyData = keyDataString, RollingPeriod = 0, RollingStartNumber = startNumber
                    }
                }
            };
            var bodyString = Newtonsoft.Json.JsonConvert.SerializeObject(bodyJson);

            using var stream = new System.IO.MemoryStream();
            using (var writer = new System.IO.StreamWriter(stream, leaveOpen: true))
            {
                await writer.WriteAsync(bodyString);

                await writer.FlushAsync();
            }
            stream.Seek(0, System.IO.SeekOrigin.Begin);

            context.Setup(_ => _.Request.Body).Returns(stream);

            if (isChaffRequest)
            {
                IHeaderDictionary headers = new HeaderDictionary()
                {
                    { "X-Chaff", "Foo" /* Server will check X-Chaff header existence, content no matter. */ }
                };
                context.Setup(_ => _.Request.Headers).Returns(headers);
            }

            // action
            var result = await diagnosisApi.RunAsync(context.Object.Request);

            // assert
            if (result is StatusCodeResult statusCodeResult)
            {
                Assert.AreEqual(((int)expectedStatusCode), statusCodeResult.StatusCode);
            }
            else if (result is BadRequestErrorMessageResult)
            {
                Assert.AreEqual(expectedStatusCode, HttpStatusCode.BadRequest);
            }
        }