Example #1
0
        public bool LogMessage(Enumeration.LoggingPriority priority, string transactionReference, Exception exception)
        {
            try
            {
                StringBuilder s = new StringBuilder();
                s.AppendFormat("Exception: {0} |", String.IsNullOrEmpty(exception.Message) ? "NONE" : exception.Message);
                if (exception.InnerException != null)
                {
                    s.AppendFormat("Inner Exception Message: {0} |", String.IsNullOrEmpty(exception.InnerException.Message) ? "NONE" : exception.InnerException.Message);
                    s.AppendFormat("Inner Exception Source: {0} |", String.IsNullOrEmpty(exception.InnerException.Source) ? "NONE" : exception.InnerException.Source);
                }
                s.AppendFormat("Exception Source: {0} |", String.IsNullOrEmpty(exception.Source) ? "NONE" : exception.Source);
                s.AppendFormat("Exception Stack Trace: {0} ", String.IsNullOrEmpty(exception.StackTrace) ? "NONE" : exception.StackTrace);

                LoggingRequest lsmr = new LoggingRequest
                {
                    TransactionReference = transactionReference,
                    LoggingPriority      = priority,
                    Message   = s.ToString(),
                    TimeStamp = DateTime.Now
                };

                //Call the Repo and insert the data (LoggingServiceRequest)

                return(true);
            }
            catch
            {
                // do nothing

                return(false);
            }
        }
Example #2
0
        public IActionResult Login(LoggingRequest request)
        {
            var refreshToken       = Guid.NewGuid();
            JwtSecurityToken token = null;

            using (var client = new SqlConnection(connectionString))
                using (var command = new SqlCommand())
                {
                    command.Connection = client;
                    client.Open();
                    command.CommandText = "Select FirstName, LastName, Password, salt from student where IndexNumber = @login";
                    command.Parameters.AddWithValue("login", request.Login);
                    var dr = command.ExecuteReader();
                    if (!dr.Read())
                    {
                        return(NotFound("nie ma takiego studenta"));
                    }
                    var imie       = dr[0].ToString();
                    var nazwisko   = dr[1].ToString();
                    var haslo      = dr[2].ToString();
                    var salt       = dr[3].ToString();
                    var valueBytes = KeyDerivation.Pbkdf2(
                        password: request.Password,
                        salt: Encoding.UTF8.GetBytes(salt),
                        prf: KeyDerivationPrf.HMACSHA512,
                        iterationCount: 10000,
                        numBytesRequested: 256 / 8);
                    if (!haslo.Equals(Convert.ToBase64String(valueBytes)))
                    {
                        return(BadRequest("podano złe hasło"));
                    }

                    string id     = imie + " " + nazwisko;
                    var    claims = new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, request.Login),
                        new Claim(ClaimTypes.Name, id),
                        new Claim(ClaimTypes.Role, "employee")
                    };
                    var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                    token = new JwtSecurityToken
                            (
                        issuer: "s18529",
                        audience: "Student",
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(10),
                        signingCredentials: creds
                            );
                    dr.Close();
                    command.CommandText = "update Student set reToken = @reToken where IndexNumber=@login;";
                    command.Parameters.AddWithValue("reToken", refreshToken);
                    command.ExecuteNonQuery();
                }
            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken
            }));
        }
Example #3
0
        public async Task <ActionResult <LoggingResult> > GetAsync(DateTimeOffset minTimestamp, DateTimeOffset maxTimestamp, int maxEntries, string searchString)
        {
            var result = new LoggingResult();

            // Build logging request
            var request = new LoggingRequest()
            {
                MinTimeStamp    = minTimestamp.UtcDateTime,
                MaxTimeStamp    = maxTimestamp.UtcDateTime,
                MaxCountEntries = maxEntries,
                SearchString    = searchString
            };

            // Validate
            try
            {
                Validator.ValidateObject(request, new ValidationContext(request), true);
            }
            catch (ValidationException ex)
            {
                return(BadRequest(ex.Message));
            }

            // Simulate some working time
            await Task.Delay(1000);

            // Generate entries
            var messageBuilder    = new StringBuilder(128);
            var entriesToGenerate = maxEntries < 100 ? maxEntries : 100;
            var actTimeStamp      = request.MaxTimeStamp;

            for (var loop = 0; loop < entriesToGenerate; loop++)
            {
                if (actTimeStamp < request.MinTimeStamp)
                {
                    break;
                }

                messageBuilder.Clear();
                messageBuilder.Append("This is a generated message");
                if (!string.IsNullOrEmpty(searchString))
                {
                    messageBuilder.Append(" (");
                    messageBuilder.Append(searchString);
                    messageBuilder.Append(")");
                }

                result.Lines.Add(new LoggingLine()
                {
                    TimeStamp = actTimeStamp,
                    Category  = "Test",
                    Message   = messageBuilder.ToString()
                });

                actTimeStamp = actTimeStamp - TimeSpan.FromMinutes(1.0);
            }

            return(result);
        }
Example #4
0
        public async Task <LoggingRequest> AddEmailAsync(LoggingRequest entity)
        {
            try
            {
                var result = _context.LoggingRequest.Add(entity);
                await _context.SaveChangesAsync();

                return(result);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                throw;
            }
        }
Example #5
0
        public async Task SendEmailAsync(string fromEmail, string toEmail, string subject, string body)
        {
            var mailInformation = new LoggingRequest();

            try
            {
                var client   = new SendGridClient(apiKey);
                var from     = new EmailAddress(fromEmail, null);
                var to       = new EmailAddress(toEmail, null);
                var msg      = MailHelper.CreateSingleEmail(from, to, subject, body, body);
                var response = await client.SendEmailAsync(msg);

                var statusCode = (int)response.StatusCode;
                if (statusCode == 200 || statusCode == 201 || statusCode == 202)
                {
                    mailInformation.Success = true;
                }
                else
                {
                    mailInformation.Success = false;
                }

                mailInformation.FromEmail   = fromEmail;
                mailInformation.ToEmail     = toEmail;
                mailInformation.Subject     = subject;
                mailInformation.Body        = body;
                mailInformation.SendingTime = DateTime.UtcNow;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                mailInformation.Error = ex.Message;
            }
            await _loggingRequestRepository.AddEmailAsync(mailInformation);

            if (mailInformation.Success == true)
            {
                Logger.Debug("Message successfuly sending");
            }
            else
            {
                Logger.Debug("Message sending is fail");
            }
        }
Example #6
0
 public async Task <LoggingResult> GetLoggingAsync(LoggingRequest request)
 {
     try
     {
         return(await _httpClient.GetFromJsonAsync <LoggingResult>(
                    "logginghistory".SetQueryParams(new
         {
             mintimestamp = request.MinTimeStamp.UtcDateTime.ToString("o"),
             maxtimestamp = request.MaxTimeStamp.UtcDateTime.ToString("o"),
             maxentries = request.MaxCountEntries,
             searchstring = request.SearchString
         })
                    .ToString()));
     }
     catch (Exception)
     {
         return(new LoggingResult());
     }
 }
Example #7
0
        public async Task <LoggingResult> GetLoggingAsync(LoggingRequest request)
        {
            var result = new LoggingResult();

            // Simulate some working time
            await Task.Delay(1000);

            // Generate entries
            var messageBuilder    = new StringBuilder(128);
            var entriesToGenerate = request.MaxCountEntries < 100 ? request.MaxCountEntries : 100;
            var actTimeStamp      = request.MaxTimeStamp;

            for (var loop = 0; loop < entriesToGenerate; loop++)
            {
                if (actTimeStamp < request.MinTimeStamp)
                {
                    break;
                }

                messageBuilder.Clear();
                messageBuilder.Append("This is a generated message");
                if (!string.IsNullOrEmpty(request.SearchString))
                {
                    messageBuilder.Append(" (");
                    messageBuilder.Append(request.SearchString);
                    messageBuilder.Append(")");
                }

                result.Lines.Add(new LoggingLine()
                {
                    TimeStamp = actTimeStamp,
                    Category  = "Test",
                    Message   = messageBuilder.ToString()
                });

                actTimeStamp = actTimeStamp - TimeSpan.FromMinutes(1.0);
            }

            return(result);
        }
Example #8
0
        public bool LogMessage(Enumeration.LoggingPriority priority, string transactionReference, object messageObject)
        {
            try
            {
                LoggingRequest lsmr = new LoggingRequest
                {
                    TransactionReference = transactionReference,
                    LoggingPriority      = priority,
                    Message   = new MessageObjectWrapper(messageObject).ToString(),
                    TimeStamp = DateTime.Now
                };

                //Call the Repo and insert the data (LoggingServiceRequest)

                return(true);
            }
            catch
            {
                // do nothing

                return(false);
            }
        }
Example #9
0
        public async void WhenRequestingLoggingProvidesLoggregatorEmitter()
        {
            var containerManager = Substitute.For <IContainerManager>();
            var container        = Substitute.For <IContainerClient>();

            containerManager.GetContainer("abc123").Returns(container);

            var request = new LoggingRequest()
            {
                ApplicationId     = "1",
                Handle            = "abc123",
                InstanceIndex     = "999",
                LoggregatorRouter = "127.0.0.1:5555",
                LoggregatorSecret = "RotoSecret",
            };

            request.DrainUris.Add("http://liquiddraino");

            var handler = new LoggingRequestHandler(containerManager, request);

            await handler.HandleAsync();

            container.Received(x => x.EnableLogging(Arg.Is <ILogEmitter>(e => e.GetType() == typeof(ContainerLogEmitter))));
        }
Example #10
0
 public LoggingResponse(LoggingRequest request, INamedList nl)
     : base(request, nl)
 {
 }
Example #11
0
 public bool LogMessage(LoggingRequest request)
 {
     return(true);
 }
Example #12
0
 public bool LogMessage([FromBody] LoggingRequest request)
 {
     return(Logger.WriteToLog(request));
 }
Example #13
0
 /// <summary>
 /// Logging from the client.
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public static bool WriteToLog(LoggingRequest request)
 {
     return(WriteToLog(request.LogType, request.Message));
 }
 public LoggingRequestHandler(IContainerManager containerManager, Request request)
     : base(containerManager, request)
 {
     this.request = (LoggingRequest)request;
 }