static async Task MainAsync(IRepository<SampleEntity> repo) { foreach (var s in await repo.GetAllAsync()) { Console.WriteLine("{0} | {1}", s.ID, s.Name); } // Paged Set // Console.WriteLine("\nPage = 2 - Page Size = 2 :"); var some = await repo.GetAsync(2, 2, s => s.ID); foreach (var s in some) { Console.WriteLine("{0} | {1}", s.ID, s.Name); } // Updating // var fox = await repo.FindAsync(e => e.Name == "Fox"); fox.Name = "Dog"; repo.Update(fox, fox.ID); // Deleting // Console.WriteLine("\n " + await repo.DeleteAsync(repo.Get(5)) + "\n"); foreach (var e in repo.GetAll()) Console.WriteLine(e.ID + " | " + e.Name); }
public void Update_Should_Save_Modified_Business_Name(IRepository<Contact, string> repository) { var contact = new Contact { Name = "Test User" }; repository.Add(contact); var contact2 = new Contact { Name = "Test User 2" }; repository.Add(contact2); contact.Name = "Test User - Updated"; repository.Update(contact); var updated = repository.Get(contact.ContactId); var notUpdated = repository.Get(contact2.ContactId); updated.Name.ShouldEqual("Test User - Updated"); notUpdated.Name.ShouldEqual("Test User 2"); }
public void Update_Should_Update_Multiple_Items(IRepository<Contact, string> repository) { IList<Contact> contacts = new List<Contact> { new Contact {Name = "Contact 1"}, new Contact {Name = "Contact 2"}, new Contact {Name = "Contact 3"}, }; repository.Add(contacts); var items = repository.GetAll().ToList(); items.Count().ShouldEqual(3); foreach (var contact in contacts.Take(2)) { contact.Name += "UPDATED"; } repository.Update(contacts); items = repository.GetAll().ToList(); items.Count(x => x.Name.EndsWith("UPDATED")).ShouldEqual(2); }
public void UpdatClient(Client cl) { _clientRepository.Update(cl); _clientRepository.Save(); }
public void Update(BllBlog entity) { repository.Update(entity.ToDal()); unitOfWork.Commit(); }
/// <summary> /// 修改权限 /// </summary> /// <param name="permission">实体</param> /// <returns></returns> public void UpdatePermission(Permission permission) { _permissionRepository.Update(permission); }
public int UpdateEmployee(Employee item) { return(empRepository.Update(item)); }
public async Task <IActionResult> Enter(EnterGiveawayViewModel viewModel) { if (ModelState.IsValid) { List <GiveawayDrop> myPossibleDrops = _giveawayDropRepository.AllQueryable() .Where(o => o.Type == viewModel.Type).OrderBy(o => o.Name).ToList(); Random random = new Random(); int randomDropNumber = random.Next(0, myPossibleDrops.Count); int randomBoundNumber = random.Next(myPossibleDrops[randomDropNumber].LowerBound, myPossibleDrops[randomDropNumber].HigherBound + 1); string quality = ""; switch (viewModel.Type) { case GiveawayDrop.DropType.Armor: case GiveawayDrop.DropType.Weapon: case GiveawayDrop.DropType.Blueprint: if (randomBoundNumber > 70) { quality = "Ascendant"; //30% } else if (randomBoundNumber > 40) { quality = "Mastercraft"; //30% } else if (randomBoundNumber > 20) { quality = "Journeyman"; //20% } else { quality = "Apprentice"; //20% } break; case GiveawayDrop.DropType.Creature: quality = "Lv" + randomBoundNumber; break; case GiveawayDrop.DropType.Resource: case GiveawayDrop.DropType.Structure: quality = "x" + randomBoundNumber; break; } //Build Prize Receipt GiveawayReceipt prize = new GiveawayReceipt(); prize.Description = quality + " " + myPossibleDrops[randomDropNumber].Name; prize.EntryDate = DateTime.Now; prize.IsInMailbox = false; prize.IsPickedUp = false; prize.ReadyForPickUpDate = prize.EntryDate.AddDays(4); //Set User & Mailbox User TargetUser = _userService.GetOrCreateUser(User.Identity.Name); Mailbox availbleBox = _mailboxRepository.AllQueryable().FirstOrDefault(o => !o.IsActive || DateTime.Now.Subtract(o.ArrivalDate).TotalDays >= 7); if (availbleBox == null) { availbleBox = new Mailbox(); Mailbox highestBox = _mailboxRepository.AllQueryable().OrderByDescending(o => o.VaultNumber).FirstOrDefault(); if (highestBox == null) { availbleBox.VaultNumber = 1; } else { availbleBox.VaultNumber = highestBox.VaultNumber + 1; } _mailboxRepository.Add(availbleBox); } availbleBox.IsActive = true; availbleBox.ArrivalDate = prize.ReadyForPickUpDate; availbleBox.Mail_Description = prize.Description; availbleBox.UserID = TargetUser.ID; _mailboxRepository.Update(availbleBox); //Set Last Part of Prize prize.MailboxID = availbleBox.ID; prize.UserID = TargetUser.ID; //Add Prize _giveawayReceiptRepository.Add(prize); //Send Email string body = "<!DOCTYPE html> <html> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://www.w3schools.com/w3css/4/w3.css\"> <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Oswald\"> <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Open Sans\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <link rel=\"stylesheet\" href=\"~/lib/bootstrap/dist/css/bootstrap.min.css\" /> <link rel=\"icon\" href=\"~/images/ark_icon.jpg\"> </head> <body> <div class=\"w3-margin-left\"> <style> h1, h2, h3, h4, h5, h6 { font-family: \"Oswald\" } body { font-family: \"Open Sans\" } </style> <h1 style=\"color: black; \">Hello " + TargetUser.PSN + ",</h1> <h3 style=\"color: black; \">Thanks for playing on the ColoArk Server.</h3> <h3 style=\"color: black; \">Your gift has been added to our delivery list.</h3> <ul class=\"w3-ul w3-hoverable w3-white\" style=\"list-style-type: none;\"> <li class=\"w3-padding-16\"> <table class=\"\"> <tr> <th> Prize </th> <td> " + prize.Description + " </td> </tr><tr> <th> Status </th> <td> <label class=\"label label-warning\">On Its Way</label> </td> </tr> <tr> <th> Mailbox </th> <td> " + prize.Mailbox.VaultNumber + " </td> </tr> <tr> <th> Expected By </th> <td>" + prize.ReadyForPickUpDate.ToString("MMM dd, yyyy") + "</td> </tr> </table> </li> </ul> <p style=\"color: black; \">Have a great day, see you in game.</p> <p style=\"color: black; \">-CWSharkbones</p> </div> </body> </html>[" + DateTime.Now.ToString("H:mm:ss mm/dd/yyyy") + "] End of message."; await _emailSender.SendEmailAsync(TargetUser.Email, "ColoArk Prize - Confirmation", body); return(RedirectToAction("Index", "Giveaway", new { changeAction = "entered" })); } return(View()); }
public void Deploy(IRepository repository, ChangeSet changeSet, string deployer, bool clean) { ITracer tracer = _traceFactory.GetTracer(); IDisposable deployStep = null; ILogger innerLogger = null; string targetBranch = null; // If we don't get a changeset, find out what branch we should be deploying and get the commit ID from it if (changeSet == null) { targetBranch = _settings.GetBranch(); changeSet = repository.GetChangeSet(targetBranch); } string id = changeSet.Id; IDeploymentStatusFile statusFile = null; try { deployStep = tracer.Step("DeploymentManager.Deploy(id)"); // Remove the old log file for this deployment id string logPath = GetLogPath(id); FileSystemHelpers.DeleteFileSafe(logPath); statusFile = GetOrCreateStatusFile(changeSet, tracer, deployer); statusFile.MarkPending(); ILogger logger = GetLogger(changeSet.Id); using (tracer.Step("Updating to specific changeset")) { innerLogger = logger.Log(Resources.Log_UpdatingBranch, targetBranch ?? id); using (var writer = new ProgressWriter()) { // Update to the the specific changeset repository.ClearLock(); repository.Update(id); } } using (tracer.Step("Updating submodules")) { innerLogger = logger.Log(Resources.Log_UpdatingSubmodules); repository.UpdateSubmodules(); } if (clean) { tracer.Trace("Cleaning {0} repository", repository.RepositoryType); innerLogger = logger.Log(Resources.Log_CleaningRepository, repository.RepositoryType); repository.Clean(); } // set to null as Build() below takes over logging innerLogger = null; // Perform the build deployment of this changeset Build(id, tracer, deployStep); } catch (Exception ex) { if (innerLogger != null) { innerLogger.Log(ex); } if (statusFile != null) { statusFile.MarkFailed(); } tracer.TraceError(ex); if (deployStep != null) { deployStep.Dispose(); } throw; } }
/// <summary> /// Updates the ACL record /// </summary> /// <param name="aclRecord">ACL record</param> public virtual void UpdateAclRecord(AclRecord aclRecord) { _aclRecordRepository.Update(aclRecord); }
public virtual void Update(TDto item) { _repository.Update(_mapper.Map <T>(item)); }
public void Update(T entity) { repository.Update(entity); repository.SaveChanges(); }
public void Update(File file) { _fileRepository.Update(file); }
/// <summary> /// Method updates product status for "saled", because the Deal is done /// </summary> /// <param name="product"></param> /// <param name="id"></param> public static void Deal(IRepository<Product> product, int id) { Console.WriteLine("Consratulations! You have bought the product {0} on address {1}", product.GetItem(id).name, product.GetItem(id).address); Product saledProduct = new Product(id, product.GetItem(id).name, product.GetItem(id).address, "saled"); product.Update(saledProduct); }
public void UpdateOrder(Order updatedOrder) { orderContext.Update(updatedOrder); orderContext.Commit(); }
public void UpdateAddressBook(AddressBook item) { addressBookRepository.Update(item); }
/// <summary> /// Updates the country /// </summary> /// <param name="country">Country</param> public virtual void UpdateCountry(Country country) { _countryRepository.Update(country); }
internal async Task<ChangeSet> Sync(DropboxInfo dropboxInfo, string branch, IRepository repository) { DropboxDeployInfo deployInfo = dropboxInfo.DeployInfo; ResetStats(); if (_settings.GetValue(CursorKey) != deployInfo.OldCursor) { throw new InvalidOperationException(Resources.Error_MismatchDropboxCursor); } // initial sync, remove default content // for simplicity, we do it blindly whether or not in-place // given the end result is the same if (String.IsNullOrEmpty(deployInfo.OldCursor) && DeploymentHelper.IsDefaultWebRootContent(_environment.WebRootPath)) { string hoststarthtml = Path.Combine(_environment.WebRootPath, Constants.HostingStartHtml); FileSystemHelpers.DeleteFileSafe(hoststarthtml); } if (!repository.IsEmpty()) { // git checkout --force <branch> repository.Update(branch); } ChangeSet changeSet = null; string message = null; try { using (_tracer.Step("Sync with Dropbox")) { if (dropboxInfo.OAuthVersion == 2) { // Fetch the deltas await UpdateDropboxDeployInfo(deployInfo); } // Sync dropbox => repository directory await ApplyChanges(dropboxInfo, useOAuth20: dropboxInfo.OAuthVersion == 2); } message = String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_Synchronized, deployInfo.Deltas.Count); } catch (Exception) { message = String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_SynchronizedWithFailure, _successCount, deployInfo.Deltas.Count, _failedCount); throw; } finally { Logger.Log(message); Logger.Log(String.Format("{0} downloaded files, {1} successful retries.", _fileCount, _retriedCount)); IDeploymentStatusFile statusFile = _status.Open(dropboxInfo.TargetChangeset.Id); statusFile.UpdateMessage(message); statusFile.UpdateProgress(String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_Committing, _successCount)); // Commit anyway even partial change if (repository.Commit(message, String.Format("{0} <{1}>", deployInfo.UserName, deployInfo.Email ?? deployInfo.UserName))) { changeSet = repository.GetChangeSet("HEAD"); } } // Save new dropboc cursor LogInfo("Update dropbox cursor"); _settings.SetValue(CursorKey, deployInfo.NewCursor); return changeSet; }
public void Upd(EbomHeader entity) { _app.Update(entity); }
private void Changed(IRepository rep, FileSystemEventArgs e) { try { IList<AttachmentInfo> list = (rep as Feng.NH.INHibernateRepository).List<AttachmentInfo>(NHibernate.Criterion.DetachedCriteria.For<AttachmentInfo>() .Add(NHibernate.Criterion.Expression.Eq("FileName", e.Name))); if (list == null || list.Count == 0) { Created(rep, e); } FileInfo fi = new FileInfo(e.FullPath); FileStream fs = fi.OpenRead(); byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, Convert.ToInt32(fs.Length)); fs.Close(); list[0].Data = bytes; rep.Update(list[0]); } catch (Exception ex) { Console.WriteLine("Changed Members of Watcher Error:" + ex.Message); } }
public void UpdateInstructor(Instructor obj) { _instRepository.Update(obj); }
public CustomResult Update(UpdatePersonnelDto dto) { var personnel = _personnelRepository.GetById(dto.Id); if (personnel != null) { #region Update Personnel Info if (PersonnelCodeExistsInDB(dto.Code, personnel.Id)) { return(new CustomResult { IsValid = false, Message = "person code is not unique" }); } if (NationalCodeExistsInDB(dto.NationalCode, personnel.Id)) { return(new CustomResult { IsValid = false, Message = "national code is not unique" }); } personnel.Code = dto.Code; personnel.Name = dto.Name; personnel.LastName = dto.LastName; personnel.FathersName = dto.FathersName; personnel.NationalCode = dto.NationalCode; personnel.BirthCertificateCode = dto.BirthCertificateCode; personnel.PlaceOfBirth = dto.PlaceOfBirth; personnel.State = dto.State; personnel.City = dto.City; personnel.PostalCode = dto.PostalCode; personnel.BirthDate = dto.BirthDate; personnel.Email = dto.Email; personnel.Mobile = dto.Mobile; personnel.Phone = dto.Phone; personnel.Address = dto.Address; personnel.Education = dto.Education; personnel.MilitaryServiceStatus = dto.MilitaryServiceStatus; personnel.Gender = dto.Gender; personnel.MaritalStatus = dto.MaritalStatus; personnel.GroupCategoryId = dto.GroupCategoryId; personnel.EmployeementTypeId = dto.EmployeementTypeId; personnel.PositionId = dto.PositionId; personnel.InsuranceRecordDuration = dto.InsuranceRecordDuration; personnel.NoneInsuranceRecordDuration = dto.NoneInsuranceRecordDuration; personnel.BankAccountNumber = dto.BankAccountNumber; personnel.DateOfEmployeement = dto.DateOfEmployeement; personnel.FirstDateOfWork = dto.FirstDateOfWork; personnel.LastDateOfWork = dto.LastDateOfWork; personnel.LeavingWorkCause = dto.LeavingWorkCause; personnel.ActiveState = dto.ActiveState; _personnelRepository.Update(personnel); #endregion #region Update Approvals _personnelApprovalProcService.CreateOrUpdate(new PersonnelApprovalProcDto { Id = dto.Id, DismissalApprovalProcId = dto.DismissalApprovalProcId, DutyApprovalProcId = dto.DutyApprovalProcId, ShiftReplacementProcId = dto.ShiftReplacementProcId }); _dismissalApprovalService.Update(dto.DismissalApprovals, personnel.Id); _dutyApprovalService.Update(dto.DutyApprovals, personnel.Id); #endregion return(new CustomResult { IsValid = true }); } else { try { throw new LogicalException(); } catch (LogicalException ex) { _logger.LogLogicalError (ex, "Personnel entity with the id: '{0}', is not available." + " update operation failed.", dto.Id); throw; } } }
public async Task <ServiceResult <List <DiscoveryPatch> > > DiscoverPayments(List <Account> accounts) { List <DiscoveryPatch> discoveryPatches = new List <DiscoveryPatch>(); try { foreach (var account in accounts) { DiscoveryPatch newDiscoveryPatch = null; string lastCursor = null; try { var discoveryPatch = _discoveryPatchRepository.Select().Include(d => d.Account) .Where(A => A.AccountId == account.Id && A.RecoredCreationDate == A.Account.DiscoveryPatchs.Max(x => x.RecoredCreationDate)).FirstOrDefault(); var walletPayments = new List <WalletPayment>(); var payments = new List <Payment>(); lastCursor = discoveryPatch?.Cursor; newDiscoveryPatch = _discoveryPatchRepository.Insert(new DiscoveryPatch(account)); newDiscoveryPatch.Start(lastCursor); _discoveryPatchRepository.SaveChanges(); await GetIncrementalWalletPayments(account.PublicKey, lastCursor, walletPayments); walletPayments.ForEach(WP => payments.Add(new Payment() { Amount = WP.Amount, CreatedAt = WP.CreatedAt, FromAccount = WP.FromAccount, PagingToken = WP.PagingToken, PaymentId = WP.PaymentId, SourceAccount = WP.SourceAccount, ToAccount = WP.ToAccount, TransactionHash = WP.TransactionHash, TransactionSuccessful = WP.TransactionSuccessful })); _paymentRepository.Insert(payments); var newCursor = payments.Count > 0 ? payments.Last()?.PagingToken : lastCursor; newDiscoveryPatch.EndSuccessful(newCursor, payments.Count); _discoveryPatchRepository.Update(newDiscoveryPatch); _paymentRepository.SaveChanges(); discoveryPatches.Add(newDiscoveryPatch); } catch (Exception ex) { discoveryPatches.Add(newDiscoveryPatch ?? new DiscoveryPatch(account).Failed(lastCursor)); Logger.Error(ex); } } } catch (Exception ex) { Logger.Error(ex); return(new ServiceResult <List <DiscoveryPatch> >(ex)); } return(new ServiceResult <List <DiscoveryPatch> >(discoveryPatches, true)); }
public Person Update(Person person) { return(_repository.Update(person)); }
public void UpdateNarudzba(Narudzba narudzba) { narudzbaRepository.Update(narudzba); }
/// <summary> /// Method procced order to shiprocket /// </summary> /// <param name="order"></param> /// <param name="ShipRocketToken"></param> /// <param name="ShipRocketBaseUrl"></param> /// <param name="nopshiprocket"></param> /// <param name="Iscod"></param> public void ProccedShiprocket(Order order, string ShipRocketToken, string ShipRocketBaseUrl, NopShiprocketOrder nopshiprocket, bool Iscod = false) { try { var storeScope = _storeContext.ActiveStoreScopeConfiguration; var ShipRocketSettings = _settingService.LoadSetting <ShipRocketSetting>(storeScope); ShipRocketApiConfiguration rocket = new ShipRocketApiConfiguration(); var dimention = GetProductDimentions(order); var Shippingcharge = Convert.ToInt32(order.OrderShippingInclTax); var discount = (order.OrderDiscount > 0)? Convert.ToInt32(order.OrderDiscount) : Convert.ToInt32(order.OrderSubTotalDiscountInclTax); var OrderBillingAddress = _addressService.GetAddressById(order.BillingAddressId); var billingCountry = _countryService.GetCountryById((OrderBillingAddress.CountryId.HasValue) ? (int)OrderBillingAddress.CountryId : 0); var BillingStateProvince = _stateProvinceService.GetStateProvinceById((OrderBillingAddress.StateProvinceId.HasValue) ? (int)OrderBillingAddress.StateProvinceId : 0); var OrderShippingAddress = _addressService.GetAddressById((order.ShippingAddressId.HasValue) ? (int)order.ShippingAddressId : 0); var shippingCountry = _countryService.GetCountryById((OrderBillingAddress.CountryId.HasValue) ? (int)OrderShippingAddress.CountryId : 0); var ShipingStateProvince = _stateProvinceService.GetStateProvinceById((OrderShippingAddress.StateProvinceId.HasValue) ? (int)OrderShippingAddress.StateProvinceId : 0); var ShiprockerOrder = new ShipRocketOrderJsonNoEway { order_id = "Nop Order " + order.Id, order_date = Convert.ToString(order.CreatedOnUtc), pickup_location = ShipRocketSettings.PickUpLocation, channel_id = Convert.ToString(ShipRocketSettings.ChannelId), billing_customer_name = OrderBillingAddress == null ? "" : OrderBillingAddress.FirstName, billing_last_name = OrderBillingAddress == null ? "" : OrderBillingAddress.LastName, billing_address = OrderBillingAddress == null ? "" : OrderBillingAddress.Address1, billing_address_2 = OrderBillingAddress == null ? "" : OrderBillingAddress.Address2, billing_city = OrderBillingAddress == null ? "" : OrderBillingAddress.City, billing_pincode = OrderBillingAddress == null ? "" : OrderBillingAddress.ZipPostalCode, billing_state = OrderBillingAddress == null ? "" : BillingStateProvince == null ? "India" : BillingStateProvince.Name, billing_country = OrderBillingAddress == null ? "" : billingCountry.Name, billing_email = OrderBillingAddress == null ? "" : OrderBillingAddress.Email, billing_phone = OrderBillingAddress == null ? "" : OrderBillingAddress.PhoneNumber, shipping_is_billing = true, shipping_customer_name = OrderShippingAddress == null ? "" : OrderShippingAddress.FirstName, shipping_last_name = OrderShippingAddress == null ? "" : OrderShippingAddress.LastName, shipping_address = OrderShippingAddress == null ? "" : OrderShippingAddress.Address1, shipping_address_2 = OrderShippingAddress == null ? "" : OrderShippingAddress.Address2, shipping_city = OrderShippingAddress == null ? "" : OrderShippingAddress.City, shipping_pincode = OrderShippingAddress == null ? "" : OrderShippingAddress.ZipPostalCode, shipping_country = OrderShippingAddress == null ? "" : shippingCountry.Name, shipping_state = OrderShippingAddress == null ? "" : ShipingStateProvince == null ? "India" : ShipingStateProvince.Name, shipping_email = OrderShippingAddress == null ? "" : OrderShippingAddress.Email, shipping_phone = OrderShippingAddress == null ? "" : OrderShippingAddress.PhoneNumber, order_items = GetOrderItemFromOrder(order), payment_method = Iscod == true ? "COD" : "Prepaid", shipping_charges = Shippingcharge, giftwrap_charges = 0, transaction_charges = Convert.ToInt32(order.PaymentMethodAdditionalFeeInclTax), total_discount = discount, sub_total = Convert.ToInt32(order.OrderSubtotalInclTax), length = dimention.length, breadth = dimention.breadth, height = dimention.height, weight = dimention.weight }; var result = rocket.createShiprocketOrdernoeway(ShipRocketToken, ShipRocketBaseUrl, ShiprockerOrder); if (!string.IsNullOrEmpty(result)) { if (!result.Contains("message")) { ShipRocketOrderResponse Responses = JsonConvert.DeserializeObject <ShipRocketOrderResponse>(result); if (Responses.order_id > 0 && Responses.shipment_id > 0) { var OrderNote = (from a in _orderNoteRepository.Table where a.OrderId.Equals(order.Id) select a).FirstOrDefault(); if (OrderNote != null) { OrderNote.CreatedOnUtc = DateTime.UtcNow; OrderNote.Note = "Ship Rocket Order Id-" + Responses.order_id + "Ship Rocket shipment Id-" + Responses.shipment_id; OrderNote.OrderId = order.Id; _orderNoteRepository.Update(OrderNote); } nopshiprocket.ShiprocketOrderId = Convert.ToString(Responses.order_id); nopshiprocket.ShiprocketStatues = true; _ShipRocketService.UpdateShiprocketOrder(nopshiprocket); } } else { _LoggerService.InsertLog(LogLevel.Error, "Error log while creating shiprocket order for order no: " + order.Id, result); nopshiprocket.ErrorResponse = result; _ShipRocketService.UpdateShiprocketOrder(nopshiprocket); _ShipRocketMessageService.SendOrderShiprocketErrorStoreOwnerNotification(order, workContext.WorkingLanguage.Id, nopshiprocket); } } } catch (Exception Exe) { _LoggerService.InsertLog(LogLevel.Error, "Error log while executing order paid event :-" + order.Id, Exe.Message + Exe.InnerException); } }
public void UpdateSkladiste(Skladiste skladiste) { skladisteRepository.Update(skladiste); }
/// <summary> /// Inserts a picture /// </summary> /// <param name="formFile">Form file</param> /// <param name="defaultFileName">File name which will be use if IFormFile.FileName not present</param> /// <param name="virtualPath">Virtual path</param> /// <returns>Picture</returns> public virtual Picture InsertPicture(IFormFile formFile, string defaultFileName = "", string virtualPath = "") { var imgExt = new List <string> { ".bmp", ".gif", ".jpeg", ".jpg", ".jpe", ".jfif", ".pjpeg", ".pjp", ".png", ".tiff", ".tif" } as IReadOnlyCollection <string>; var fileName = formFile.FileName; if (string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(defaultFileName)) { fileName = defaultFileName; } //remove path (passed in IE) fileName = _fileProvider.GetFileName(fileName); var contentType = formFile.ContentType; var fileExtension = _fileProvider.GetFileExtension(fileName); if (!string.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } if (imgExt.All(ext => !ext.Equals(fileExtension, StringComparison.CurrentCultureIgnoreCase))) { return(null); } //contentType is not always available //that's why we manually update it here //http://www.sfsu.edu/training/mimetype.htm if (string.IsNullOrEmpty(contentType)) { switch (fileExtension) { case ".bmp": contentType = MimeTypes.ImageBmp; break; case ".gif": contentType = MimeTypes.ImageGif; break; case ".jpeg": case ".jpg": case ".jpe": case ".jfif": case ".pjpeg": case ".pjp": contentType = MimeTypes.ImageJpeg; break; case ".png": contentType = MimeTypes.ImagePng; break; case ".tiff": case ".tif": contentType = MimeTypes.ImageTiff; break; default: break; } } var picture = InsertPicture(GetDownloadBits(formFile), contentType, _fileProvider.GetFileNameWithoutExtension(fileName)); if (string.IsNullOrEmpty(virtualPath)) { return(picture); } picture.VirtualPath = _fileProvider.GetVirtualPath(virtualPath); _pictureRepository.Update(picture); return(picture); }
public void UpdatePodkategorija(Podkategorija podkategorija) { podkategorijaRepository.Update(podkategorija); }
public void UpdateEvent(Event eventToUpdate) { Require.NotNull(eventToUpdate, nameof(eventToUpdate)); _eventRepository.Update(eventToUpdate); }
public void UpdateKategorija(Kategorija kategorija) { kategorijaRepository.Update(kategorija); }
protected override DriverResult Editor(EmailContactPart part, IUpdateModel updater, dynamic shapeHelper) { View_EmailVM oldviewModel = new View_EmailVM(); updater.TryUpdateModel(oldviewModel, Prefix, null, null); bool error = false; _transaction.Demand(); foreach (View_EmailVM_element vmel in oldviewModel.Elenco) { if ((vmel.Delete || string.IsNullOrEmpty(vmel.Email)) && vmel.Id > 0) { CommunicationEmailRecord cmr = _repoEmail.Fetch(x => x.Id == vmel.Id).FirstOrDefault(); _repoEmail.Delete(cmr); } else if (!vmel.Delete) { if (!string.IsNullOrEmpty(vmel.Email)) { if (_repoEmail.Fetch(x => x.Email == vmel.Email && x.Id != vmel.Id).Count() > 0) { error = true; updater.AddModelError("Error", T("Email can't be assigned is linked to other contact")); } } if (vmel.Id > 0) { CommunicationEmailRecord cmr = _repoEmail.Fetch(x => x.Id == vmel.Id).FirstOrDefault(); if (cmr.Email != vmel.Email || cmr.Validated != vmel.Validated || cmr.AccettatoUsoCommerciale != vmel.AccettatoUsoCommerciale || cmr.AutorizzatoTerzeParti != vmel.AutorizzatoTerzeParti) { cmr.Email = vmel.Email; cmr.Validated = vmel.Validated; cmr.AccettatoUsoCommerciale = vmel.AccettatoUsoCommerciale; cmr.AutorizzatoTerzeParti = vmel.AutorizzatoTerzeParti; cmr.DataModifica = DateTime.Now; _repoEmail.Update(cmr); } } else { View_EmailVM_element vm = new View_EmailVM_element(); CommunicationEmailRecord cmr = new CommunicationEmailRecord(); _mapper.Map <View_EmailVM_element, CommunicationEmailRecord>(vm, cmr); cmr.Email = vmel.Email; cmr.Validated = vmel.Validated; cmr.AccettatoUsoCommerciale = vmel.AccettatoUsoCommerciale; cmr.AutorizzatoTerzeParti = vmel.AutorizzatoTerzeParti; cmr.EmailContactPartRecord_Id = part.Id; _repoEmail.Create(cmr); } } } if (error == true) { _transaction.Cancel(); } else { _repoEmail.Flush(); } // _transaction.RequireNew(); return(Editor(part, shapeHelper)); }
public void UpdateStavka(Stavka stavka) { stavkaRepository.Update(stavka); }
public void Update(User user) { repository.Update(user); }
public IActionResult Put(Movie movie) { _movieRepository.Update(movie); return(Ok()); }
internal static void Persist(IRepository<Instance> instanceRepository, Instance instanceToPersist, SaveMechanic saveMechanic) { switch(saveMechanic) { case SaveMechanic.Add: instanceRepository.Add(instanceToPersist); break; case SaveMechanic.Update: instanceRepository.Update(instanceToPersist); break; default: throw new InvalidOperationException("Unknown save mechanic. This should never happen."); } }
public void Update(Book entity) { repository.Update(entity); }
internal ChangeSet Sync(DropboxHandler.DropboxInfo deploymentInfo, string branch, ILogger logger, IRepository repository) { DropboxDeployInfo info = deploymentInfo.DeployInfo; _logger = logger; _successCount = 0; _fileCount = 0; _failedCount = 0; _retriedCount = 0; if (_settings.GetValue(CursorKey) != info.OldCursor) { throw new InvalidOperationException(Resources.Error_MismatchDropboxCursor); } if (!repository.IsEmpty()) { // git checkout --force <branch> repository.ClearLock(); repository.Update(branch); } ChangeSet changeSet; string message = null; try { using (_tracer.Step("Synch with Dropbox")) { // Sync dropbox => repository directory ApplyChanges(deploymentInfo); } message = String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_Synchronized, deploymentInfo.DeployInfo.Deltas.Count()); } catch (Exception) { message = String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_SynchronizedWithFailure, _successCount, deploymentInfo.DeployInfo.Deltas.Count(), _failedCount); throw; } finally { _logger.Log(message); _logger.Log(String.Format("{0} downloaded files, {1} successful retries.", _fileCount, _retriedCount)); _status.Open(deploymentInfo.TargetChangeset.Id).UpdateMessage(message); _status.Open(deploymentInfo.TargetChangeset.Id).UpdateProgress(String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_Committing, _successCount)); // Commit anyway even partial change changeSet = repository.Commit(message, String.Format("{0} <{1}>", info.UserName, info.Email)); } // Save new dropboc cursor LogInfo("Update dropbox cursor"); _settings.SetValue(CursorKey, info.NewCursor); return changeSet; }
public void StorePushNotification(PushNotificationRecord pushElement) { PushNotificationRecord oldPush = _pushNotificationRepository.Fetch(x => (x.UUIdentifier == pushElement.UUIdentifier || x.Token == pushElement.Token) && x.Produzione == pushElement.Produzione && x.Device == pushElement.Device).FirstOrDefault(); DateTime adesso = DateTime.Now; string oldUUId = ""; if (oldPush != null) // se dispositivo già registrato sovrascrivo lo stesso record { oldUUId = oldPush.UUIdentifier; oldPush.Device = pushElement.Device; oldPush.UUIdentifier = pushElement.UUIdentifier; oldPush.Token = pushElement.Token; oldPush.Validated = pushElement.Validated; oldPush.DataModifica = adesso; oldPush.Produzione = pushElement.Produzione; oldPush.Language = pushElement.Language; // anche se il dispositivo è già esistente, registra host, prefix e machineName dell'ambiente corrente // Rif: https://lasergroup.teamwork.com/index.cfm#tasks/18521520 oldPush.RegistrationUrlHost = _shellSetting.RequestUrlHost ?? ""; oldPush.RegistrationUrlPrefix = _shellSetting.RequestUrlPrefix ?? ""; oldPush.RegistrationMachineName = System.Environment.MachineName ?? ""; oldPush.MobileContactPartRecord_Id = EnsureContactId(oldPush.UUIdentifier); _pushNotificationRepository.Update(oldPush); } else { pushElement.Id = 0; pushElement.DataInserimento = adesso; pushElement.DataModifica = adesso; pushElement.MobileContactPartRecord_Id = EnsureContactId(pushElement.UUIdentifier); // se è un nuovo dispositivo, registra anche host, prefix e machineName dell'ambiente corrente pushElement.RegistrationUrlHost = _shellSetting.RequestUrlHost ?? ""; pushElement.RegistrationUrlPrefix = _shellSetting.RequestUrlPrefix ?? ""; pushElement.RegistrationMachineName = System.Environment.MachineName ?? ""; _pushNotificationRepository.Create(pushElement); } // cerca eventuali record corrispondenti in UserDevice e fa sì che ce ne sia uno solo relativo al nuovo UUIdentifier (quello con l'Id più recente) // eliminando eventualmente i duplicati e i record riferiti al vecchio UUIdentifier; UserDeviceRecord my_disp = null; var elencoNuovi = _userDeviceRecord.Fetch(x => x.UUIdentifier == pushElement.UUIdentifier).OrderByDescending(y => y.Id).ToList(); foreach (var record in elencoNuovi) { if (my_disp == null) { my_disp = record; } else { _userDeviceRecord.Delete(record); } } if (oldPush != null && oldUUId != pushElement.UUIdentifier) { var elencoVecchi = _userDeviceRecord.Fetch(x => x.UUIdentifier == oldUUId).OrderByDescending(y => y.Id).ToList(); foreach (var record in elencoVecchi) { if (my_disp == null) { // aggiorna uno dei record che aveva il vecchio UUIdentifier, quello con l'Id più recente my_disp = record; my_disp.UUIdentifier = pushElement.UUIdentifier; _userDeviceRecord.Update(my_disp); } else { _userDeviceRecord.Delete(record); } } } }
public async Task DeployAsync(IRepository repository, ChangeSet changeSet, string deployer, bool clean, bool needFileUpdate = true) { using (var deploymentAnalytics = new DeploymentAnalytics(_analytics, _settings)) { Exception exception = null; ITracer tracer = _traceFactory.GetTracer(); IDisposable deployStep = null; ILogger innerLogger = null; string targetBranch = null; // If we don't get a changeset, find out what branch we should be deploying and get the commit ID from it if (changeSet == null) { targetBranch = _settings.GetBranch(); changeSet = repository.GetChangeSet(targetBranch); if (changeSet == null) { throw new InvalidOperationException(String.Format("The current deployment branch is '{0}', but nothing has been pushed to it", targetBranch)); } } string id = changeSet.Id; IDeploymentStatusFile statusFile = null; try { deployStep = tracer.Step("DeploymentManager.Deploy(id)"); // Remove the old log file for this deployment id string logPath = GetLogPath(id); FileSystemHelpers.DeleteFileSafe(logPath); statusFile = GetOrCreateStatusFile(changeSet, tracer, deployer); statusFile.MarkPending(); ILogger logger = GetLogger(changeSet.Id); if (needFileUpdate) { using (tracer.Step("Updating to specific changeset")) { innerLogger = logger.Log(Resources.Log_UpdatingBranch, targetBranch ?? id); using (var writer = new ProgressWriter()) { // Update to the specific changeset or branch repository.Update(targetBranch ?? id); } } } if (_settings.ShouldUpdateSubmodules()) { using (tracer.Step("Updating submodules")) { innerLogger = logger.Log(Resources.Log_UpdatingSubmodules); repository.UpdateSubmodules(); } } if (clean) { tracer.Trace("Cleaning {0} repository", repository.RepositoryType); innerLogger = logger.Log(Resources.Log_CleaningRepository, repository.RepositoryType); repository.Clean(); } // set to null as Build() below takes over logging innerLogger = null; // Perform the build deployment of this changeset await Build(changeSet, tracer, deployStep, repository, deploymentAnalytics); } catch (Exception ex) { exception = ex; if (innerLogger != null) { innerLogger.Log(ex); } if (statusFile != null) { MarkStatusComplete(statusFile, success: false); } tracer.TraceError(ex); deploymentAnalytics.Error = ex.ToString(); if (deployStep != null) { deployStep.Dispose(); } } // Reload status file with latest updates statusFile = _status.Open(id); if (statusFile != null) { await _hooksManager.PublishEventAsync(HookEventTypes.PostDeployment, statusFile); } if (exception != null) { throw new DeploymentFailedException(exception); } } }
private Image UpdateImage(IRootPathProvider pathProvider, IRepository repository, Image image, HttpFile newImage) { if (this.HasNewImage(image, newImage)) { // delete the image if (image != null) { image.Delete(); } // add the new image image = new Image() { Filename = newImage.Name }; repository.Add(image); image.SaveImage(newImage.Value); repository.Update(image); } return image; }