public ProcessOutboxMessageCommandHandlerTestsFixture() { Now = DateTime.UtcNow; EndpointName = "SFA.DAS.NServiceBus"; Events = new List <Event> { new FooEvent { Created = Now.AddDays(-1) }, new BarEvent { Created = Now } }; OutboxMessage = new OutboxMessage(GuidComb.NewGuidComb(), EndpointName, Events); Context = new TestableMessageHandlerContext { MessageId = OutboxMessage.MessageId.ToString() }; Command = new ProcessOutboxMessageCommand(); Outbox = new Mock <IOutbox>(); Outbox.Setup(o => o.GetAsync(OutboxMessage.MessageId)).ReturnsAsync(OutboxMessage); Handler = new ProcessOutboxMessageCommandHandler(Outbox.Object); }
public async Task ItShouldUpdateTheTimestamps() { this.SetupAquireMocks(); await this.target.AcquireLeaseAsync(); await this.target.RenewLeaseAsync(); await this.target.KeepAliveAsync(); await this.target.RenewLeaseAsync(); var end = Now.AddDays(1); this.timestampCreator.Setup(v => v.Now()).Returns(end); this.blob.Setup(v => v.FetchAttributesAsync(this.cancellationToken)).Returns(Task.FromResult(0)).Verifiable(); var metadata = new Dictionary <string, string>(); this.blob.SetupGet(v => v.Metadata).Returns(metadata); this.blob.Setup(v => v.SetMetadataAsync(It.IsAny <AccessCondition>(), null, null, this.cancellationToken)).Returns(Task.FromResult(0)).Verifiable(); await this.target.UpdateTimestampsAsync(); this.blob.Verify(); Assert.AreEqual <DateTime>(Now, metadata[Azure.Constants.LeaseStartTimestampMetadataKey].FromIso8601String()); Assert.AreEqual <DateTime>(end, metadata[Azure.Constants.LeaseEndTimestampMetadataKey].FromIso8601String()); Assert.AreEqual(3, int.Parse(metadata[Azure.Constants.LeaseRenewCountMetadataKey])); }
public async void RetriesOnceOnDocumentConflictError(string uid, bool shouldPersist) { var duplicateToken1 = new RefreshToken { UID = uid, Token = "tokenthatsalreadyinuse", ExpiresAt = Now.AddDays(30), Persistent = shouldPersist }; var duplicateToken2 = new RefreshToken { UID = uid, Token = "anothertokenthatsalreadyinuse", ExpiresAt = Now.AddDays(30), Persistent = shouldPersist }; tokenService.SetupSequence(x => x.CreateRefreshToken()) .Returns(duplicateToken1.Token) .Returns(duplicateToken2.Token); refreshTokenRepo.SetupSequence(x => x.Create(duplicateToken1)) .ThrowsAsync(new DocumentConflictException()); refreshTokenRepo.SetupSequence(x => x.Create(duplicateToken2)) .ThrowsAsync(new DocumentConflictException()); await Assert.ThrowsAsync <DocumentConflictException>( () => userService.CreateAuthTokens(new User { Id = uid }, shouldPersist) ); refreshTokenRepo.Verify(x => x.Create(It.IsNotNull <RefreshToken>()), Times.Exactly(2)); }
public async void SavesRefreshTokenReturnsTokenPair(string uid, bool shouldPersist) { var user = new User { Id = uid, UserName = "******" }; var expected = new TokenPair { AccessToken = "axessToken" + uid, RefreshToken = "refreshToken" + uid, User = user, Persistent = shouldPersist }; var refreshToken = new RefreshToken { Token = expected.RefreshToken, UID = uid, ExpiresAt = Now.AddDays(30), Persistent = shouldPersist }; tokenService.Setup(x => x.CreateAccessToken(uid)).Returns(expected.AccessToken); tokenService.Setup(x => x.CreateRefreshToken()).Returns(expected.RefreshToken); refreshTokenRepo.Setup(x => x.Create(refreshToken)).ReturnsAsync(refreshToken); var actual = await userService.CreateAuthTokens(user, shouldPersist); Assert.Equal(expected, actual); refreshTokenRepo.Verify(x => x.Create(It.IsAny <RefreshToken>()), Times.Once); }
protected async Task <bool> HasSubscriptionDayBeenInitialized(DateTime?date = null) { var dateStr = !date.HasValue ? Now.AddDays(1).Date.ToString("yyyy-MM-dd") : date.Value.ToString("yyyy-MM-dd"); var item = await SubscriptionDayRepository.GetSingleAsync(x => x.Date == dateStr); return(item != null && item.Initialized); }
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 ProcessClientOutboxMessageCommandV2HandlerTestsFixture() { Now = DateTime.UtcNow; EndpointName = "SFA.DAS.NServiceBus"; Events = new List <object> { new FooEvent(Now.AddDays(-1)), new BarEvent(Now) }; TransportOperations = Events.Select(e => new TransportOperation(Guid.NewGuid(), e)).ToList(); ClientOutboxMessage = new ClientOutboxMessageV2(GuidComb.NewGuidComb(), EndpointName, TransportOperations); SynchronizedStorageSession = new Mock <SynchronizedStorageSession>(); Context = new TestableMessageHandlerContext { MessageId = ClientOutboxMessage.MessageId.ToString(), SynchronizedStorageSession = SynchronizedStorageSession.Object }; Command = new ProcessClientOutboxMessageCommandV2(); ClientOutboxStorage = new Mock <IClientOutboxStorageV2>(); ClientOutboxStorage.Setup(o => o.GetAsync(ClientOutboxMessage.MessageId, SynchronizedStorageSession.Object)).ReturnsAsync(ClientOutboxMessage); Handler = new ProcessClientOutboxMessageCommandV2Handler(ClientOutboxStorage.Object); }
public async void RetriesOnDocumentConflictError(string token, string uid, bool shouldPersist) { var user = new User { Id = uid, UserName = "******" }; userRepo.Setup(x => x.FindById(uid)).ReturnsAsync(user); var tokenDoc = new RefreshToken { Id = "someid" + token, Token = token, UID = uid, ExpiresAt = Now.AddDays(23), Persistent = shouldPersist }; refreshTokenRepo.Setup(x => x.Find(token)).ReturnsAsync(tokenDoc); var duplicateToken = new RefreshToken { Id = tokenDoc.Id, UID = uid, Token = "tokenthatsalreadyinuse", ExpiresAt = Now.AddDays(30), Persistent = shouldPersist }; var refreshToken = new RefreshToken { Id = tokenDoc.Id, UID = uid, Token = "newtoken" + token, ExpiresAt = Now.AddDays(30), Persistent = shouldPersist }; refreshTokenRepo.SetupSequence(x => x.Update(refreshToken)) .ReturnsAsync(refreshToken); refreshTokenRepo.SetupSequence(x => x.Update(duplicateToken)) .ThrowsAsync(new DocumentConflictException()); var accessToken = uid + "token"; tokenService.Setup(x => x.CreateAccessToken(uid)).Returns(accessToken); tokenService.SetupSequence(x => x.CreateRefreshToken()) .Returns(duplicateToken.Token) .Returns(refreshToken.Token); var result = await userService.CreateAuthTokens(token); refreshTokenRepo.Verify(x => x.Update(It.IsNotNull <RefreshToken>()), Times.Exactly(2)); Assert.Equal(new TokenPair { RefreshToken = refreshToken.Token, AccessToken = accessToken, User = user, Persistent = shouldPersist }, result); }
public void WhenPostingNewPostWithoutPublishDateSpecified_AndThereIsNoLastPost_ScheduleItForTomorrowAtNoot() { var rescheduler = new PostSchedulingStrategy(Session, Now); var result = rescheduler.Schedule(); Assert.Equal(Now.AddDays(1).SkipToNextWorkDay().AtNoon(), result); }
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Global protected void CheckOperationDate(DateTime operationDate) { if (operationDate > Now.AddDays(1) ) //TODO[UTC]: if everyone properly uses UTC, we don't have to do +1 { throw new CannotPerformOperationInFuture(); } }
// method to print information of order public override void Print() { Console.WriteLine("Order: Booking "); Console.WriteLine($"Room: {Type}"); Console.WriteLine($"Name {Name}, phone number {Phone} "); Console.WriteLine($"Order for {Persons} persons and for {Days} days"); Console.WriteLine($"Time the end of order is in {Now.AddDays(Days)}"); OnCost(new OrderEvents($"sum of order:{Persons * Days * Convert.ToDecimal(Type)}")); }
public ClientOutboxPersisterV2TestsFixture() { Now = DateTime.UtcNow; DateTimeService = new Mock <IDateTimeService>(); Settings = new Mock <ReadOnlySettings>(); Connection = new Mock <DbConnection>(); Transaction = new Mock <DbTransaction> { CallBase = true }; Command = new Mock <DbCommand>(); Parameters = new Mock <DbParameterCollection>(); ClientOutboxTransaction = new SqlClientOutboxTransaction(Connection.Object, Transaction.Object); EndpointName = "SFA.DAS.NServiceBus"; Events = new List <object> { new FooEvent(Now.AddDays(-1)), new BarEvent(Now) }; TransportOperations = Events.Select(e => new TransportOperation(Guid.NewGuid(), e)).ToList(); TransportOperationsData = JsonConvert.SerializeObject(TransportOperations, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); ClientOutboxMessage = new ClientOutboxMessageV2(GuidComb.NewGuidComb(), EndpointName, TransportOperations); SynchronizedStorageSession = new Mock <SynchronizedStorageSession>(); SqlSession = SynchronizedStorageSession.As <ISqlStorageSession>(); OutboxMessages = new List <IClientOutboxMessageAwaitingDispatch>(); CancellationTokenSource = new CancellationTokenSource(); CancellationToken = CancellationTokenSource.Token; DateTimeService.Setup(d => d.UtcNow).Returns(Now); Parameters.Setup(p => p.Add(It.IsAny <DbParameter>())); Command.SetupSet(c => c.CommandText = It.IsAny <string>()); Command.SetupSet(c => c.Transaction = It.IsAny <DbTransaction>()); Command.Protected().Setup <DbParameter>("CreateDbParameter").Returns(() => { var parameter = new Mock <DbParameter> { CallBase = true }; parameter.SetupProperty(p => p.ParameterName); parameter.SetupProperty(p => p.Value); return(parameter.Object); }); Command.Protected().Setup <DbParameterCollection>("DbParameterCollection").Returns(Parameters.Object); Connection.Protected().Setup <DbTransaction>("BeginDbTransaction", IsolationLevel.Unspecified).Returns(Transaction.Object); Connection.Protected().Setup <DbCommand>("CreateDbCommand").Returns(Command.Object); Settings.Setup(s => s.Get <Func <DbConnection> >("SqlPersistence.ConnectionBuilder")).Returns(() => Connection.Object); SqlSession.Setup(s => s.Connection).Returns(Connection.Object); SqlSession.Setup(s => s.Transaction).Returns(Transaction.Object); ClientOutboxStorage = new ClientOutboxPersisterV2(DateTimeService.Object, Settings.Object); }
public OutboxTestsFixture() { Now = DateTime.UtcNow; Connection = new Mock <DbConnection>(); UnitOfWorkContext = new Mock <IUnitOfWorkContext>(); Settings = new Mock <ReadOnlySettings>(); Transaction = new Mock <DbTransaction> { CallBase = true }; Command = new Mock <DbCommand>(); Parameters = new Mock <DbParameterCollection>(); OutboxTransaction = new OutboxTransaction(Transaction.Object); EndpointName = "SFA.DAS.NServiceBus"; Events = new List <Event> { new FooEvent { Created = Now.AddDays(-1) }, new BarEvent { Created = Now } }; EventsData = JsonConvert.SerializeObject(Events, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); OutboxMessage = new OutboxMessage(GuidComb.NewGuidComb(), EndpointName, Events); OutboxMessages = new List <IOutboxMessageAwaitingDispatch>(); Parameters.Setup(p => p.Add(It.IsAny <DbParameter>())); Command.SetupSet(c => c.CommandText = It.IsAny <string>()); Command.SetupSet(c => c.Transaction = It.IsAny <DbTransaction>()); Command.Protected().Setup <DbParameter>("CreateDbParameter").Returns(() => { var parameter = new Mock <DbParameter> { CallBase = true }; parameter.SetupProperty(p => p.ParameterName); parameter.SetupProperty(p => p.Value); return(parameter.Object); }); Command.Protected().Setup <DbParameterCollection>("DbParameterCollection").Returns(Parameters.Object); Connection.Protected().Setup <DbTransaction>("BeginDbTransaction", IsolationLevel.Unspecified).Returns(Transaction.Object); Connection.Protected().Setup <DbCommand>("CreateDbCommand").Returns(Command.Object); UnitOfWorkContext.Setup(c => c.Get <DbConnection>()).Returns(Connection.Object); UnitOfWorkContext.Setup(c => c.Get <DbTransaction>()).Returns(Transaction.Object); Settings.Setup(s => s.Get <string>("NServiceBus.Routing.EndpointName")).Returns(EndpointName); Outbox = new Outbox(Connection.Object, UnitOfWorkContext.Object); }
internal static void LearnMemory(dynamic metadata, dynamic content) { var groupKey = metadata.GroupKey.ToString(); var id = content.Id.ToString(); var memoryItem = Memories.SingleOrDefault(d => d.Id == id); if (memoryItem != null) { var nextdate = Now; var stage = memoryItem.Stage; switch (memoryItem.Stage) { case MemoryStage.Stage0: stage = MemoryStage.Stage1; break; case MemoryStage.Stage1: nextdate = Now.AddDays(1); stage = MemoryStage.Stage2; break; case MemoryStage.Stage2: nextdate = Now.AddDays(3); stage = MemoryStage.Stage3; break; case MemoryStage.Stage3: nextdate = Now.AddDays(7); stage = MemoryStage.Stage4; break; case MemoryStage.Stage4: nextdate = Now.AddDays(14); stage = MemoryStage.Stage5; break; case MemoryStage.Stage5: nextdate = Now.AddDays(30); stage = MemoryStage.Stage6; break; case MemoryStage.Stage6: nextdate = DateTimeOffset.MaxValue; break; default: break; } memoryItem.NextMemorizeDate = nextdate; memoryItem.Stage = stage; } }
public void WhenPostingNewPostWithoutPublishDateSpecified_AndTheLastPostPublishDateIsAFewDaysAgo_ScheduleItForTomorrowAtNoot() { Session.Store(new Post { PublishAt = Now.AddDays(-3) }); Session.SaveChanges(); var rescheduler = new PostSchedulingStrategy(Session, Now); var result = rescheduler.Schedule(); Assert.Equal(Now.AddDays(1).SkipToNextWorkDay().AtNoon(), result); }
/// <summary> /// Обработчик завершения одного игрового дня /// </summary> private void Tick() { Now = Now.AddDays(1); onDayLeft.Invoke(); if (IsWeekLeft()) { onWeekLeft.Invoke(); } if (IsMonthLeft()) { onMonthLeft.Invoke(); } }
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)); }
public async void ReturnsNullIfTokenExpired(string token, bool shouldPersist) { var tokenDoc = new RefreshToken { Id = "someid" + token, Token = token, UID = "uid", ExpiresAt = Now.AddDays(-2), Persistent = shouldPersist }; refreshTokenRepo.Setup(x => x.Find(token)).ReturnsAsync(tokenDoc); var result = await userService.CreateAuthTokens(token); Assert.Null(result); }
public TestHelper() { LoggerCoord = new NullLogger <CoordinatorAccountController>(); LoggerNoti = new NullLogger <NotificationController>(); LoggerProv = new NullLogger <ProviderAccountController>(); SetUpCoordinators(); SetUpStatuses(); SetUpProviderAccount(); SetUpUpdateActions(); SetUpNotifications(); SetUpMocks(); Now = DateTime.Now; NowPSev = Now.AddDays(7); NowPThirty = Now.AddDays(30); }
public TodayAndYesterdayModel Add(LoggedTimeEvent loggedTimeEvent) { var day = loggedTimeEvent.Day == Now.AddDays(-1).Date ? "yesterday" : "today"; if (!Children.ContainsKey(day)) { Children.Add(day, new List <Model>()); } var loggedTimeModel = new Model(); loggedTimeModel.Data["StartHour"] = loggedTimeEvent.StartHour; loggedTimeModel.Data["StartMinute"] = loggedTimeEvent.StartMinute; loggedTimeModel.Data["Project"] = loggedTimeEvent.Project; loggedTimeModel.Data["Hours"] = loggedTimeEvent.TotalHours; Children[day].Add(loggedTimeModel); return(this); }
public async void UpdatesRefreshTokenReturnsTokenPair(string token, string uid, bool shouldPersist) { var user = new User { Id = uid, UserName = "******" }; userRepo.Setup(x => x.FindById(uid)).ReturnsAsync(user); var tokenDoc = new RefreshToken { Id = "someid" + token, Token = token, UID = uid, ExpiresAt = Now.AddDays(23), Persistent = shouldPersist }; refreshTokenRepo.Setup(x => x.Find(token)).ReturnsAsync(tokenDoc); var newToken = new RefreshToken { Id = tokenDoc.Id, UID = uid, Token = "newtoken" + token, ExpiresAt = Now.AddDays(30), Persistent = shouldPersist }; refreshTokenRepo.SetupSequence(x => x.Update(newToken)).ReturnsAsync(newToken); var accessToken = uid + "token"; tokenService.Setup(x => x.CreateAccessToken(uid)).Returns(accessToken); tokenService.Setup(x => x.CreateRefreshToken()).Returns(newToken.Token); var result = await userService.CreateAuthTokens(token); refreshTokenRepo.Verify(x => x.Update(It.IsAny <RefreshToken>())); Assert.Equal(new TokenPair { RefreshToken = newToken.Token, AccessToken = accessToken, User = user, Persistent = shouldPersist }, result); }
/// <summary> /// 获取本周1的日期 时间为0点 /// </summary> /// <returns></returns> public static DateTime GetMonday() { int dayOfWeek = (int)Now.DayOfWeek; DateTime monday; if (dayOfWeek == 0) { monday = Now.AddDays(-6); } else { monday = Now.AddDays(1 - dayOfWeek); } monday = new DateTime(monday.Year, monday.Month, monday.Day); return(monday); }
public MainPage() { InitializeComponent(); Unloaded += MainPage_Unloaded; SetupLogging(); _lastExceptionReceived = Now.AddDays(-1); _uiCleanUp = ThreadPoolTimer.CreatePeriodicTimer(uiCleanUp_Tick, TimeSpan.FromSeconds(10)); _logger = new Logger(_logInfoAction, _logIErrorAction); _devices = new Dictionary <string, ICommonDevice>(); _sharpSensorConverter = new RawValueConverter(SharpConversionFactor, SharpExponent); StartDevices(); }
public async void RetriesOnDocumentConflictError(string uid, bool shouldPersist) { var user = new User { Id = uid, UserName = "******" }; var expected = new TokenPair { AccessToken = "axessToken" + uid, RefreshToken = "refreshToken" + uid, User = user, Persistent = shouldPersist }; var refreshToken = new RefreshToken { Token = expected.RefreshToken, UID = uid, ExpiresAt = Now.AddDays(30), Persistent = shouldPersist }; var duplicateToken = new RefreshToken { UID = uid, Token = "tokenthatsalreadyinuse", ExpiresAt = Now.AddDays(30), Persistent = shouldPersist }; tokenService.Setup(x => x.CreateAccessToken(uid)).Returns(expected.AccessToken); tokenService.SetupSequence(x => x.CreateRefreshToken()) .Returns(duplicateToken.Token) .Returns(expected.RefreshToken); refreshTokenRepo.SetupSequence(x => x.Create(duplicateToken)) .ThrowsAsync(new DocumentConflictException()); refreshTokenRepo.SetupSequence(x => x.Create(refreshToken)) .ReturnsAsync(refreshToken); var actual = await userService.CreateAuthTokens(user, shouldPersist); Assert.Equal(expected, actual); refreshTokenRepo.Verify(x => x.Create(It.IsNotNull <RefreshToken>()), Times.Exactly(2)); }
public void Run(DateTime date) { GlobalNow.Value = this.StartDate; while (Now <= date) { foreach (var job in this.People.SelectMany(x => x.Jobs)) { job.Disburse(); } ////foreach (var asset in this.Assets) { //// asset.Run(); ////} ////foreach (var liability in this.Liabilities) { //// liability.Run(); ////} Console.WriteLine(Now.ToString(DateTimePattern.ShortDate)); GlobalNow.Value = Now.AddDays(1); } }
public MaterialProvider(MaterialLogger logger) { All = logger.Read().ToArray(); AsDays = MakeDiff(EachDay(All)).Reverse().ToArray(); DateTime firsttime = Now; if (All.Count > 0) { firsttime = All[0].DateTime; } Durations = new[] { new { TitleKey = "ChartTimeRange_Days1", From = Now.AddDays(-1) }, new { TitleKey = "ChartTimeRange_Weeks1", From = Now.AddDays(-7) }, new { TitleKey = "ChartTimeRange_Weeks2", From = Now.AddDays(-14) }, new { TitleKey = "ChartTimeRange_Months1", From = Now.AddMonths(-1) }, new { TitleKey = "ChartTimeRange_Months2", From = Now.AddMonths(-2) }, new { TitleKey = "ChartTimeRange_Months3", From = Now.AddMonths(-3) }, new { TitleKey = "ChartTimeRange_Months6", From = Now.AddMonths(-6) }, new { TitleKey = "ChartTimeRange_Years1", From = Now.AddYears(-1) }, new { TitleKey = "ChartTimeRange_All", From = firsttime } }; From = Now.AddDays(-14); }
/// <summary> /// При при установке смещения или единицы изменяются значения Day, Month, Year. /// Смещение в неделях задает дату с точностью в день. /// </summary> private void SetDateByOffsetUnit() { Contract.Ensures(Contract.OldValue(_offset) == Contract.ValueAtReturn(out _offset)); Contract.Ensures(Contract.OldValue(_unit) == Contract.ValueAtReturn(out _unit)); if (Offset == null) { Year = null; Month = null; Day = null; return; } switch (Unit) { case DateUnit.Day: var date = Now.AddDays(-Offset.Value); Year = date.Year; Month = date.Month; Day = date.Day; break; case DateUnit.Week: date = Now.AddDays(-Offset.Value * 7); Year = date.Year; Month = date.Month; Day = date.Day; break; case DateUnit.Month: if (Offset < Now.Month) { Year = Now.Year; Month = Now.Month - Offset; } else { var a = Offset - Now.Month; Year = Now.Year - a / 12 - 1; Month = 12 - a % 12; } if (CutsDate) { Day = null; } break; case DateUnit.Year: Year = Now.Year - Offset; if (CutsDate) { Month = null; Day = null; } break; default: throw new ArgumentOutOfRangeException("Unit"); } ValidateDate(); }
protected async Task <FinanceOperationEmail> AcceptFeeImpl(string contents, DateTime operationDate, int feeChange, int money, PaymentType paymentType, Claim claim) { paymentType.EnsureActive(); if (operationDate > Now.AddDays(1) ) //TODO[UTC]: if everyone properly uses UTC, we don't have to do +1 { throw new CannotPerformOperationInFuture(); } if (feeChange != 0 || money < 0) { claim.RequestMasterAccess(CurrentUserId, acl => acl.CanManageMoney); } var state = FinanceOperationState.Approved; if (paymentType.UserId != CurrentUserId) { if (claim.PlayerUserId == CurrentUserId) { //Player mark that he pay fee. Put this to moderation state = FinanceOperationState.Proposed; } else { claim.RequestMasterAccess(CurrentUserId, acl => acl.CanManageMoney); } } var comment = AddCommentImpl(claim, null, contents, isVisibleToPlayer: true, extraAction: null); var financeOperation = new FinanceOperation() { Created = Now, FeeChange = feeChange, MoneyAmount = money, Changed = Now, Claim = claim, Comment = comment, PaymentType = paymentType, State = state, ProjectId = claim.ProjectId, OperationDate = operationDate }; comment.Finance = financeOperation; claim.FinanceOperations.Add(financeOperation); claim.UpdateClaimFeeIfRequired(operationDate); var email = EmailHelpers.CreateClaimEmail <FinanceOperationEmail>(claim, contents, s => s.MoneyOperation, commentExtraAction: null, initiator: await UserRepository.GetById(CurrentUserId), extraRecipients: new[] { paymentType.User }); email.FeeChange = feeChange; email.Money = money; return(email); }
public ActionResult UploadFile(string moduleName = null, Guid?uniqueKey = null) { var result = JsonAnswer <int>(); try { //if (!string.IsNullOrEmpty(uniqueKey) && uniqueKey.Length > 255) throw new ArgumentOutOfRangeException(nameof(uniqueKey), "Длина уникального ключа не может быть больше 255 символов."); if (string.IsNullOrEmpty(moduleName)) { throw new ArgumentNullException(nameof(moduleName), "Не указан модуль, для которого загружается файл."); } var module = AppCore.GetModulesManager().GetModule(moduleName) ?? (int.TryParse(moduleName, out int idModule) ? AppCore.GetModulesManager().GetModule(idModule) : null); if (module == null) { throw new Exception("Указанный модуль не найден."); } var hpf = HttpContext.Request.Files["file"] as HttpPostedFileBase; if (hpf == null) { throw new ArgumentNullException("Не найден загружаемый файл."); } var rootDirectory = System.Web.Hosting.HostingEnvironment.MapPath("/"); var filePathRelative = Path.Combine("data/filesClosed/", Guid.NewGuid().ToString() + Path.GetExtension(hpf.FileName)); var filePath = Path.Combine(rootDirectory, filePathRelative); Directory.CreateDirectory(Path.GetDirectoryName(filePath)); hpf.SaveAs(filePath); switch (Module.Register(out var file, hpf.FileName, filePathRelative, uniqueKey, DateTime.Now.AddDays(1))) { case RegisterResult.Error: case RegisterResult.NotFound: result.FromFail("Не удалось зарегистрировать переданный файл."); break;