Example #1
0
        public void test_usagelog_prepandpushitem()
        {
            //Arrange
            //It will generate the exception related to large AppName and by consequence we reach the expection section in UsageLog constructor
            var logger = new UsageLog("AppName1", UserId, SessionId);

            //Using reflection we set to true the private property EnableDiagnosticsOutput
            PropertyInfo propertyInfo = typeof(UsageLog).GetProperty("EnableDiagnosticsOutput", BindingFlags.NonPublic | BindingFlags.Instance);

            propertyInfo.SetValue(logger, true, null);

            //Act
            largeAppName.Clear();
            for (int i = 0; i < TEST_MAX_DATA_LENGTH + 1; i++)
            {
                largeAppName.Append(i.ToString());
            }
            logger.Debug("notificationD", largeAppName.ToString());

            //Using reflection we get the private field items inside UsageLog class
            FieldInfo varField  = typeof(UsageLog).GetField("items", BindingFlags.NonPublic | BindingFlags.Instance);
            var       itemsList = (Queue <Dictionary <string, string> >)varField.GetValue(logger);

            //Assert
            //We inserted the Debug
            //Because when using the UploaderExec method is using threads we can have 3 or 4 elements in the list.
            logger.Dispose();
            Assert.IsNotNull(itemsList);                                                                  //Check that itemsList is not null
            Assert.IsTrue(itemsList.Any());                                                               //Check that itemsList has at least one item
            Assert.IsTrue(itemsList.FirstOrDefault().FirstOrDefault().Value.StartsWith("notificationD")); //Check that the value contains the value logged in the Debug method
        }
Example #2
0
        public static void LogUsage(string product, int userId)
        {
            var    httpRequest = HttpContext.Current.Request;
            var    IpAddress = httpRequest.UserHostAddress; //get IP address of the user that sent the request
            string url, httpMethod;
            var    data     = GetRequestData(httpRequest, out url, out httpMethod);
            var    usageLog = new UsageLog()
            {
                HttpMethod     = httpMethod,
                Request        = url,
                IPAddress      = IpAddress,
                Product        = product,
                UserId         = userId,
                AdditionalInfo = data
            };

            try
            {
                var usageLogService = new UsageLogService();
                usageLogService.CreateUsageLog(usageLog);
            }
            catch
            {
                //TODO: Try log and update failed # of tries
            }
        }
        public async Task <IActionResult> Index(string token)
        {
            var shortUrl = await _shortUrlRepository.FindByToken(token);

            if (shortUrl == null)
            {
                return(NotFound());
            }

            // Check if short url's expiration
            if (shortUrl.ExpiresAt.HasValue && shortUrl.ExpiresAt.Value < DateTime.Now)
            {
                return(NotFound());
            }

            var clientInfo = Parser.GetDefault().Parse(Request.Headers["User-Agent"]);

            // TODO: Use NLog for this
            // Log usage info
            var usageLog = new UsageLog
            {
                ShortUrlId    = shortUrl.Id,
                ClientIP      = HttpContext.Connection.RemoteIpAddress.ToString(),
                ClientBrowser = clientInfo.UA.Family,
                ClientDevice  = clientInfo.Device.Family,
                ClientOS      = clientInfo.OS.Family
            };

            await _usageLogRepository.Create(usageLog);

            return(Redirect(shortUrl.OriginalUrl));
        }
Example #4
0
        public UsageResultKind CheckKind(CheckParameter cp)
        {
            if (cp.AllowedTime < cp.UsedSeconds)
            {
                return(UsageResultKind.Blocked);
            }

            // not enough data to understand how many time passed since user started to use the computer
            if (cp.BreakTime > 0)
            {
                UsageLog beforeBreak     = null;
                var      usedBeforeBreak = 0D;

                var usagesArray = cp.Usages.ToArray();
                for (int q = 0; q < usagesArray.Length - 1; q++)
                {
                    var bb = usagesArray[q];
                    var ab = usagesArray[q + 1];

                    if (bb.Finished.TotalSeconds + cp.BreakTime * cp.BreakCorrector <= ab.Started.TotalSeconds)
                    {
                        beforeBreak     = bb;
                        usedBeforeBreak = cp.Usages.Where(_ => _.Started < ab.Started).Sum(_ => _.Used.TotalSeconds);
                    }
                }

                if (beforeBreak == null && cp.UsedSeconds > cp.AllowedTime / 2)
                {
                    return(UsageResultKind.BreakRequired);
                }
            }
            return(UsageResultKind.NoRestriction);
        }
Example #5
0
        public void test_usagelog_properties()
        {
            string AppNameValue = string.Empty;
            var    logger       = new UsageLog("Dynamo", UserId, SessionId);

            //Act
            //Get of the AppName property
            logger.AppName = "DynamoTest";
            AppNameValue   = logger.AppName; //Execute the Get of the AppName property

            //Assert
            //AppName - The exception for AppName property is executed when has special chars
            Assert.Throws <ArgumentException>(() => logger.AppName = specialCharsStr);
            //AppName - The exception for AppName property is executed when exceed 256 chars
            Assert.Throws <ArgumentException>(() => logger.AppName = largeAppName.ToString());

            //SessionID - The exception for SessionID property is executed when has special chars
            Assert.Throws <ArgumentException>(() => logger.SessionID = specialCharsStr);
            //SessionID -The exception for SessionID property is executed when exceed 256 chars
            Assert.Throws <ArgumentException>(() => logger.SessionID = largeAppName.ToString());

            //UserID - - The exception for UserID property is executed when has special chars
            Assert.Throws <ArgumentException>(() => logger.UserID = specialCharsStr);
            //UserID -The exception for UserID property is executed when exceed 256 chars
            Assert.Throws <ArgumentException>(() => logger.UserID = largeAppName.ToString());

            //Validate UploadedItems.GET
            logger.Dispose();
            Assert.AreEqual(logger.UploadedItems, 0);
        }
Example #6
0
        private async Task GenerateFileLog(Message message, BotManager.File file, Bot bot)
        {
            BotUser botUser = null;

            using (_dataFilter.Disable <IMultiTenant>())
                botUser = await _botUserRepository.FindAsync(bu => bu.BotId.CompareTo(bot.Id) == 0 && bu.UserId == message.From.Id);
            if (botUser == null)
            {
                botUser = new BotUser()
                {
                    BotId     = bot.Id,
                    FirstName = message.From.FirstName,
                    IsActive  = true,
                    LastName  = message.From.LastName,
                    UserId    = message.From.Id,
                    UserName  = message.From.Username,
                    TenantId  = bot.TenantId
                };
                await _botUserRepository.InsertAsync(botUser);
            }
            var usageLog = new UsageLog()
            {
                BotUserId       = botUser.Id,
                FileId          = file.Id,
                requestDateTime = DateTime.Now,
                RequestUrl      = file.ShareUrl,//TODO
                TenantId        = bot.TenantId,
                UsageResultType = UsageResultType.Done
            };
            await _usageLogRepository.InsertAsync(usageLog);
        }
        public void LogUsage(UsageLog log)
        {
            _queue.Enqueue(log);

            // only one thread ever to write
            if (_transactionActive)
            {
                return;
            }
            lock (_lock)
            {
                if (_transactionActive)
                {
                    return;
                }
                _transactionActive = true;
            }

            if (_failedToWrite)
            {
                WriteUsageToDisk();
            }
            else
            {
                if (!WriteUsageToDataBase())
                {
                    _failedToWrite = true;
                    WriteUsageToDisk();
                }
            }
            _transactionActive = false;
        }
Example #8
0
        Storage GetStorage(User user, UsageLog usageLog, IEnumerable <Curfew> curfews)
        {
            var st = GetStorage();

            st.Expect(_ => _.GetUser(user.Login)).Return(user);
            st.Expect(_ => _.GetUsage(user.Login, usageLog.Date)).Return(new[] { usageLog });
            st.Expect(_ => _.GetUserCurfews(user)).Return(curfews);

            return(st);
        }
 protected void logUsage()
 {
     using (var curDB = new HelpDesk_DB())
     {
         UsageLog log = new UsageLog();
         log.searchDateTime = DateTime.Now;
         log.NTID_id        = (int)Session["userID"];
         curDB.UsageLogs.Add(log);
         curDB.SaveChanges();
     }
 }
Example #10
0
        public void test_usagelog_exception()
        {
            //Act
            //It will generate the exception related to large AppName and by consequence we reach the expection section in UsageLog constructor
            var logger = new UsageLog(largeAppName.ToString(), UserId, SessionId);

            //Assert
            logger.Dispose();
            //This asserts just check that the properties were released by the Garbage Collector correctly
            Assert.IsNull(logger.AppName);
            Assert.IsNull(logger.UserID);
            Assert.IsNull(logger.SessionID);
        }
Example #11
0
        public void test_usagelog_log()
        {
            //Arrange
            var logger = new UsageLog("AppName1", UserId, SessionId);

            //Assert/Act
            //The next methods only throw the NotImplementedException
            Assert.Throws <NotImplementedException>(() => logger.Log("Exception"));
            Assert.Throws <NotImplementedException>(() => logger.LogError("Exception"));
            Assert.Throws <NotImplementedException>(() => logger.LogWarning("Exception", WarningLevel.Error));
            Assert.Throws <NotImplementedException>(() => logger.Log(new Exception("Test Exception")));

            logger.Dispose();
        }
Example #12
0
        public async Task <bool> LogUsage(UsageLog usageLog)
        {
            bool isTransactionLoggingEnabled = Convert.ToBoolean(_configuration["ConnectionStrings:EnableUsageLog"]);

            if (isTransactionLoggingEnabled)
            {
                var    baseUrl  = _configuration["ConnectionStrings:WebApiBaseUrl"];
                string endpoint = baseUrl + "/api/Logger//api/Logger/api/UsageLog";
                var    content  = new StringContent(JsonConvert.SerializeObject(usageLog), Encoding.UTF8,
                                                    "application/json");

                using var client = new HttpClient();
                await client.PostAsync(endpoint, content);
            }
            return(true);
        }
Example #13
0
        public void test_usagelog_validate_input_null()
        {
            //Arrange
            var  logger      = new UsageLog("AppName1", UserId, SessionId);
            bool validLenght = true;

            //Act
            //Using reflection we execute the ValidateLength method with null in the second parameter
            MethodInfo dynMethod = typeof(UsageLog).GetMethod("ValidateLength", BindingFlags.NonPublic | BindingFlags.Instance);

            validLenght = (bool)dynMethod.Invoke(logger, new object[] { null });

            //Assert
            //The ValidateLength returns false if the parameter passed is false
            logger.Dispose();
            Assert.IsFalse(validLenght);
        }
Example #14
0
        public Detail getLastByCompanyId(int companyId)
        {
            DBHelper._UsageLog dbhelp   = new DBHelper._UsageLog();
            UsageLog           usageLog = dbhelp.GetLastByCommpanyId(companyId);

            return(new Detail()
            {
                CompanyId = usageLog.CompanyId,
                CompanyName = usageLog.Company == null ? "" : usageLog.Company.Name,
                FactoryQty = usageLog.FactoryQty,
                EquipmentQty = usageLog.EquipmentQty,
                DeviceMessage = usageLog.DeviceMessage,
                AlarmMessage = usageLog.AlarmMessage,
                DocSizeInGB = usageLog.DocSizeInGB,
                DocDBPercentage = usageLog.DocDBPercentage,
                UpdatedAt = usageLog.UpdatedAt
            });
        }
Example #15
0
        public void UsageLogAdd()
        {
            UsageLog usage = null;
            var      n     = DateTime.Now;
            var      ts    = TimeSpan.FromSeconds(n.TimeOfDay.Minutes * n.TimeOfDay.Seconds);

            using (var s = new Storage(new Data()))
            {
                using (var t = s.BeginTransaction())
                {
                    usage = s.AddUsage(Login, ts, n.Date, 900);

                    t.Commit();
                }

                Assert.AreEqual(ts, usage.Used);
                Assert.AreEqual(n.Date, usage.Date);

                Assert.AreEqual(s.GetUser(Login).Id, usage.UserId);
            }
        }
Example #16
0
        public void UsageLogSerialization()
        {
            var ul = new UsageLog {
                Id = 123, UserId = 1234, Started = TimeSpan.FromHours(11), Used = TimeSpan.FromHours(1), Date = DateTime.Today
            };

            using (var ms = new MemoryStream())
            {
                ul.WriteTo(ms);

                ms.Position = 0;

                var ul2 = new UsageLog();
                ul2.MergeFrom(ms);

                Assert.AreEqual(ul.Id, ul2.Id);
                Assert.AreEqual(ul.UserId, ul2.UserId);

                Assert.AreEqual(ul.Date, ul2.Date);
                Assert.AreEqual(ul.Used, ul2.Used);
            }
        }
        private bool WriteUsageToDataBase()
        {
            UsageLog logEntry = null;

            try
            {
                while (!_queue.IsEmpty)
                {
                    var hasItem = _queue.TryDequeue(out logEntry);
                    if (hasItem && logEntry != null)
                    {
                        var usageLogger = new DbUsageLogger(logEntry);
                        usageLogger.LogUsage();
                    }
                }
                return(true);
            }
            catch (ThreadAbortException)
            {
                if (logEntry != null)
                {
                    _queue.Enqueue(logEntry);
                }
                _failedToWrite = true;
                return(false);
            }
            catch (Exception ex)
            {
                if (logEntry != null)
                {
                    _queue.Enqueue(logEntry);
                }
                _failedToWrite = true;

                ErrorLog.Error(ex, "QueuedUsageLogger.WriteUsageLog, items in queue: {0}", _queue.Count);
                return(false);
            }
        }
Example #18
0
        public void test_usagelog_upload_item_exception()
        {
            //Arrange
            var  logger       = new UsageLog("AppName1", UserId, SessionId);
            bool uploadedItem = true;
            Dictionary <String, String> item = null;

            //Act
            //set the EnableDiagnosticsOutput=true
            PropertyInfo propertyInfo = typeof(UsageLog).GetProperty("EnableDiagnosticsOutput", BindingFlags.NonPublic | BindingFlags.Instance);

            propertyInfo.SetValue(logger, true, null);

            //Using reflection we execute the ValidateLength method with null in the second parameter
            MethodInfo dynMethod = typeof(UsageLog).GetMethod("UploadItem", BindingFlags.NonPublic | BindingFlags.Instance);

            uploadedItem = (bool)dynMethod.Invoke(logger, new object[] { item });

            //Assert
            //The UploadItem returns false if the parameter passed is false
            logger.Dispose();
            Assert.IsFalse(uploadedItem);
        }
Example #19
0
        public HttpResponseMessage AddEdit(int userId, string pageUrl, byte actionType)
        {
            //Read = 0,
            //Login = 1,
            //Logoff = 2,
            //Write = 3,
            //Search = 4,
            //Scan = 5
            var usageLog = new UsageLog()
            {
                UserId     = userId,
                PageUrl    = pageUrl,
                ActionType = (UsageLogActionType)actionType,
                OccurredOn = DateTime.Now
            };
            var repo   = new UsageLogRepository();
            var entity = repo.AddEdit(usageLog);

            var json = JsonConvert.SerializeObject(entity);

            return(new HttpResponseMessage {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            });
        }
Example #20
0
        public void test_usagelog_log_methods()
        {
            //Arrange
            //It will generate the exception related to large AppName and by consequence we reach the expection section in UsageLog constructor
            var logger = new UsageLog("AppName1", UserId, SessionId);

            //Act
            logger.Debug("notificationD", "Debug Message");
            logger.Error("notificationE", "Error Message");
            logger.Log("notificationL", "Log Message");
            logger.Verbose("notificationV", "Verbose Message");

            //Using reflection we get the private field items inside UsageLog class
            FieldInfo varField  = typeof(UsageLog).GetField("items", BindingFlags.NonPublic | BindingFlags.Instance);
            var       itemsList = (Queue <Dictionary <string, string> >)varField.GetValue(logger);

            //Assert
            //We inserted the Debug, Error, Log and Verbose so we should have only four elements in the queue
            //Because when using the UploaderExec method is using threads we can have 3 or 4 elements in the list.
            logger.Dispose();
            Assert.IsNotNull(itemsList);            //Check that itemsList is not null
            Assert.IsTrue(itemsList.Any());         //Check that itemsList has at least one item
            Assert.LessOrEqual(itemsList.Count, 4); //Check that itemsList has less than 4 or equals to 4
        }
Example #21
0
        public void test_usagelog_push_item()
        {
            //Arrange
            //It will generate the exception related to large AppName and by consequence we reach the expection section in UsageLog constructor
            var logger = new UsageLog("AppName1", UserId, SessionId);

            //Using reflection we set to true the private property EnableDiagnosticsOutput
            PropertyInfo propertyInfo = typeof(UsageLog).GetProperty("EnableDiagnosticsOutput", BindingFlags.NonPublic | BindingFlags.Instance);

            propertyInfo.SetValue(logger, true, null);

            StringBuilder debugMessage = new StringBuilder("Debug Message ");

            //Act
            for (int i = 0; i < TEST_MAX_DATA_LENGTH + 1; i++)
            {
                debugMessage.Append(i.ToString());
            }
            logger.Debug("notificationD", debugMessage.ToString());


            //Using reflection we get the private field items inside UsageLog class
            FieldInfo varField = typeof(UsageLog).GetField("items", BindingFlags.NonPublic | BindingFlags.Instance);

            Queue <Dictionary <string, string> > itemsLarge = new Queue <Dictionary <string, string> >();

            for (int i = 0; i < TEST_MAX_DATA_LENGTH + 1; i++)
            {
                var item = new Dictionary <string, string>
                {
                    { "Tag", i.ToString() },
                    { "Priority", "PR" },
                    { "AppIdent", "AN" },
                    { "UserID", "UserID" },
                    { "SessionID", "Session" },
                    { "DateTime", DateTime.Now.ToString() },
                    { "MicroTime", "MT" },
                    { "Data", "Test" + i.ToString() }
                };

                itemsLarge.Enqueue(item);
            }
            //This will set the items field with 5000000 items
            varField.SetValue(logger, itemsLarge);


            var itemFinal = new Dictionary <string, string>
            {
                { "Tag", "Test1" },
                { "Priority", "PR" },
                { "AppIdent", "AN" },
                { "UserID", "UserID" },
                { "SessionID", "Session" },
                { "DateTime", DateTime.Now.ToString() },
                { "MicroTime", "MT" },
                { "Data", "Test1" }
            };

            //Using reflection we execute the PushItem method, the second parameter has to be a Dictionary<string, string>
            //This will rearch the validation inside PushItem about MAX_ITEMS
            MethodInfo dynMethod = typeof(UsageLog).GetMethod("PushItem", BindingFlags.NonPublic | BindingFlags.Instance);

            dynMethod.Invoke(logger, new object[] { itemFinal });

            var itemsList = (Queue <Dictionary <string, string> >)varField.GetValue(logger);

            //Assert
            //We inserted the Debug, Error, Log and Verbose so we should have only four elements in the queue
            //Because when using the UploaderExec method is using threads we can have 3 or 4 elements in the list.
            logger.Dispose();
            Assert.IsNotNull(itemsList);                                //Check that itemsList is not null
            Assert.IsTrue(itemsList.Any());                             //Check that itemsList has at least one item
            Assert.AreEqual(itemsList.Count, TEST_MAX_DATA_LENGTH + 1); //Check that itemsList has 500 000 + 1 items
        }
Example #22
0
 public void CreateUsageLog(UsageLog usageLog)
 {
     mongoDbContext.UsageLogs.InsertOneAsync(usageLog);
 }
Example #23
0
 public DbUsageLogger(UsageLog usageLog)
 {
     _usageLog = usageLog;
 }
Example #24
0
        public void InsertData()
        {
            using (var db = new Data())
                try
                {
                    var u = new User()
                    {
                        Login = "******", Name = "testName"
                    };
                    var i = db.InsertWithInt32Identity(u);

                    u.Id = i;

                    var totalTime = new TimeSpan(GetHour(), GetMinute(), 00);
                    var cf        = new Curfew()
                    {
                        UserId = i, WeekDay = "Mo", Time = totalTime
                    };
                    var cfi = db.InsertWithInt32Identity(cf);

                    var user = db.Users.LoadWith(_ => _.Curfews).FirstOrDefault(_ => _.Id == i);
                    Assert.IsNotNull(user);

                    var curfew = db.Curfews.LoadWith(_ => _.User).FirstOrDefault(_ => _.Id == cfi);
                    Assert.IsNotNull(curfew);
                    Assert.AreEqual(TimeSpan.Zero, curfew.Break);
                    Assert.AreEqual(totalTime, curfew.Time);

                    Assert.AreEqual(1, user.Curfews.Count());
                    Assert.IsNotNull(curfew.User);

                    var testTime      = new TimeSpan(GetHour(), GetMinute(), 00);
                    var testBreakTime = new TimeSpan(0, _rnd.Next(20, 59), 0);
                    var cfBreak       = new Curfew()
                    {
                        UserId = i, WeekDay = "Mo", Time = testTime, Break = testBreakTime
                    };
                    var cfiBreak = db.InsertWithInt32Identity(cfBreak);
                    cfBreak = db.Curfews.LoadWith(_ => _.User).FirstOrDefault(_ => _.Id == cfiBreak);

                    Assert.AreEqual(i, cfBreak.UserId);
                    Assert.AreEqual(testTime, cfBreak.Time);
                    Assert.AreEqual(testBreakTime, cfBreak.Break);

                    var usageDate = DateTime.Today;
                    var usedTime  = new TimeSpan(GetHour(), GetMinute(), 0);
                    var startTime = new TimeSpan(GetHour(), GetMinute(), GetMinute());

                    var usage = new UsageLog()
                    {
                        UserId = user.Id, Date = usageDate, Used = usedTime, Started = startTime
                    };
                    var usageId = db.InsertWithInt32Identity(usage);
                    usage = db.UsageLogs.FirstOrDefault(_ => _.Id == usageId);

                    Assert.AreEqual(user.Id, usage.UserId);
                    Assert.AreEqual(usedTime, usage.Used);
                    Assert.AreEqual(usageDate, usage.Date);
                    Assert.AreEqual(startTime, usage.Started);
                }
                catch (LinqToDBConvertException l2dbe)
                {
                    Console.WriteLine("{0}", l2dbe);
                    throw;
                }
        }
Example #25
0
        public void test_usagelog_validate_inputs_exceptions()
        {
            //Arrange
            var logger = new UsageLog("AppName1", UserId, SessionId);

            //Act
            //Create a large string so the validations will fail when calling the logger functions
            largeAppName.Clear();
            for (int i = 0; i < TEST_MAX_DATA_LENGTH + 1; i++)
            {
                largeAppName.Append(i.ToString());
            }
            try
            {
                //Exception when the first parameter of Debug method is null
                logger.Debug(null, "Debug Message");
            }
            catch (ArgumentNullException ex)
            {
                Assert.IsTrue(ex.Message.Contains("Tag must not be null"));
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }

            try
            {
                //Exception when the second parameter of Error method is null
                logger.Error("notificationE", null);
            }
            catch (ArgumentNullException ex)
            {
                Assert.IsTrue(ex.Message.Contains("Text must not be null"));
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }

            try
            {
                //Exception when the second parameter of Log method is null
                logger.Log(largeAppName.ToString(), "Log Message");
            }
            catch (ArgumentException ex)
            {
                Assert.IsTrue(ex.Message.Contains("Tag must be 256 chars or less"));
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }

            try
            {
                //Exception when the second parameter of Verbose method has special characters
                logger.Verbose(specialCharsStr, "Verbose Message");
            }
            catch (ArgumentException ex)
            {
                Assert.IsTrue(ex.Message.Contains("Tag must only be letters, numbers or '-', '.'"));
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                logger.Dispose();
            }
        }