public IHttpActionResult PutPortfolio(int id, Portfolio portfolio) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != portfolio.Id) { return(BadRequest()); } db.Entry(portfolio).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!PortfolioExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public IActionResult OnGet(int id) { if (!_context.Posts.Any(p => p.Id == id)) { return(RedirectToPage("Index")); } PopulateOptions(); Post = _context.Posts.Where(p => p.Id == id).Include(p => p.Content).ThenInclude(c => c.Language).FirstOrDefault(); var Contents = Post.Content ?? new List <Content>(); //Check if content list has all languages if (Contents.Count != Languages.Count) { //Populate Content with amount of language options, skip existing for (int i = 0; i < Languages.Count; i++) { //Check if content has language id if (!Contents.Any(c => c.LanguageId == Languages[i].Id)) { //Add new content object to list if none found Contents.Add(new Content { Language = Languages[i], LanguageId = Languages[i].Id, PostId = Post.Id }); } } _context.Update(Post); _context.SaveChanges(); } Post.Content = Contents; Console.WriteLine(string.Empty); return(Page()); }
public void Create(PortfolioModel portfolioModel) { var portfolio = _context.Portfolios.FirstOrDefault(x => x.ISIN == portfolioModel.ISIN); if (portfolio == null) { var currency = _context.Currencys.FirstOrDefault(x => x.Name == portfolioModel.Currency); var portfolioToAdd = new Entity.Entity.Portfolio { ISIN = portfolioModel.ISIN, MarketValue = portfolioModel.MarketValue, Date = portfolioModel.Date, Currency = currency }; _context.Portfolios.Add(portfolioToAdd); if (portfolioModel.Positions != null) { var countrys = _context.Countrys.ToList(); var currencys = _context.Currencys.ToList(); var positionTypes = _context.PositionTypes.ToList(); List <Entity.Entity.Position> positions = new List <Entity.Entity.Position>(); foreach (var position in portfolioModel.Positions) { positions.Add(new Entity.Entity.Position { ISIN = position.ISIN, Country = countrys.FirstOrDefault(x => x.Name == position.CountryName), Name = position.Name, MarketValue = position.MarketValue, Currency = currencys.FirstOrDefault(x => x.Name == position.CurrencyName), Type = positionTypes.FirstOrDefault(x => x.Name == position.TypeName), PortfolioId = portfolioToAdd.Id }); } _context.Positions.AddRange(positions); } _context.SaveChanges(); ChangeSharePercentageByISIN(portfolioModel); } }
public IActionResult PostReadingLogs(ReadingLog readingLog) { _context.ReadingLogs.Add(readingLog); _context.SaveChanges(); return(Ok()); }
public ActionResult Create(Tag tag) { if (ModelState.IsValid) { db.Tags.Add(tag); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(tag)); }
public IActionResult Create(Service model, IFormFile file, string isHomeBool, int?imgId) { bool isHome; Image img = new Image(); if (isHomeBool == "on") { isHome = true; } else { isHome = false; } if (file != null) { string fileFolder = "wwwroot\\assets\\img\\services"; string path = Path.Combine(Directory.GetCurrentDirectory(), fileFolder, file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { file.CopyTo(stream); ViewBag.Message = string.Format("<b>{0}</b> yüklendi.<br /> Yüklendiği Klasör: </br>{1}", file.FileName, path); } img = new Image() { ImageName = file.FileName, FullPath = "assets\\img\\services", Service = new Service() { isHome = isHome } }; } else if (imgId != null) { img = context.Images.FirstOrDefault(i => i.ImageId == imgId); } else { ViewBag.Message = "Resim seçilmedi/yüklenmedi"; ViewBag.Images = context.Images.Where(p => p.FullPath.Contains("services") && p.Service == null).ToList(); return(View()); } Service entity = new Service() { Title = model.Title, Text = model.Text, Image = img, isHome = isHome }; context.Services.Add(entity); context.SaveChanges(); return(RedirectToAction("Index")); }
public IActionResult Create(IFormFile file, string folder) { if (file != null) { string fileFolder = ""; string path = ""; if (folder == "portfolio") { fileFolder = "wwwroot\\assets\\img\\portfolio"; path = Path.Combine(Directory.GetCurrentDirectory(), fileFolder, file.FileName); } else if (folder == "services") { fileFolder = "wwwroot\\assets\\img\\services"; path = Path.Combine(Directory.GetCurrentDirectory(), fileFolder, file.FileName); } else if (folder == "clients") { fileFolder = "wwwroot\\assets\\img\\clients"; path = Path.Combine(Directory.GetCurrentDirectory(), fileFolder, file.FileName); } else if (folder == "ides") { fileFolder = "wwwroot\\assets\\img\\ides"; path = Path.Combine(Directory.GetCurrentDirectory(), fileFolder, file.FileName); } else { fileFolder = "wwwroot\\assets\\img"; path = Path.Combine(Directory.GetCurrentDirectory(), fileFolder, file.FileName); } if (!Directory.Exists(fileFolder)) { Directory.CreateDirectory(fileFolder); } string filename = string.Format(file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { file.CopyTo(stream); ViewBag.Message = string.Format("<b>{0}</b> yüklendi.<br /> Yüklendiği Klasör: </br>{1}", file.FileName, path); } Image entity = new Image() { ImageName = file.FileName, FullPath = fileFolder.Replace("wwwroot\\", "") }; context.Images.Add(entity); context.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.Message = "Dosya Seçilmedi"; return(View()); }
public ActionResult Create(Project project) { if (ModelState.IsValid) { db.Projects.Add(project); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(project)); }
public ActionResult Create(ScreenShot screenshot) { if (ModelState.IsValid) { db.ScreenShots.Add(screenshot); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ProjectID = new SelectList(db.Projects, "ProjectID", "alias", screenshot.ProjectID); return(View(screenshot)); }
public ActionResult Create(ProjectTag projecttag) { if (ModelState.IsValid) { db.ProjectTags.Add(projecttag); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ProjectID = new SelectList(db.Projects, "ProjectID", "alias", projecttag.ProjectID); ViewBag.TagID = new SelectList(db.Tags, "TagID", "name", projecttag.TagID); return(View(projecttag)); }
private void SyncUpdates <T>(PortfolioContext dest, IEnumerable <T> sourceProjectDetail, Project destProject) where T : IPostgresProject { // Now sync the updates T lastUpdate = default(T); foreach (var sourceUpdate in sourceProjectDetail.OrderBy(u => u.timestamp)) { var destUpdate = destProject.Updates.SingleOrDefault(u => u.SyncId == sourceUpdate.id); if (lastUpdate == null || !lastUpdate.IsDuplicate(sourceUpdate)) { if (destUpdate == null) { destUpdate = new ProjectUpdateItem() { SyncId = sourceUpdate.id, Project = destProject }; destProject.Updates.Add(destUpdate); } mapper.Map(sourceUpdate, destUpdate, opt => { opt.Items[nameof(PortfolioContext)] = dest; }); if (lastUpdate != null && (lastUpdate.update?.Equals(sourceUpdate.update) ?? false)) { destUpdate.Text = null; debugLogDiscardedUpdateText(sourceUpdate); } } else { debugLogDiscardedUpdateText(sourceUpdate); if (destUpdate != null) { dest.ProjectUpdates.Remove(destUpdate); } } lastUpdate = sourceUpdate; } dest.SaveChanges(); // Set the latest update var updates = destProject.Updates.OrderBy(u => u.Timestamp); destProject.FirstUpdate = updates.First(); destProject.LatestUpdate = updates.Last(); dest.SaveChanges(); }
public void SyncUsers() { log.Add("Syncing users..."); using (var source = new MigratePortfolioContext <oddproject>("odd")) using (var dest = new PortfolioContext()) { // Ensure we have all access groups var agViewKeys = SyncMaps.accessGroupKeyMap.Select(kv => kv.Value).Distinct(); var accessGroups = agViewKeys.Select(k => new AccessGroup() { ViewKey = k, Description = k }).ToArray(); dest.AccessGroups.AddOrUpdate(a => a.ViewKey, accessGroups); dest.SaveChanges(); var accessGroupLookup = dest.AccessGroups.Where(ag => ag.ViewKey != null).ToDictionary(ag => ag.ViewKey); // Sync the users foreach (var sourceUser in source.users) { var destUser = dest.Users.SingleOrDefault(u => u.UserName == sourceUser.username); if (destUser == null) { destUser = new User() { UserName = sourceUser.username, PasswordHash = sourceUser.pass_hash, Timestamp = sourceUser.timestamp, }; dest.Users.Add(destUser); log.Add($"Added user {destUser.UserName}"); } destUser.AccessGroup = accessGroupLookup[SyncMaps.accessGroupKeyMap[sourceUser.access_group]]; string[] roles; if (SyncMaps.userRoleMap.TryGetValue(sourceUser.username, out roles)) { destUser.RoleList = string.Join(",", roles); } } dest.SaveChanges(); var toDelete = dest.AccessGroups.Where(a => a.ViewKey == null).ToArray(); if (toDelete.Length > 0) { dest.AccessGroups.RemoveRange(toDelete); dest.SaveChanges(); } log.Add("Sync users complete."); } }
public Holding CreateHolding(Holding holding) { try { _ctx.Add(holding); _ctx.SaveChanges(); return(holding); } catch (Exception ex) { _logger.LogError($"Error creating holding for user {holding?.UserId}", ex); throw; } }
public IHttpActionResult Put(Transaction transaction) { if (!ModelState.IsValid) { return(BadRequest("Invalid model")); } using (var context = new PortfolioContext()) { try { var result = context.Transactions.SingleOrDefault(t => t.TransactionId == transaction.TransactionId); if (result != null) { result.CashValue = transaction.CashValue; result.Commission = transaction.Commission; result.Date = transaction.Date; result.Name = transaction.Name; result.Price = transaction.Price; result.Shares = transaction.Shares; result.Symbol = transaction.Symbol; result.Type = transaction.Type; context.SaveChanges(); return(Ok()); } else { return(this.Insert(transaction)); } } catch (Exception ex) { return(InternalServerError(ex)); } } }
public bool Create(InterviewRequestVM irVM) { Company company = db.Companies.FirstOrDefault(com => com.Name == irVM.Company); if (company != null) { company.InterviewRequests.Add(new InterviewRequest { Time = irVM.Time, Location = irVM.Location }); } else { InterviewRequest ir = new InterviewRequest { Time = irVM.Time, Location = irVM.Location }; Company c = new Company { Contact = irVM.Contact, Name = irVM.Company, Email = irVM.Email, Phone = irVM.Phone }; db.Companies.Add(c); //Which one I think the second ????? db.InterviewRequests.Add(ir); c.InterviewRequests.Add(ir); } db.SaveChanges(); return(true); }
public IActionResult Comment(Comment comment) { db.Comments.Add(comment); db.SaveChanges(); showAllComments(); return(View("Comment")); }
public IActionResult AddBook(Book book) { // check validity of data if (string.IsNullOrWhiteSpace(book.Author) || string.IsNullOrWhiteSpace(book.Title)) { return(BadRequest("Title and Author must be provided")); } // check if book already exists var sameBook = _context.Books.Where <Book>(b => b.Author == book.Author && b.Title == book.Title).FirstOrDefault(); if (sameBook != null) { return(BadRequest("This book already exists in the database")); } // save it in the database try { _context.Books.Add(book); _context.SaveChanges(); } catch (Exception ex) { return(BadRequest("Failed to save book into the database")); } return(Ok()); }
public IHttpActionResult Delete(int id) { if (id < 0) { return(BadRequest("Invalid id")); } using (var context = new PortfolioContext()) { try { var transaction = context.Transactions .Where(t => t.TransactionId == id) .FirstOrDefault(); if (transaction != null) { context.Entry(transaction).State = EntityState.Deleted; context.SaveChanges(); } return(Ok()); } catch (Exception ex) { return(InternalServerError(ex)); } } }
public static void Initialize(PortfolioContext context) { if (!context.Works.Any()) { context.Works.AddRange ( new Work { desc_short = "Banner for up2date", desc_long = "", tools = "Adobe Photoshop" }, new Work { desc_short = "Banner for RomanD", desc_long = "", tools = "Adobe XD" } ); context.SaveChanges(); } if (!context.Orders.Any()) { context.Orders.AddRange ( new Order { user_name = "test", contact_email = "*****@*****.**" } ); context.SaveChanges(); } if (!context.Comments.Any()) { context.Comments.AddRange ( new Comment { user_name = "test", contact_email = "*****@*****.**", feedback = "nice work" } ); context.SaveChanges(); } }
public void DeleteCommentById(int commentId) { var context = new PortfolioContext(); var entryComment = context.Comment.FirstOrDefault(x => x.CommentId == commentId); context.Comment.Remove(entryComment); context.SaveChanges(); }
public void DeleteBlogById(int commentId) { var context = new PortfolioContext(); var entryBlog = context.Blog.FirstOrDefault(x => x.BlogId == commentId); context.Blog.Remove(entryBlog); context.SaveChanges(); }
public ActionResult DeleteConfirmed(int id) { Project project = _context.Projects.Find(id); _context.Projects.Remove(project); _context.SaveChanges(); return(RedirectToAction("Index")); }
public Project Edit(Project project) { using (var context = new PortfolioContext()) { context.Entry(project).State = EntityState.Modified; context.SaveChanges(); return(project); } }
public ProjectImage Delete(ProjectImage image) { using (var context = new PortfolioContext()) { context.Entry(image).State = EntityState.Deleted; context.SaveChanges(); return(image); } }
public Email Delete(Email image) { using (var context = new PortfolioContext()) { context.Entry(image).State = EntityState.Deleted; context.SaveChanges(); return(image); } }
public IActionResult OnPost() { //TODO: Integrate checking if title/entry already exists. If so, give alert. Post.Modified = Post.Created = DateTime.Now; Post.Public = false; _context.Add(Post); _context.SaveChanges(); return(RedirectToPage($"/PostEdit", new { Id = Post.Id })); }
public ProjectTechnology Delete(ProjectTechnology technology) { using (var context = new PortfolioContext()) { context.Entry(technology).State = EntityState.Deleted; context.SaveChanges(); return(technology); } }
public IActionResult Create(PortfolioViewModel pvm) { Portfolio portfolio = new Portfolio { AboutWork = pvm.AboutWork, InfoAboutMe = pvm.InfoAboutMe, InfoAboutStudy = pvm.InfoAboutStudy, Achievement = pvm.Achievement }; if (pvm.Image != null) { byte[] imageData = null; // считываем переданный файл в массив байтов using (var binaryReader = new BinaryReader(pvm.Image.OpenReadStream())) { imageData = binaryReader.ReadBytes((int)pvm.Image.Length); } // установка массива байтов portfolio.Image = imageData; } _context.Portfolios.Add(portfolio); _context.SaveChanges(); if (pvm.Image != null) { // путь к папке Files string path = "/img/" + portfolio.Id + ".png"; // сохраняем файл в папку Files в каталоге wwwroot using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)) { pvm.Image.CopyTo(fileStream); } FileModel file = new FileModel { Name = pvm.Image.FileName, Path = path }; _context.Files.Add(file); _context.SaveChanges(); } return(RedirectToAction("Create")); }
public Project Delete(int projectId) { using (var context = new PortfolioContext()) { var project = context.Projects.FirstOrDefault(_ => _.ProjectId == projectId); context.Entry(project).State = EntityState.Deleted; context.SaveChanges(); return(project); } }
public IActionResult Create(Category model, string cType) { Category entity = new Category(); if (ModelState.IsValid) { entity.CategoryName = model.CategoryName; if (cType != null) { if (cType == "Lang") { entity.CType = CategoryType.Lang; } else { entity.CType = CategoryType.Tech; } } else { ModelState.AddModelError("", "Kategori türü boş bırakılamaz."); return(View(model)); } if (!model.Filter.StartsWith(".")) { if (model.Filter.Contains(".")) { model.Filter.Replace(".", ""); } entity.Filter = "." + model.Filter; } else { entity.Filter = model.Filter; } context.Categories.Add(entity); context.SaveChanges(); ViewData["message"] = $"{entity.CategoryName} eklendi." + $"{DateTime.Now}"; return(RedirectToAction("Index")); } return(View(model)); }
protected void Seed(PortfolioContext context) { // Cascade null context.Database.ExecuteSqlCommand(@"IF(OBJECT_ID('Project_Media','F') IS NOT NULL) BEGIN ALTER TABLE Project DROP CONSTRAINT Project_Media END"); context.Database.ExecuteSqlCommand(@"ALTER TABLE Project ADD CONSTRAINT Project_Media FOREIGN KEY (MediaID) REFERENCES Media (ID) ON UPDATE CASCADE ON DELETE SET NULL"); context.Database.ExecuteSqlCommand(@"IF(OBJECT_ID('User_Media','F') IS NOT NULL) BEGIN ALTER TABLE AccountUser DROP CONSTRAINT User_Media END"); context.Database.ExecuteSqlCommand(@"ALTER TABLE AccountUser ADD CONSTRAINT User_Media FOREIGN KEY (MediaID) REFERENCES Media (ID) ON UPDATE CASCADE ON DELETE SET NULL"); // Create myself as a user var user = new AccountUser { FirstName = "Hannah", LastName = "Hamlin", Email = "*****@*****.**", Password = SecurePasswordHasher.Hash("password"), MediaID = null, CreatedAt = TimeStamp.Now(), UpdatedAt = TimeStamp.Now() }; context.AccountUsers.Add(user); context.SaveChanges(); }