Example #1
0
 public void StartCount(int stage)
 {
     IsStartCount[stage] = true;
     NowSec[stage]       = Now.Second;
     GoalTimes[stage]    = Now.AddHours(ResourceDatas[stage].hour);
     GoalTimes[stage]    = GoalTimes[stage].AddMinutes(ResourceDatas[stage].min);
 }
Example #2
0
 public async Task WithStartBeforeEnd_Throws()
 {
     _ = await Assert.ThrowsAsync <AblyException>(() =>
                                                  _channel.HistoryAsync(new PaginatedRequestParams {
         Start = Now, End = Now.AddHours(-1)
     }));
 }
Example #3
0
        public async Task ShouldKeepCurrentTokenParamsAndOptionsEvenIfCurrentTokenIsValidAndNoNewTokenIsRequested()
        {
            var client = GetRestClient(
                null,
                opts => opts.TokenDetails = new TokenDetails("boo")
            {
                Expires = Now.AddHours(10)
            });

            var testAblyAuth      = new TestAblyAuth(client.Options, client);
            var customTokenParams = TokenParams.WithDefaultsApplied();

            customTokenParams.Ttl       = TimeSpan.FromHours(2);
            customTokenParams.Timestamp = Now.AddHours(1);

            var customAuthOptions = AuthOptions.FromExisting(testAblyAuth.Options);

            customAuthOptions.UseTokenAuth = true;

            await testAblyAuth.AuthorizeAsync(customTokenParams, customAuthOptions);

            var expectedTokenParams = customTokenParams.Clone();

            expectedTokenParams.Timestamp = null;
            testAblyAuth.CurrentTokenParams.Should().BeEquivalentTo(expectedTokenParams);
            testAblyAuth.CurrentAuthOptions.Should().BeSameAs(customAuthOptions);
        }
        public void UpdatePublishDateOfExistintPost_WillUpdateTheDateAndTimeCorrectly()
        {
            Session.Store(new Post {
                PublishAt = Now.AddDays(-3)
            });
            Session.Store(new Post {
                PublishAt = Now.AddHours(-1)
            });
            Session.Store(new Post {
                PublishAt = Now.AddHours(12)
            });
            Session.SaveChanges();

            var lastPost = Session.Query <Post>()
                           .OrderByDescending(post => post.PublishAt)
                           .First();

            Assert.Equal(Now.AddHours(12), lastPost.PublishAt);

            var rescheduler = new PostSchedulingStrategy(Session, Now);

            lastPost.PublishAt = rescheduler.Schedule(Now.AddHours(6));
            Session.SaveChanges();

            Assert.Equal(Now.AddHours(6), lastPost.PublishAt);
        }
        public async Task WithTokenErrorAndTokenRenewalFails_ShouldRaiseErrorAndTransitionToFailed()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            var client = GetClientWithFakeTransport(opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    throw new AblyException(new ErrorInfo()
                    {
                        Code = 123
                    });
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error) { Error = new ErrorInfo("Unauthorised", _tokenErrorCode, HttpStatusCode.Unauthorized) });

            client.Connection.State.Should().Be(ConnectionState.Failed);
            client.Connection.ErrorReason.Should().NotBeNull();
            client.Connection.ErrorReason.Code.Should().Be(123);
        }
        public async Task WithTokenErrorAndNonRenewableToken_ShouldRaiseErrorAndTransitionToFailed()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            bool renewTokenCalled = false;
            var  client           = GetClientWithFakeTransport(opts =>
            {
                opts.Key               = "";
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    renewTokenCalled = true;
                    return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error) { Error = new ErrorInfo("Unauthorised", _tokenErrorCode, HttpStatusCode.Unauthorized) });

            renewTokenCalled.Should().BeFalse();
            client.Connection.State.Should().Be(ConnectionState.Failed);
            client.Connection.ErrorReason.Should().NotBeNull();
            client.Connection.ErrorReason.Code.Should().Be(_tokenErrorCode);
        }
Example #7
0
        public async Task WithDefaultTokenParamsAndTokenParamsSpecified_ShouldUseOnlyParamsPassedIntoTheMethod()
        {
            var client = GetRestClient(
                null,
                options => options.DefaultTokenParams = new TokenParams
            {
                ClientId = "123", Ttl = TimeSpan.FromHours(2)
            });

            var capability = new Capability();

            capability.AddResource("a").AllowAll();
            var methodParams = new TokenParams
            {
                Capability = capability,
                ClientId   = "999",
                Ttl        = TimeSpan.FromMinutes(1),
                Nonce      = "123",
                Timestamp  = Now.AddHours(1)
            };

            await client.Auth.RequestTokenAsync(methodParams);

            var data = LastRequest.PostData as TokenRequest;

            data.Capability.Should().Be(capability);
            data.ClientId.Should().Be(methodParams.ClientId);
            data.Ttl.Should().Be(methodParams.Ttl);
            data.Nonce.Should().Be(methodParams.Nonce);
            data.Timestamp.Should().Be(methodParams.Timestamp);
        }
Example #8
0
        public async Task <List <WeatherData> > GetAll(int userId, string deviceId, int lastHours = 24)
        {
            var dataList = new List <WeatherData>();
            var lastDate = Now.AddHours(-lastHours);

            var activeProfile = await Db.Profiles.Where(x => x.UserId == userId && x.Active).SingleOrDefaultAsync();

            var locationDtos = await locationRepository.GetLocationDtos(deviceId, activeProfile.Id);

            foreach (var locationDto in locationDtos)
            {
                var weatherData = new WeatherData();
                weatherData.Location    = locationDto;
                weatherData.WeatherList = await Db.Weathers
                                          .Where(x => x.LocationId == locationDto.Id && x.CreatedAt > lastDate)
                                          .OrderByDescending(x => x.Id).Select(x => new WeatherDto()
                {
                    Temperature = x.Temperature,
                    Humidity    = x.Humidity,
                    Date        = x.CreatedAt
                }).ToListAsync();

                dataList.Add(weatherData);
            }


            return(dataList);
        }
Example #9
0
        public void Init()
        {
            Tracker = new LockTracker("xxx");
            Now     = DateTimeOffset.Now.AddHours(2);
            Later   = Now.AddHours(4);

            SystemTime.Now = () => Now;
        }
        public void WhenPostingNewPostWithPublishDateSpecified_AndThereIsNoLastPost_ScheduleItForSpecifiedDate()
        {
            var rescheduler = new PostSchedulingStrategy(Session, Now);

            var scheduleDate = Now.AddHours(1);
            var result       = rescheduler.Schedule(scheduleDate);

            Assert.Equal(scheduleDate, result);
        }
Example #11
0
        public async Task WithTokenErrorAndRenewableToken_ShouldRenewTokenAutomaticallyWithoutEmittingError()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            bool renewTokenCalled = false;
            var  client           = GetClientWithFakeTransport(
                opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
                opts.AutoConnect       = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    if (renewTokenCalled == false)
                    {
                        renewTokenCalled = true;
                    }

                    return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            client.Connect();
            List <ErrorInfo> raisedErrors = new List <ErrorInfo>();

            client.Connection.On((args) =>
            {
                if (args.HasError)
                {
                    raisedErrors.Add(args.Reason);
                }
            });

            await client.WaitForState(ConnectionState.Connecting);

            client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo("Unauthorised", ErrorCodes.TokenError, HttpStatusCode.Unauthorized)
            });

            await client.ProcessCommands();

            renewTokenCalled.Should().BeTrue();
            var currentToken = client.RestClient.AblyAuth.CurrentToken;

            currentToken.Token.Should().Be(_returnedDummyTokenDetails.Token);
            currentToken.ClientId.Should().Be(_returnedDummyTokenDetails.ClientId);
            currentToken.Expires.Should().BeCloseTo(_returnedDummyTokenDetails.Expires, TimeSpan.FromMilliseconds(20));
            raisedErrors.Should().BeEmpty("No errors should be raised!");
        }
Example #12
0
    public bool IsYesTodayBySecond(int second, bool realy = false)
    {
        DateTime target   = FromSecond(second);
        DateTime yestoday = Now.AddHours(-24);

        if (!realy)
        {
            target = RelativeDate(target);
        }
        return(target.Year == yestoday.Year && target.Month == yestoday.Month && target.Day == yestoday.Day);
    }
Example #13
0
        public async Task WithTokenErrorTwice_ShouldNotRenewAndRaiseErrorAndTransitionToDisconnected()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            var renewCount = 0;
            var client     = GetClientWithFakeTransport(
                opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
                opts.AutoConnect       = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    renewCount++;
                    return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            bool disconnected = false;

            client.Connection.On(ConnectionEvent.Disconnected, (_) =>
            {
                disconnected = true;
            });
            client.Connect();

            await client.WaitForState(ConnectionState.Connecting);

            client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo("Unauthorised", ErrorCodes.TokenError, HttpStatusCode.Unauthorized)
            });

            await client.ProcessCommands();

            client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo("Unauthorised", ErrorCodes.TokenError, HttpStatusCode.Unauthorized)
            });

            await client.ProcessCommands();

            await client.WaitForState(ConnectionState.Disconnected);

            renewCount.Should().Be(1);
            disconnected.Should().BeTrue();
            client.Connection.ErrorReason.Should().NotBeNull();
        }
        }         // CalculateHourlyTodaysApprovals

        private int CalculateLastHourApprovals()
        {
            DateTime anHourAgo = Now.AddHours(-1);

            return(this.cashRequestsRepository.GetAll().Count(cr =>
                                                              cr.UnderwriterDecisionDate.HasValue &&
                                                              cr.UnderwriterDecisionDate.Value >= anHourAgo &&
                                                              cr.AutoDecisionID == 1 &&
                                                              !cr.Customer.IsTest
                                                              ));
        }         // CalculateLastHourApprovals
Example #15
0
 public ConnectionFailuresOnceConnectedSpecs(ITestOutputHelper output) : base(output)
 {
     Now         = DateTimeOffset.Now;
     _validToken = new TokenDetails("id")
     {
         Expires = Now.AddHours(1)
     };
     _renewTokenCalled = false;
     _tokenErrorInfo   = new ErrorInfo()
     {
         Code = _tokenErrorCode, StatusCode = HttpStatusCode.Unauthorized
     };
 }
 public ConnectionFailuresOnceConnectedSpecs(ITestOutputHelper output)
     : base(output)
 {
     SetNowFunc(() => DateTimeOffset.UtcNow);
     _validToken = new TokenDetails("id")
     {
         Expires = Now.AddHours(1)
     };
     _renewTokenCalled = false;
     _tokenErrorInfo   = new ErrorInfo {
         Code = ErrorCodes.TokenError, StatusCode = HttpStatusCode.Unauthorized
     };
 }
Example #17
0
        /// <summary>
        /// Method scans the file.
        /// Note: Same implementation as of ScanDir but with one file only
        /// </summary>
        static void ScanFile()
        {
            WriteLine("-- File Scanner --");
            WriteLine();
            ForegroundColor = Cyan;
            Write("[?] Enter File Path : ");
            ResetColor();

            FileInfo fileInfo = new FileInfo(ReadLine());

            var vt = new VirusTotal(File.ReadAllText(Globals.ApiKey));

            ForegroundColor = Blue;
            WriteLine($"[*] Scan Started At {Globals.CurrentDateTime}");
            ResetColor();
            var report = Report(Globals.GetSHA256(fileInfo.FullName));

            ForegroundColor = Yellow;
            WriteLine($"[~] Scanning {fileInfo.FullName}");
            ResetColor();
            var isMisc = false;

            if (report.ResponseCode == FileReportResponseCode.Present)
            {
                int detection = 0;
                foreach (var av in report.Scans.Keys)
                {
                    if (report.Scans[av].Detected)
                    {
                        detection++;
                    }
                }
                FormatDetection(detection);
            }
            else
            {
                var scanReport = SendScan(fileInfo);
                var file       = new string[] { $"{scanReport.SHA256}|{fileInfo.FullName}" };
                File.WriteAllLines(Globals.MiscFile, file);
                isMisc = true;
            }
            ForegroundColor = Blue;
            WriteLine($"[*] Scan Completed At {Globals.CurrentDateTime}");
            ResetColor();
            if (isMisc)
            {
                WriteLine();
                WriteLine("We found some miscellaneous files");
                WriteLine($"Try scaning misc file after {Now.AddHours(5):dd/MM/yyyy hh:mm:ss tt}");
            }
        }
Example #18
0
        public async Task WithTokenErrorAndTokenRenewalFails_ShouldRaiseErrorAndTransitionToDisconnected()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            var taskAwaiter = new TaskCompletionAwaiter(taskCount: 2);
            var client      = GetClientWithFakeTransport(
                opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    throw new AblyException(new ErrorInfo {
                        Code = ErrorCodes.TokenError
                    });
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            var stateChanges = new List <ConnectionStateChange>();

            client.Connection.On(stateChange =>
            {
                if (stateChange.Current == ConnectionState.Disconnected)
                {
                    taskAwaiter.Tick();
                }

                stateChanges.Add(stateChange);
            });

            await client.WaitForState(ConnectionState.Connecting);

            client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo("Unauthorised", ErrorCodes.TokenError, HttpStatusCode.Unauthorized)
            });

            await taskAwaiter.Task;

            stateChanges.Count.Should().BeGreaterThan(0);
            client.Connection.ErrorReason.Should().NotBeNull();
            client.Connection.ErrorReason.Code.Should().Be(ErrorCodes.TokenError);
        }
        public void WhenPostingNewPostWithPublishDateSpecified_AndTheLastPostPublishDateIsAFewDaysAgo_ScheduleItForSpecifiedDate()
        {
            Session.Store(new Post {
                PublishAt = Now.AddDays(-3)
            });
            Session.SaveChanges();

            var rescheduler = new PostSchedulingStrategy(Session, Now);

            var scheduleDate = Now.AddHours(1);
            var result       = rescheduler.Schedule(scheduleDate);

            Assert.Equal(scheduleDate, result);
            Assert.NotEqual(scheduleDate.AddDays(-2), result);
        }
        public void WhenPostingNewPost_DoNotReschedulePublishedPosts()
        {
            Session.Store(new Post {
                PublishAt = Now.AddDays(-3)
            });
            Session.Store(new Post {
                PublishAt = Now.AddHours(-1)
            });
            Session.SaveChanges();

            var rescheduler = new PostSchedulingStrategy(Session, Now);

            rescheduler.Schedule();

            Assert.Empty(Session.Query <Post>().Where(post => post.PublishAt > Now));
        }
Example #21
0
        public async Task <List <CombiLogDto> > GetDtos(string ownedDeviceId, int lastHours = 12)
        {
            var afterDate = Now.AddHours(-lastHours);

            var query = Db.CombiLogs.Where(x => x.DeviceId == ownedDeviceId && x.CreatedAt > afterDate).OrderByDescending(x => x.Id);

            if ((await query.CountAsync()) < 10)
            {
                query = Db.CombiLogs.Where(x => x.DeviceId == ownedDeviceId).Take(10).OrderByDescending(x => x.Id);
            }

            return(await query.Select(x => new CombiLogDto()
            {
                Date = x.CreatedAt,
                State = x.State
            }).ToListAsync());
        }
        public async Task WithTokenErrorAndRenewableToken_ShouldRenewTokenAutomaticallyWithoutEmittingError()
        {
            Now = DateTimeOffset.Now;
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            bool renewTokenCalled = false;
            var  client           = GetClientWithFakeTransport(opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    renewTokenCalled = true;
                    return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            List <ErrorInfo> raisedErrors = new List <ErrorInfo>();

            client.Connection.InternalStateChanged += (sender, args) =>
            {
                if (args.HasError)
                {
                    raisedErrors.Add(args.Reason);
                }
            };

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error) { Error = new ErrorInfo("Unauthorised", _tokenErrorCode, HttpStatusCode.Unauthorized) });

            renewTokenCalled.Should().BeTrue();
            var currentToken = client.RestClient.AblyAuth.CurrentToken;

            currentToken.Token.Should().Be(_returnedDummyTokenDetails.Token);
            currentToken.ClientId.Should().Be(_returnedDummyTokenDetails.ClientId);
            currentToken.Expires.Should().BeCloseTo(_returnedDummyTokenDetails.Expires);
            raisedErrors.Should().BeEmpty("No errors should be raised!");
        }
            private IEnumerable <IThreadSafeTimeEntry> getTimeEntries(
                int numberOfTimeEntries,
                bool withProject,
                int initalId       = 0,
                bool activeProject = true,
                long projectId     = 4)
            {
                if (numberOfTimeEntries == 0)
                {
                    return(new List <IThreadSafeTimeEntry>());
                }

                var workspace = new MockWorkspace {
                    Id = 12
                };
                var project = new MockProject {
                    Id = projectId, Name = $"{projectId}", Active = activeProject
                };

                return(Enumerable.Range(initalId, numberOfTimeEntries)
                       .Select(index =>
                {
                    var entry = new MockTimeEntry
                    {
                        Id = index,
                        UserId = 10,
                        WorkspaceId = workspace.Id,
                        Workspace = workspace,
                        At = Now,
                        Start = Now.AddHours(index % 23),
                        Description = $"te{index}"
                    };

                    if (withProject)
                    {
                        entry.ProjectId = project.Id;
                        entry.Project = project;
                    }

                    return entry;
                }));
            }
Example #24
0
        protected virtual void GatherData()
        {
            Cfg.Load();

            DB.ForEachRowSafe(
                ProcessRow,
                "LoadAutoReapprovalData",
                CommandSpecies.StoredProcedure,
                new QueryParameter("CustomerID", Args.CustomerID),
                new QueryParameter("Now", Now)
                );

            GatherAvailableFunds();

            MetaData.Validate();

            Trail.MyInputData.Init(Now, null);
            Trail.MyInputData.ReApproveAmount     = MetaData.ApprovedAmount;
            Trail.MyInputData.FraudStatus         = MetaData.FraudStatus;
            Trail.MyInputData.ManualApproveDate   = MetaData.LacrTime;
            Trail.MyInputData.WasLate             = MetaData.LateLoanCount > 0;
            Trail.MyInputData.WasRejected         = MetaData.RejectAfterLacrID > 0;
            Trail.MyInputData.NumOutstandingLoans = MetaData.OpenLoanCount;
            Trail.MyInputData.HasLoanCharges      = MetaData.SumOfCharges > 0.00000001m;
            Trail.MyInputData.LacrID = MetaData.LacrID;

            Trail.MyInputData.MaxLateDays                           = LatePayments.Count < 1 ? 0 : LatePayments.Select(lp => lp.Delay).Max();
            Trail.MyInputData.NewDataSourceAdded                    = NewMarketplaces.Count > 0;
            Trail.MyInputData.AvaliableFunds                        = Funds.Available - Funds.Reserved;
            Trail.MyInputData.AutoReApproveMaxLacrAge               = Cfg.MaxLacrAge;
            Trail.MyInputData.AutoReApproveMaxLatePayment           = Cfg.MaxLatePayment;
            Trail.MyInputData.AutoReApproveMaxNumOfOutstandingLoans = Cfg.MaxNumOfOutstandingLoans;
            Trail.MyInputData.MinLoan = ConfigManager.CurrentValues.Instance.MinLoan;

            Output = new AutoReapprovalOutput {
                AppValidFor               = Now.AddHours(MetaData.OfferLength),
                IsEmailSendingBanned      = MetaData.IsEmailSendingBanned,
                LastApprovedCashRequestID = MetaData.LacrID,
            };
        }         // GatherData
Example #25
0
        public async Task ShouldKeepTokenParamsAndAuthOptionsExceptForceAndCurrentTimestamp()
        {
            var client            = GetRestClient();
            var testAblyAuth      = new TestAblyAuth(client.Options, client);
            var customTokenParams = TokenParams.WithDefaultsApplied();

            _ = customTokenParams.Merge(new TokenParams {
                Ttl = TimeSpan.FromHours(2), Timestamp = Now.AddHours(1)
            });
            var customAuthOptions = AuthOptions.FromExisting(testAblyAuth.Options);

            customAuthOptions.UseTokenAuth = true;

            await testAblyAuth.AuthorizeAsync(customTokenParams, customAuthOptions);

            var expectedTokenParams = customTokenParams.Clone();

            expectedTokenParams.Timestamp = null;
            testAblyAuth.CurrentTokenParams.Should().BeEquivalentTo(expectedTokenParams);

            testAblyAuth.CurrentAuthOptions.Should().BeSameAs(customAuthOptions);
            testAblyAuth.CurrentTokenParams.Timestamp.Should().Be(null);
        }
Example #26
0
        public async Task ShouldKeepTokenParamsAndAuthOptionsExcetpForceAndCurrentTimestamp()
        {
            var client            = GetRestClient();
            var testAblyAuth      = new TestAblyAuth(client.Options, client);
            var customTokenParams = new TokenParams()
            {
                Ttl = TimeSpan.FromHours(2), Timestamp = Now.AddHours(1)
            };
            var customAuthOptions = new AuthOptions()
            {
                UseTokenAuth = true, Force = true
            };

            await testAblyAuth.AuthoriseAsync(customTokenParams, customAuthOptions);

            var expectedTokenParams = customTokenParams.Clone();

            expectedTokenParams.Timestamp = null;
            testAblyAuth.CurrentTokenParams.ShouldBeEquivalentTo(expectedTokenParams);

            testAblyAuth.CurrentAuthOptions.Should().BeSameAs(customAuthOptions);
            testAblyAuth.CurrentTokenParams.Timestamp.Should().Be(null);
            testAblyAuth.CurrentAuthOptions.Force.Should().BeFalse();
        }
Example #27
0
        public int SaveData(AccountDbContext context)
        {
            CheckForNewCurrentDataRow(context);

            List <LimitDataArchiveItem> localDataArchive;

            lock (DataArchiveLockObject)
            {
                var dataArchive = GetDataArchive(context);
                localDataArchive = new List <LimitDataArchiveItem>(dataArchive);
            }

            // Сохраним все несохранённые записи
            var repository = context.GetLimitDataRepository();
            var rows       = localDataArchive.Where(t => t.Id == Guid.Empty).ToArray();

            foreach (var row in rows)
            {
                var limitData = new LimitData()
                {
                    BeginDate         = row.BeginDate,
                    EndDate           = row.EndDate,
                    Type              = LimitDataType.Per5Minutes,
                    EventsRequests    = row.EventsRequests,
                    EventsSize        = row.EventsSize,
                    LogSize           = row.LogSize,
                    MetricsRequests   = row.MetricsRequests,
                    MetricsSize       = row.MetricsSize,
                    UnitTestsRequests = row.UnitTestsRequests,
                    UnitTestsSize     = row.UnitTestsSize
                };
                limitData.UnitTestData = row.UnitTestData.Select(t => new LimitDataForUnitTest()
                {
                    Id           = Guid.NewGuid(),
                    LimitData    = limitData,
                    UnitTestId   = t.Key,
                    ResultsCount = t.Value.ResultsCount
                }).ToList();
                repository.Add(limitData);

                context.SaveChanges();

                row.Id           = limitData.Id;
                row.UnitTestData = null;
            }

            // Проверим, есть ли запись за вчера с данными за целый день
            var yesterday         = Now.Date.AddDays(-1);
            var totalForYesterday = repository.QueryAll().FirstOrDefault(t => t.Type == LimitDataType.Per1Day && t.BeginDate == yesterday);

            if (totalForYesterday == null)
            {
                // Если записи за вчера нет, создадим её
                totalForYesterday = new LimitData()
                {
                    BeginDate = yesterday,
                    EndDate   = yesterday.AddDays(1),
                    Type      = LimitDataType.Per1Day
                };

                // Заполним данными из архива за вчера
                var yesterdayArchive = localDataArchive.Where(t => t.BeginDate >= yesterday && t.BeginDate < yesterday.AddDays(1)).ToList();

                totalForYesterday.EventsRequests    = yesterdayArchive.Sum(t => t.EventsRequests);
                totalForYesterday.EventsSize        = yesterdayArchive.Sum(t => t.EventsSize);
                totalForYesterday.UnitTestsRequests = yesterdayArchive.Sum(t => t.UnitTestsRequests);
                totalForYesterday.UnitTestsSize     = yesterdayArchive.Sum(t => t.UnitTestsSize);
                totalForYesterday.MetricsRequests   = yesterdayArchive.Sum(t => t.MetricsRequests);
                totalForYesterday.MetricsSize       = yesterdayArchive.Sum(t => t.MetricsSize);
                totalForYesterday.LogSize           = yesterdayArchive.Sum(t => t.LogSize);

                repository.Add(totalForYesterday);
                context.SaveChanges();
            }

            // Удалим из архива в памяти те, которые старше 48 часов (сегодня + вчера)
            lock (DataArchiveLockObject)
            {
                var dataArchive = GetDataArchive(context);
                dataArchive.RemoveAll(t => t.BeginDate < Now.AddHours(-48));
            }

            // Удалим из базы те, которые старше старше 48 часов (сегодня + вчера)
            repository.RemoveOld(Now.AddHours(-48), LimitDataType.Per5Minutes);

            return(rows.Length);
        }
Example #28
0
        /// <summary>
        /// Method Scans the curr dir.
        /// </summary>
        static void ScanCurrDir()
        {
            int total = 0;

            WriteLine("-- Directory Scanner --");
            WriteLine();
            ForegroundColor = Blue;
            WriteLine($"[*] Scan Started At {Globals.CurrentDateTime}");
            ResetColor();

            // getting filenames
            var files = Directory.GetFiles(CurrentDirectory, "*", SearchOption.AllDirectories);
            // instacing misc to store misc files
            var misc   = new System.Collections.Generic.List <string>();
            var isMisc = false; // flag to check if any misc file

            foreach (var file in files)
            {
                if (++total > 5000)  // safeguard api calls
                {
                    ForegroundColor = Red;
                    WriteLine("You reached  5000/per day scan limit");
                    WriteLine("If you try to scan again then your API may be blocked");
                    ResetColor();
                    Exit(1);
                }
                var fileInfo = new FileInfo(file);
                if (fileInfo.Length < 1.28e+8)  // safeguard file size
                {
                    ForegroundColor = Yellow;
                    WriteLine($"[~] Scanning {fileInfo.FullName}");
                    ResetColor();
                    var report = Report(Globals.GetSHA256(fileInfo.FullName));
                    if (report.ResponseCode == FileReportResponseCode.Present)
                    {
                        // execute detection and format detection if file is present on server
                        int detected = 0;
                        foreach (var av in report.Scans.Keys)
                        {
                            if (report.Scans[av].Detected)
                            {
                                detected++;
                            }
                        }
                        FormatDetection(detected);
                    }
                    // otherwise misc file is not there or is being scanned
                    else if (report.ResponseCode == FileReportResponseCode.Queued)
                    {
                        // file is queued
                        ForegroundColor = Magenta;
                        WriteLine("[!] Not found - Misc File");
                        ResetColor();
                    }
                    else
                    {
                        ForegroundColor = Magenta;
                        WriteLine("[!] Not found - Misc File");
                        ResetColor();
                        var scan = SendScan(fileInfo);
                        misc.Add($"{scan.SHA256}|{fileInfo.FullName}");  // adding to misc file
                        isMisc = true;
                        //break;
                    }
                    WriteLine($"[#] Next Scan At {Now.AddSeconds(30):dd/MM/yyyy hh:mm:ss tt}");
                    Sleep(30000); // sleep to prevent spamming
                }
                else
                {
                    ForegroundColor = Yellow;
                    WriteLine($"[!] Skipping {fileInfo.FullName} - Beyond 128mB");
                    ResetColor();
                }
            }
            ForegroundColor = Blue;
            WriteLine($"[*] Scan Completed At {Globals.CurrentDateTime}");
            ResetColor();
            if (isMisc)
            {
                // writing misc files
                File.WriteAllLines(Globals.MiscFile, misc.ToArray());
                WriteLine();
                WriteLine("We found some miscellaneous files");
                WriteLine($"Try scaning misc file after {Now.AddHours(5):dd/MM/yyyy hh:mm:ss tt}");
            }
        }
        public void Initialize()
        {
            _testClock = new TestClock(Now);

            _resetTime = Now.AddHours(-1);
        }