// Post: Events/Details/5 public async Task <IActionResult> Detailsubmit(int?id, int?userId = 1) { if (id == null || userId == null) { return(NotFound()); } var @event = await _context.Events .Include(e => e.Category) .FirstOrDefaultAsync(m => m.Id == id); if (@event == null) { return(NotFound()); } var @userInEvent = new UserInEvent { EventId = Convert.ToInt32(id), UserId = Convert.ToInt32(userId), IsApproved = true, EventBarcode = Guid.NewGuid().ToString() }; _context.Add(@userInEvent); await _context.SaveChangesAsync(); int userEventid = @userInEvent.Id; return(RedirectToAction("ThankYou", new { id = userEventid })); }
public async Task <IActionResult> PutDepartment(int id, Department department) { if (id != department.Id) { return(BadRequest()); } _context.Entry(department).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DepartmentExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> Create([Bind("Id,Details")] Note note) { if (ModelState.IsValid) { _context.Add(note); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Thankyou))); } return(View(note)); }
public async Task <IActionResult> Create([Bind("Id,Title,Details,supportType")] request_support request_support) { if (ModelState.IsValid) { _context.Add(request_support); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Thankyou))); } return(View(request_support)); }
public async Task <Unit> Handle(AddTodoToGroupCommand request, CancellationToken cancellationToken) { var currentAccount = await accountProvider.GetCurrentAsync(cancellationToken); var todoId = new Identifier <Todo>(request.TodoId); var groupId = new Identifier <Group>(request.GroupId); var todo = await dbContext.Todos.FindAsync(new object[] { todoId }, cancellationToken); if (todo is null || todo.OwnerId != currentAccount.Id) { throw new Exception("Todo not found"); } var group = await dbContext.Groups.FindAsync(new object[] { groupId }, cancellationToken); if (group is null || group.OwnerId != currentAccount.Id) { throw new Exception("Group not found"); } todo.AddTo(group); await dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <Unit> Handle(AddViewPermissionsCommand request, CancellationToken cancellationToken) { var currentAccount = await accountProvider.GetCurrentAsync(cancellationToken); var todoId = new Identifier <Todo>(request.Id); var todo = await dbContext.Todos .Include(t => t.accountsThatCanEdit) // Meutar .Include(t => t.accountsThatCanView) .SingleOrDefaultAsync(t => t.Id == todoId, cancellationToken); if (todo is null || !todo.CanEdit(currentAccount)) { throw new Exception("Todo not found"); } try { var account = await accountProvider.GetAccountFromEmailAsync(request.Email, cancellationToken); if (account.Id == currentAccount.Id) { throw new Exception("You can't add your account"); } todo.accountsThatCanView.Add(account); await dbContext.SaveChangesAsync(cancellationToken); } catch (UserNotFoundException) { } return(Unit.Value); }
public async Task <Unit> Handle(ArchiveTodoCommand request, CancellationToken cancellationToken) { var account = await accountProvider.GetCurrentAsync(cancellationToken); var todoId = new Identifier <Todo>(request.TodoId); var todo = await dbContext.Todos .Include(t => t.accountsThatCanEdit) .Include(t => t.accountsThatCanView) .SingleOrDefaultAsync(t => t.Id == todoId, cancellationToken); if (todo is null) { throw new Exception("Todo not found"); } if (!todo.CanEdit(account)) { throw new Exception("Not authorized"); } todo.Archive(); await dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <Unit> Handle(ArchiveGroupCommand request, CancellationToken cancellationToken) { var account = await accountProvider.GetCurrentAsync(cancellationToken); var group = await dbContext.Groups.FindAsync(new object[] { request.groupId }, cancellationToken); if (group is null) { throw new Exception("Group not found"); } if (group.OwnerId != account.Id) { throw new Exception("Not authorized"); } var todosInGroup = await dbContext.Todos .Where(todo => todo.GroupId == group.Id) .Where(todo => !todo.Archived) .ToListAsync(cancellationToken); foreach (var todo in todosInGroup) { todo.Archive(); } group.Archive(); await dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <IActionResult> Create([Bind("Id,Title,Details,DepartmentId")] Complaint complaint) { if (ModelState.IsValid) { _context.Add(complaint); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Thankyou))); } //ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Id", complaint.DepartmentId); ViewData["DepartmentId"] = _context.Departments.Select(c => new SelectListItem { Text = c.NameEN, Value = Convert.ToString(c.Id) }); return(View(complaint)); }
public async Task CanCreateUserInt() { using (var db = new CustomDbContext <int>( new DbContextOptionsBuilder().UseSqlite($"DataSource=D{Guid.NewGuid()}.db").Options)) { db.Database.EnsureCreated(); var user = new User <int>(); db.Users.Add(user); await db.SaveChangesAsync(); user.UserName = "******"; await db.SaveChangesAsync(); var fetch = db.Users.First(u => u.UserName == "Boo"); Assert.Equal(user, fetch); db.Database.EnsureDeleted(); } }
public override async Task <IdentityResult> CreateAsync(ApplicationUser user) { var result = await base.CreateAsync(user); if (result.Succeeded) { var account = new Account(new Identifier <Account>(Guid.Parse(user.Id))); await customDbContext.Accounts.AddAsync(account); await customDbContext.SaveChangesAsync(); } return(result); }
public async Task <Unit> Handle(RenameTodoCommand request, CancellationToken cancellationToken) { var todo = await GetTodoAsync(request, cancellationToken); await CheckAuthorizationAsync(todo, cancellationToken); ValidateRequest(request); todo.Rename(request.Name); await dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task CanUpdateNameString() { using (var db = new CustomDbContext <string>( new DbContextOptionsBuilder().UseSqlite($"DataSource=D{Guid.NewGuid()}.db").Options)) { db.Database.EnsureCreated(); var oldName = Guid.NewGuid().ToString(); var user = new User <string> { UserName = oldName, Id = Guid.NewGuid().ToString() }; db.Users.Add(user); await db.SaveChangesAsync(); var newName = Guid.NewGuid().ToString(); user.UserName = newName; await db.SaveChangesAsync(); Assert.Null(db.Users.SingleOrDefault(u => u.UserName == oldName)); Assert.Equal(user, db.Users.Single(u => u.UserName == newName)); db.Database.EnsureDeleted(); } }
public async Task <Unit> Handle(EditTodoCommand request, CancellationToken cancellationToken) { var currentAccount = await accountProvider.GetCurrentAsync(cancellationToken); var todoId = new Identifier <Todo>(request.Id); if (string.IsNullOrWhiteSpace(request.Name)) { throw new InvalidOperationException("Todo name is required"); } if (request.Name.Length > 256) { throw new InvalidOperationException("Todo name is too long"); } var todo = await dbContext.Todos .Include(t => t.accountsThatCanEdit) .Include(t => t.accountsThatCanView) .SingleOrDefaultAsync(t => t.Id == todoId, cancellationToken); if (todo is null || !todo.CanEdit(currentAccount)) { throw new Exception("Todo not found"); //FIXME - change to custom exception asap } todo.Rename(request.Name); todo.ChangePriority(new Priority(request.Priority)); if (todo.GroupId is not null && request.GroupId is null) { todo.RemoveFromGroup(); } if (request.GroupId is not null) { var groupId = new Identifier <Group>(request.GroupId.Value); var group = await dbContext.Groups.FindAsync(new object[] { groupId }, cancellationToken); if (group is null || group.OwnerId != currentAccount.Id) { throw new Exception("Group not found"); //FIXME - change to custom exception asap } todo.AddTo(group); } await dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <Guid> Handle(CreateGroupCommand request, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(request.Name)) { throw new InvalidOperationException("Todo name is required"); } if (request.Name.Length > 256) { throw new InvalidOperationException("Todo name is too long"); } var account = await accountProvider.GetCurrentAsync(cancellationToken); var id = new Identifier <Group>(Guid.NewGuid()); var group = new Group(id, request.Name, account); dbContext.Groups.Add(group); await dbContext.SaveChangesAsync(cancellationToken); return(group.Id.ToGuid()); }
public async Task <Guid> Handle(CreateTodoCommand request, CancellationToken cancellationToken) { var currentAccount = await accountProvider.GetCurrentAsync(cancellationToken); var todoId = Identifier <Todo> .GenerateNew(); if (string.IsNullOrWhiteSpace(request.Name)) { throw new InvalidOperationException("Todo name is required"); } if (request.Name.Length > 256) { throw new InvalidOperationException("Todo name is too long"); } var groupId = request.groupId is not null ? new Identifier <Group>(request.groupId.Value) : null; var todo = new Todo(todoId, currentAccount, request.Name, new Priority(request.Priority), groupId); dbContext.Todos.Add(todo); await dbContext.SaveChangesAsync(cancellationToken); return(todo.Id.ToGuid()); }
public async Task <Unit> Handle(ArchiveTodoCommand request, CancellationToken cancellationToken) { var account = await accountProvider.GetCurrentAsync(cancellationToken); var todoId = new Identifier <Todo>(request.TodoId); var todo = await dbContext.Todos.FindAsync(new object[] { todoId }, cancellationToken); if (todo is null) { throw new Exception("Todo not found"); } if (todo.OwnerId != account.Id) { throw new Exception("Not authorized"); } todo.Archive(); await dbContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
/// <summary> /// Resends an activation link for a user; expects a user_created email template and a valid user identifier /// </summary> /// <param name="context"></param> /// <param name="userId"></param> /// <param name="ea"></param> /// <param name="emailTpl"></param> /// <returns></returns> public static async Task ResendActivationLink(DbContext context, Guid userId, IEmailAccount ea = null, IEmailTemplate emailTpl = null) { //Note: MBR seems to not like resending an activation link with a new password... It simply does not generate a new one but rather regenerates the verification key //because of that need to fake an account creation with some random email and then grab some auto generated data out of it // //basically a new account is created in order to get a new token and a new pass and verification key with its creation date //such user account is then destroyed but the necessary details are set on the account that we try to resend a link for. if (userId == default(Guid)) { throw new InvalidOperationException("You cannot resend an activation link - this user has not yet been created..."); } var mbrCtx = new CustomDbContext("MapHiveMbr"); //get the mbr user object var mbrUser = await mbrCtx.Users.FirstOrDefaultAsync(u => u.ID == userId); if (mbrUser == null) { throw new InvalidOperationException("User does not exist in MBR."); } //need user account service to properly create a MBR user var userAccountService = CustomUserAccountService.GetInstance("MapHiveMbr"); //wire up an evt listener - this is the way mbr talks AccountCreatedEvent <CustomUserAccount> e = null; userAccountService.Configuration.AddEventHandler( new MembershipRebootEventHandlers.AccountCreatedEventHandler <CustomUserAccount>(evt => e = evt)); //rrnd email - after all need to avoid scenarios when two folks try the same resend activation procedure at once var rndEmail = $"{DateTime.Now.Ticks}@somedomain.com"; //finally a new rnd user, so we can get a properly recreated verification key and a new pass... var newMbrAccount = userAccountService.CreateAccount(rndEmail, Cartomatic.Utils.Crypto.Generator.GenerateRandomString(10), rndEmail); //update the account in question with //mbrUser.VerificationKey = newMbrAccount.VerificationKey; //mbrUser.VerificationPurpose = newMbrAccount.VerificationPurpose; //mbrUser.HashedPassword = newMbrAccount.HashedPassword; //mbrUser.VerificationKeySent = newMbrAccount.VerificationKeySent //because the properties are read only, we need to do some crazy hocus-pocus again //note: looks like the type returned via mbrCtx.Users.FirstOrDefaultAsync is somewhat more dynamic and does not //map properly. therefore need to use a 'barebone' object instance var obj = new CustomUserAccount(); //Warning - this sql is postgresql specific! var updateSql = $@"UPDATE {mbrCtx.GetTableSchema(obj)}.""{mbrCtx.GetTableName(obj)}"" SET ""{mbrCtx.GetTableColumnName(obj, nameof(mbrUser.VerificationKey))}"" = '{newMbrAccount.VerificationKey}', ""{mbrCtx.GetTableColumnName(obj, nameof(mbrUser.VerificationPurpose))}"" = {(int)newMbrAccount.VerificationPurpose}, ""{mbrCtx.GetTableColumnName(obj, nameof(mbrUser.HashedPassword))}"" = '{newMbrAccount.HashedPassword}', ""{mbrCtx.GetTableColumnName(obj, nameof(mbrUser.VerificationKeySent))}"" = '{newMbrAccount.VerificationKeySent}' WHERE ""{mbrCtx.GetTableColumnName(obj, nameof(mbrUser.ID))}"" = '{mbrUser.ID}';"; //get rid of the new account mbrCtx.Users.Remove(await mbrCtx.Users.FirstAsync(u => u.ID == newMbrAccount.ID)); //and save da mess await mbrCtx.SaveChangesAsync(); await mbrCtx.Database.ExecuteSqlCommandAsync(updateSql); //send out the email if (emailTpl != null && ea != null) { MapHive.Server.Core.Email.EmailSender.Send( ea, emailTpl.Prepare(new Dictionary <string, object> { { nameof(e.VerificationKey), e.VerificationKey }, { nameof(e.InitialPassword), e.InitialPassword } }), mbrUser.Email ); } }
public async Task <ActionResult <NewRequestResponse> > Create([FromBody] NewRequestRequest request) { var email = this.GetUserEmail(); // Check mandatory parameters. if (AnyMissing(request?.SelectedProducts)) { return(this.Problem("Unable to create request", 400, ErrorCode.MissingMandatoryField)); } // Check for negative quantities. if (request.SelectedProducts.Any(p => p.Quantity < 0)) { return(this.Problem("Unable to create request", 400, ErrorCode.NegativeValue)); } // Create new request. using var transaction = await context.Database.BeginTransactionAsync(); Guid refNo; if (request.RefNo == null) { // Unknown refNo. Assign new one. refNo = Guid.NewGuid(); } else { // Known refNo. Set previous request with same refNo as not being current anymore. refNo = request.RefNo.Value; var existingRequest = await context .Request .Include(r => r.RequestStatus) .Include(r => r.User) .SingleOrDefaultAsync(r => r.RefNo.Equals(refNo) && r.IsCurrent == 1); if (existingRequest == null) { return(this.Problem("Unable to create request", 400, ErrorCode.InvalidRefNo)); } if (existingRequest.User.Email != email) { return(this.Problem("Unable to create request", 403, ErrorCode.UserNotAllowed)); } existingRequest.IsCurrent = 0; context.Request.Update(existingRequest); await context.SaveChangesAsync(); } var user = await context.User.SingleAsync(u => u.Email == email); var status = await context.RequestStatus.SingleAsync(s => s.Id == RequestStatusId.Pending); var newRequest = new Request() { Id = Guid.NewGuid(), RefNo = refNo, User = user, IsCurrent = 1, RequestStatus = status, }; var newRequestDetails = request.SelectedProducts.Select(sp => new RequestDetail() { Id = Guid.NewGuid(), Qty = sp.Quantity, Product = context.Product.SingleOrDefault(p => p.Id == sp.Id), Request = newRequest, }).ToList(); if (newRequestDetails.Any(rd => rd.Product == null)) { return(this.Problem("Unable to create request", 400, ErrorCode.InvalidProductId)); } await context.Request.AddAsync(newRequest); await context.SaveChangesAsync(); await context.RequestDetail.AddRangeAsync(newRequestDetails); await context.SaveChangesAsync(); transaction.Commit(); return(Ok(new NewRequestResponse() { RefNo = newRequest.RefNo })); }
public async Task <ActionResult <UserResponse> > Create([FromBody] NewUserRequest request) { var email = this.GetUserEmail(); var isAnonymous = email == null; email ??= request?.Email; // Anonymous // Check mandatory fields if (AnyMissing(email, request?.FirstName, request?.LastName) || (isAnonymous && AnyMissing(request?.RecaptchaPayload))) { return(this.Problem("Unable to create user", 400, ErrorCode.MissingMandatoryField)); } if (isAnonymous) { // Check ReCaptcha var isNotABot = await recaptchaService.ValidatePayload(request.RecaptchaPayload); if (!isNotABot.Success) { return(this.Problem("Unable to create user", 400, ErrorCode.BotValidationError, $"Validation error codes: {string.Join(", ", isNotABot.ErrorCodes)}")); } } // Check if the user already exists var existingUser = context.User.SingleOrDefault(u => u.Email == email); if (existingUser != null) { return(this.Problem("Unable to create user", 400, ErrorCode.UserAlreadyExists)); } // People will be User unless specified otherwise request.Role ??= RoleId.User; // Check requested user role var role = context.Role.SingleOrDefault(r => r.Id == request.Role); if (role == null) { return(this.Problem("Unable to create user", 400, ErrorCode.InvalidUserRoleId)); } var userStatus = context.UserStatus.Single(s => s.Id == UserStatusId.Pending); var user = new User() { Email = email, FirstName = request.FirstName, LastName = request.LastName, Role = role, UserStatus = userStatus, }; await context.User.AddAsync(user); await context.SaveChangesAsync(); return(Ok(new UserResponse() { Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, Role = user.Role.Id, Status = user.UserStatus.Id, })); }
public async Task<ActionResult> UserProperties(UserPropertiesViewModel model) { if (ModelState.IsValid) { try { using (CustomDbContext db = new CustomDbContext()) { UserStore<CustomUser> userstore = new UserStore<CustomUser>(db); var user = await userstore.FindByIdAsync(User.Identity.GetUserId()); user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; user.Phone = model.Phone; await userstore.UpdateAsync(user); await db.SaveChangesAsync(); return RedirectToAction("Manage", new { Message = "Your properties have been updated." }); } } catch (Exception ex) { Trace.TraceError("Error occurred while updating user properties : {0}", ex.ToString()); } } return View(model); }
public async Task CommitAsync() { await _db.SaveChangesAsync(); }
public async Task <ActionResult> PayeezyResponse(FormCollection formFields) { ActionResult actionResult; int? impersonatorTenantId; long? impersonatorUserId; int value; long num; bool item = formFields["isRecordPayment"] != null; int num1 = 0; int num2 = 0; int num3 = 0; long num4 = (long)0; if (!item) { string str = formFields["x_cust_id"].ToString(); string[] strArrays = str.Split(new char[] { '|' }); num1 = int.Parse(strArrays[0].ToString()); num2 = int.Parse(strArrays[1].ToString()); num3 = int.Parse(strArrays[2].ToString()); num4 = long.Parse(strArrays[3].ToString()); } else { num1 = int.Parse(formFields["invoiceId"].ToString()); num2 = int.Parse(formFields["x_cust_id"].ToString()); if (this.AbpSession.ImpersonatorTenantId.HasValue) { impersonatorTenantId = this.AbpSession.ImpersonatorTenantId; value = impersonatorTenantId.Value; } else { impersonatorTenantId = this.AbpSession.TenantId; value = impersonatorTenantId.Value; } num3 = value; if (this.AbpSession.ImpersonatorUserId.HasValue) { impersonatorUserId = this.AbpSession.ImpersonatorUserId; num = impersonatorUserId.Value; } else { impersonatorUserId = this.AbpSession.UserId; num = impersonatorUserId.Value; } num4 = num; } Dictionary <string, string> strs = new Dictionary <string, string>(); foreach (object key in formFields.Keys) { strs.Add(key.ToString(), formFields[key.ToString()]); } InvoicePayment invoicePayment = new InvoicePayment() { Id = (long)0, TenantId = num3, InvoiceId = (long)num1, CustomerId = (long)num2, X_Response_Code = strs["x_response_code"].ToString(), X_Response_Reason_Code = strs["x_response_reason_code"].ToString(), X_Response_Reason_Text = strs["x_response_reason_text"].ToString(), X_Auth_Code = strs["x_auth_code"].ToString(), X_Trans_Id = strs["x_trans_id"].ToString(), X_Description = strs["x_description"].ToString(), DollarAmount = decimal.Parse(strs["x_amount"].ToString()), TransactionDateTime = DateTime.Now, P_Authorization_Num = strs["Authorization_Num"].ToString(), P_Bank_Resp_Code = strs["Bank_Resp_Code"].ToString(), P_Bank_Message = strs["Bank_Message"].ToString(), P_Customer_Ref = strs["Customer_Ref"].ToString(), P_Exact_Ctr = strs["exact_ctr"].ToString(), P_EXact_Message = strs["EXact_Message"].ToString(), P_ResponseObject = JsonConvert.SerializeObject(strs, Formatting.Indented) }; InvoicePayment invoicePayment1 = invoicePayment; ((dynamic)this.ViewBag).NewId = 0; decimal num5 = new decimal(0); using (CustomDbContext customDbContext = new CustomDbContext()) { try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("INSERT INTO [dbo].[FuelWerxInvoicePayments]"); stringBuilder.AppendLine(" ([TenantId]"); stringBuilder.AppendLine(" ,[InvoiceId]"); stringBuilder.AppendLine(" ,[CustomerId]"); stringBuilder.AppendLine(" ,[X_Response_Code]"); stringBuilder.AppendLine(" ,[X_Response_Reason_Code]"); stringBuilder.AppendLine(" ,[X_Response_Reason_Text]"); stringBuilder.AppendLine(" ,[X_Auth_Code]"); stringBuilder.AppendLine(" ,[X_Trans_Id]"); stringBuilder.AppendLine(" ,[X_Description]"); stringBuilder.AppendLine(" ,[P_Exact_Ctr]"); stringBuilder.AppendLine(" ,[P_Authorization_Num]"); stringBuilder.AppendLine(" ,[P_Customer_Ref]"); stringBuilder.AppendLine(" ,[P_Bank_Resp_Code]"); stringBuilder.AppendLine(" ,[P_Bank_Message]"); stringBuilder.AppendLine(" ,[P_EXact_Message]"); stringBuilder.AppendLine(" ,[P_ResponseObject]"); stringBuilder.AppendLine(" ,[TransactionDateTime]"); stringBuilder.AppendLine(" ,[DollarAmount]"); stringBuilder.AppendLine(" ,[ExportedToReporting]"); stringBuilder.AppendLine(" ,[IsDeleted]"); stringBuilder.AppendLine(" ,[DeleterUserId]"); stringBuilder.AppendLine(" ,[DeletionTime]"); stringBuilder.AppendLine(" ,[LastModificationTime]"); stringBuilder.AppendLine(" ,[LastModifierUserId]"); stringBuilder.AppendLine(" ,[CreationTime]"); stringBuilder.AppendLine(" ,[CreatorUserId])"); stringBuilder.AppendLine(" VALUES"); stringBuilder.AppendLine(" (@p0"); stringBuilder.AppendLine(" ,@p1"); stringBuilder.AppendLine(" ,@p2"); stringBuilder.AppendLine(" ,@p3"); stringBuilder.AppendLine(" ,@p4"); stringBuilder.AppendLine(" ,@p5"); stringBuilder.AppendLine(" ,@p6"); stringBuilder.AppendLine(" ,@p7"); stringBuilder.AppendLine(" ,@p8"); stringBuilder.AppendLine(" ,@p9"); stringBuilder.AppendLine(" ,@p10"); stringBuilder.AppendLine(" ,@p11"); stringBuilder.AppendLine(" ,@p12"); stringBuilder.AppendLine(" ,@p13"); stringBuilder.AppendLine(" ,@p14"); stringBuilder.AppendLine(" ,@p15"); stringBuilder.AppendLine(" ,@p16"); stringBuilder.AppendLine(" ,@p17"); stringBuilder.AppendLine(" ,0"); stringBuilder.AppendLine(" ,0"); stringBuilder.AppendLine(" ,null"); stringBuilder.AppendLine(" ,null"); stringBuilder.AppendLine(" ,null"); stringBuilder.AppendLine(" ,null"); stringBuilder.AppendLine(" ,GETDATE()"); stringBuilder.AppendLine(" ,@p18);"); stringBuilder.AppendLine("SELECT CAST(SCOPE_IDENTITY() AS BIGINT)[NewId];"); Database database = customDbContext.Database; string str1 = stringBuilder.ToString(); object[] tenantId = new object[] { invoicePayment1.TenantId, invoicePayment1.InvoiceId, invoicePayment1.CustomerId, invoicePayment1.X_Response_Code, invoicePayment1.X_Response_Reason_Code, invoicePayment1.X_Response_Reason_Text, invoicePayment1.X_Auth_Code, invoicePayment1.X_Trans_Id, invoicePayment1.X_Description, invoicePayment1.P_Exact_Ctr, invoicePayment1.P_Authorization_Num, invoicePayment1.P_Customer_Ref, invoicePayment1.P_Bank_Resp_Code, invoicePayment1.P_Bank_Message, invoicePayment1.P_EXact_Message, invoicePayment1.P_ResponseObject, invoicePayment1.TransactionDateTime, null, null }; decimal dollarAmount = invoicePayment1.DollarAmount; tenantId[17] = decimal.Parse(dollarAmount.ToString()); tenantId[18] = num4; long num6 = await database.SqlQuery <long>(str1, tenantId).SingleAsync(); long num7 = num6; await customDbContext.SaveChangesAsync(); ((dynamic)this.ViewBag).NewId = num7; string str2 = "SELECT LineTotal FROM FuelWerxInvoices WHERE Id = @p0"; Database database1 = customDbContext.Database; string str3 = str2.ToString(); object[] invoiceId = new object[] { invoicePayment1.InvoiceId }; dollarAmount = await database1.SqlQuery <decimal>(str3, invoiceId).SingleAsync(); decimal num8 = dollarAmount; string str4 = "UPDATE FuelWerxInvoices SET PaidTotal = (SELECT SUM(DollarAmount) FROM FuelWerxInvoicePayments WHERE InvoiceId = @p0) WHERE Id = @p0; SELECT PaidTotal FROM FuelWerxInvoices WHERE Id = @p0;"; Database database2 = customDbContext.Database; string str5 = str4.ToString(); object[] objArray = new object[] { invoicePayment1.InvoiceId }; dollarAmount = await database2.SqlQuery <decimal>(str5, objArray).SingleAsync(); decimal num9 = dollarAmount; if (num8 < num9) { num5 = num9 - num8; this.Logger.Debug(string.Concat("CreateInvoiceForOverageAmount[] invoiceId:overage = ", num1.ToString(), ":", num5.ToString())); StringBuilder stringBuilder1 = new StringBuilder(); stringBuilder1.AppendLine("DECLARE @newId As BIGINT = 0;"); stringBuilder1.AppendLine("INSERT INTO [dbo].[FuelWerxInvoices]"); stringBuilder1.AppendLine(" ([TenantId]"); stringBuilder1.AppendLine(" ,[CustomerId]"); stringBuilder1.AppendLine(" ,[Number]"); stringBuilder1.AppendLine(" ,[Date]"); stringBuilder1.AppendLine(" ,[PONumber]"); stringBuilder1.AppendLine(" ,[Discount]"); stringBuilder1.AppendLine(" ,[Rate]"); stringBuilder1.AppendLine(" ,[Hours]"); stringBuilder1.AppendLine(" ,[Tax]"); stringBuilder1.AppendLine(" ,[LineTotal]"); stringBuilder1.AppendLine(" ,[Terms]"); stringBuilder1.AppendLine(" ,[CurrentStatus]"); stringBuilder1.AppendLine(" ,[TimeEntryLog]"); stringBuilder1.AppendLine(" ,[Description]"); stringBuilder1.AppendLine(" ,[IsActive]"); stringBuilder1.AppendLine(" ,[ProjectId]"); stringBuilder1.AppendLine(" ,[CreationTime]"); stringBuilder1.AppendLine(" ,[CreatorUserId]"); stringBuilder1.AppendLine(" ,[CustomerAddressId]"); stringBuilder1.AppendLine(" ,[Label]"); stringBuilder1.AppendLine(" ,[BillingType]"); stringBuilder1.AppendLine(" ,[DueDateDiscountExpirationDate]"); stringBuilder1.AppendLine(" ,[DueDateDiscountTotal]"); stringBuilder1.AppendLine(" ,[DueDate]"); stringBuilder1.AppendLine(" ,[Upcharge]"); stringBuilder1.AppendLine(" ,[GroupDiscount]"); stringBuilder1.AppendLine(" ,[HoursActual]"); stringBuilder1.AppendLine(" ,[TermType]"); stringBuilder1.AppendLine(" ,[LogDataAndTasksVisibleToCustomer]"); stringBuilder1.AppendLine(" ,[EmergencyDeliveryFee]"); stringBuilder1.AppendLine(" ,[IsDeleted]"); stringBuilder1.AppendLine(" ,[IncludeEmergencyDeliveryFee])"); stringBuilder1.AppendLine(" SELECT [TenantId]"); stringBuilder1.AppendLine(" ,[CustomerId]"); stringBuilder1.AppendLine(" ,[Number]"); stringBuilder1.AppendLine(" ,CONVERT(date, GETDATE())"); stringBuilder1.AppendLine(" ,[PONumber]"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,[Rate]"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(string.Concat(" ,-", num5.ToString())); stringBuilder1.AppendLine(" ,[Terms]"); stringBuilder1.AppendLine(string.Concat(" ,'", this.L("InvoiceOverageNewInvoiceDefaultStatus").Replace("'", "''"), "'")); stringBuilder1.AppendLine(" ,''"); stringBuilder1.AppendLine(" ,[Description]"); stringBuilder1.AppendLine(" ,1"); stringBuilder1.AppendLine(" ,null"); stringBuilder1.AppendLine(" ,GETDATE()"); stringBuilder1.AppendLine(" ,[CreatorUserId]"); stringBuilder1.AppendLine(" ,[CustomerAddressId]"); stringBuilder1.AppendLine(" ,[Label]"); stringBuilder1.AppendLine(" ,[BillingType]"); stringBuilder1.AppendLine(" ,null"); stringBuilder1.AppendLine(" ,null"); stringBuilder1.AppendLine(" ,CONVERT(date, DATEADD(m, 1, GETDATE()))"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,[TermType]"); stringBuilder1.AppendLine(" ,[LogDataAndTasksVisibleToCustomer]"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" ,[IncludeEmergencyDeliveryFee]"); stringBuilder1.AppendLine(" FROM [dbo].[FuelWerxInvoices]"); stringBuilder1.AppendLine(" WHERE ([Id] = @p0);"); stringBuilder1.AppendLine("SET @newId = (SELECT CAST(SCOPE_IDENTITY() AS BIGINT)[NewId]);"); stringBuilder1.AppendLine("IF @newId > 0"); stringBuilder1.AppendLine("BEGIN"); stringBuilder1.AppendLine(" INSERT INTO [dbo].[FuelWerxInvoiceAdjustments]"); stringBuilder1.AppendLine(" ("); stringBuilder1.AppendLine(" [InvoiceId]"); stringBuilder1.AppendLine(" ,[Name]"); stringBuilder1.AppendLine(" ,[Cost]"); stringBuilder1.AppendLine(" ,[RetailCost]"); stringBuilder1.AppendLine(" ,[Description]"); stringBuilder1.AppendLine(" ,[IsTaxable]"); stringBuilder1.AppendLine(" ,[IsActive]"); stringBuilder1.AppendLine(" ,[CreationTime]"); stringBuilder1.AppendLine(" ,[CreatorUserId]"); stringBuilder1.AppendLine(" ,[IsDeleted]"); stringBuilder1.AppendLine(" )"); stringBuilder1.AppendLine(" VALUES"); stringBuilder1.AppendLine(" ("); stringBuilder1.AppendLine(" @newId"); stringBuilder1.AppendLine(string.Concat(" ,'", this.L("InvoiceOverageNewInvoiceDefaultAdjustmentName").Replace("'", "''"), "'")); stringBuilder1.AppendLine(string.Concat(" ,-", num5.ToString())); stringBuilder1.AppendLine(string.Concat(" ,-", num5.ToString())); stringBuilder1.AppendLine(string.Concat(" ,'", this.L("InvoiceOverageNewInvoiceDefaultAdjustmentDescription").Replace("'", "''"), "'")); stringBuilder1.AppendLine(" ,1"); stringBuilder1.AppendLine(" ,1"); stringBuilder1.AppendLine(" ,GETDATE()"); stringBuilder1.AppendLine(" ,(SELECT TOP 1 [CreatorUserId] FROM [dbo].[FuelWerxInvoices] WHERE [Id] = @newId)"); stringBuilder1.AppendLine(" ,0"); stringBuilder1.AppendLine(" );"); stringBuilder1.AppendLine("END"); stringBuilder1.AppendLine("SELECT @newId;"); Database database3 = customDbContext.Database; string str6 = stringBuilder1.ToString(); object[] invoiceId1 = new object[] { invoicePayment1.InvoiceId }; num6 = await database3.SqlQuery <long>(str6, invoiceId1).SingleAsync(); long num10 = num6; this.Logger.Debug(string.Concat("CreateInvoiceForOverageAmount[] newInvoiceId = ", num10.ToString())); } } catch (Exception exception1) { Exception exception = exception1; ((dynamic)this.ViewBag).NewId = 0; throw new UserFriendlyException(string.Concat(this.L("ManualPaymentCreationFailed"), exception.Message.ToString())); } } if (!item) { actionResult = this.View(); } else { actionResult = this.Json(new MvcAjaxResponse()); } return(actionResult); }
public async Task CommitAsync() { await context.SaveChangesAsync(); }