public ActionResult Create(UserNews login) { try { string fileName = Path.GetFileNameWithoutExtension(login.ImageFile.FileName); string extension = Path.GetExtension(login.ImageFile.FileName); fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; login.Foto = "~/Image/" + fileName; fileName = Path.Combine(Server.MapPath("~/Image/"), fileName); login.ImageFile.SaveAs(fileName); using (NewsContext dbModel = new NewsContext()) { News new_table = new News(); new_table.Data = login.Data; new_table.Noutati = login.Noutati; new_table.Foto = login.Foto; dbModel.New.Add(new_table); dbModel.SaveChanges(); } ModelState.Clear(); return(RedirectToAction("Index")); } catch { return(View()); } }
public ActionResult EditDetails(FeedSelectionViewModel vm) { if (vm == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ; //if user tickled add to feed radio button , add this to the list of feeds current user is following. try { var id = vm.FeedID; FeedChannel chn = (FeedChannel)db.Channels.First(ch => ch.FeedChannelID == id); profile.SelectedChannels.Add(chn); db.SaveChanges(); } catch (Exception ex) { ModelState.AddModelError(string.Empty, $@"Unable to save the record. {ex.Message}"); return(View(vm)); } return(RedirectToAction("FeedsIndex")); }
public ActionResult Create(News news) { db._News.Add(news); db.SaveChanges(); return(RedirectToAction("Index")); }
private static void MakeUpdate() { var newsContext = new NewsContext(); var firstNews = newsContext.News.OrderBy(n => n.Id).First(); Console.WriteLine("Text from DB: {0}", firstNews.Content); Console.Write("User input: "); using (var dbContextTransaction = newsContext.Database.BeginTransaction()) { try { var input = Console.ReadLine(); firstNews.Content = input; newsContext.SaveChanges(); dbContextTransaction.Commit(); Console.WriteLine("Changes successfully saved in the DB."); } catch (DbUpdateConcurrencyException ex) { dbContextTransaction.Rollback(); Console.WriteLine("Conflict!"); MakeUpdate(); } } }
public static void UpdateNews(News news) { using (var context = new NewsContext()) { context.Entry(news).State = EntityState.Modified; context.SaveChanges(); } }
private static void ClearDatabase() { var context = new NewsContext(); context.News.Delete(); context.Users.Delete(); context.SaveChanges(); }
static void Main() { NewsContext newsContext = new NewsContext(); Article article = new Article(); article.Content = "New article"; newsContext.Articles.Add(article); newsContext.SaveChanges(); }
// GET: Article/Details/id public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Article article = db.Articles.Find(id); if (article == null) { return(HttpNotFound()); } article.Views += 1; db.Entry(article).State = EntityState.Modified; db.SaveChanges(); return(View(article)); }
public static void AddNews(News news) { using (var db = new NewsContext()) { db.News.Add(news); db.SaveChanges(); } }
public static void DeleteNews(News news) { using (var context = new NewsContext()) { context.News.Remove(news); context.SaveChanges(); } }
public ActionResult <News> AddNews([FromBody] Context.Model.News news) { news.Id = Guid.NewGuid(); context.News.Add(news); context.SaveChanges(); return(CreatedAtAction("Get", news)); }
public IActionResult AddNews(News news, FormHelper formhelper) { if (news.Header == null || formhelper.CategoryId == null) { return(BadRequest(ModelState)); // TODO: Märk upp meddelande för modelstate // TODO: Validera att rubrik och kategori är unik(?) } using (var context = new NewsContext()) { news.Created = DateTime.Now; news.Updated = DateTime.Now; context.Add(news); var author = context.Authors.Single(x => x.Id == formhelper.AuthorId); var authornews = new AuthorsNews(news, author); context.Add(authornews); context.SaveChanges(); for (int i = 0; i < formhelper.CategoryId.Length; i++) { var tmpnewscategory = new NewsCategories() { NewsId = news.Id, CategoryId = formhelper.CategoryId[i] }; context.Add(tmpnewscategory); context.SaveChanges(); } } var addedMessage = string.Format("Nyheten fick ID {0}", news.Id); return(Json(new { success = true, Message = addedMessage })); }
public IActionResult AddArticle(ArticleViewModel model) { //model validation check if (!ModelState.IsValid) { //sth wrong. Return to the page with model & error data return(View("AddArticle", model)); } //create new article with model data Article article = new Article { Title = model.Title.ToUpper(), Author = model.Author, Text = model.Text, PublishDate = model.PublishDate, EventDate = DateTime.Now, EditorEmail = HttpContext.Session.GetString("SessionKeyEmail") }; //Add new article to database _context.Article.Add(article); _context.SaveChanges(); //go back to Puclish page return(RedirectToAction("Publish", "Home")); }
public ActionResult detailsPost([Bind(Include = "ID,NewsPostID,Title,Text,Author")] Comment cmt) { //Comment _cmt = new Comment(); //db.ID = default(int); if (ModelState.IsValid) { cmt.Author = User.Identity.Name; cmt.PublishDate = DateTime.Now; db.Comments.Add(cmt); db.SaveChanges(); return(RedirectToAction("Details", "NewsPosts", new { id = cmt.NewsPostID })); } else { // Error page here return(View("Details")); } }
public IActionResult Post([FromBody] Article article) { if (article == null) { return(BadRequest()); } if (ModelState.IsValid) { article.TimeStamp = DateTime.Now; context.Articles.Add(article); context.SaveChanges(); return(Ok(article)); } else { return(BadRequest(ModelState)); } }
protected override void Seed(NewsContext db) { // Add default feeds to database if (db.Feeds.Count() == 0 && db.Tags.Count() == 0) { db.Feeds.AddRange(DEFAULT_FEEDS); db.SaveChanges(); } }
public ValuesController(NewsContext context) { // i++; _context = context; List <News> newsList = new List <News>() { new News { Title = "Overskrift", Author = "Simon", Content = "Indhold", CreatedDate = DateTime.Now.AddDays(-4), UpdatedDate = DateTime.Now, HashTags = "#SimonErGud;#FedOpgave" }, new News { Title = "Bob er syg!", Author = "julianbulian", Content = "han er så syg", CreatedDate = DateTime.Now.AddDays(-3), UpdatedDate = DateTime.Now, HashTags = "#FuckingSyg;#MorgenHår;#Dabtastic;#ForhåbentligRaskIgenSnart" }, new News { Title = "Bob er rask!", Author = "julianbulian", Content = "Han er så rask!", CreatedDate = DateTime.Now.AddDays(-2), UpdatedDate = DateTime.Now, HashTags = "#FuckingRask;#Yay;#NearDeathExperience" }, new News { Title = "Bob er syg, igen!", Author = "julianbulian", Content = "Bob var aldrig rask!", CreatedDate = DateTime.Now.AddDays(-1), UpdatedDate = DateTime.Now, HashTags = "#FuckMyLife;#Testamente;#ErDerFlereHashTags?;#HashTagHashTags" }, }; //} //{ // Title = "Overskrift", // Author = "Simon", // Content = "Indhold", // CreatedDate = DateTime.Now.AddDays(-1), // UpdatedDate = DateTime.Now, // HashTags = "#SimonErGud;#FedOpgave" //}; _context.AddRange(newsList); _context.SaveChanges(); }
public ActionResult Delete(int id) { using (NewsContext context = new NewsContext()) { DeleteNodes(context, id); context.SaveChanges(); } return(RedirectToAction("Index")); }
private static void SeedDatabase() { var context = new NewsContext(); CleanDatabase(); SeedNews(context); context.SaveChanges(); }
public void Add(T entity) { _ctx.Set <T>().Add(entity); /* * without class => where T : class,new() * _ctx.Set(entity.GetType()).Add(entity); */ _ctx.SaveChanges(); }
public void Save(News news, decimal total) { var t = _db.News.Find(news.Id); if (t != null) { t.TotalRating = total; } _db.SaveChanges(); }
private static void SeedNews(NewsContext context) { context.News.Add(new News() { Title = "Seed", Content = "Seed", PublishDate = DateTime.Now }); context.SaveChanges(); }
public ActionResult Create(FormCollection form) { NewsItem news = new NewsItem(); UpdateModel(news); NewsContext context = new NewsContext(); context.News.Add(news); context.SaveChanges(); return(RedirectToAction("Index")); }
static void Main() { using (var context = new NewsContext()) { context.News.RemoveRange(); context.SaveChanges(); } var listener = new Listener(); listener.Register(); }
private static void CleanDatabase() { // Clean all data in all database tables var dbContext = new NewsContext(); dbContext.News.Delete(); // ... // dbContext.AnotherEntity.Delete(); // ... dbContext.SaveChanges(); }
public FavoriteControllerTest() { var options = new DbContextOptionsBuilder <NewsContext>() .UseInMemoryDatabase(databaseName: "InMemoryNewsDB") .Options; _context = new NewsContext(options); _context.NewsItems.Add(new News { NewsTitle = "Item1" }); _context.SaveChanges(); }
public void ExampleTest() { DbContextOptions <NewsContext> options = new DbContextOptionsBuilder <NewsContext>() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) .Options; Guid newsId = Guid.NewGuid(); Guid authorId = Guid.NewGuid(); using (NewsContext context = new NewsContext(options)) { context.Employees.Add(new Context.Model.Employee() { Id = authorId, FullName = null }); context.News.Add(new Context.Model.News() { Id = newsId, Article = null, AuthorId = authorId, Preamble = null, Title = null }); context.SaveChanges(); } using (NewsContext context = new NewsContext(options)) { CurrentUser currentUserInjection = new CurrentUser(authorId); var result = new Controllers.NewsController(context, currentUserInjection).Get(); var okObjectResult = result as ActionResult <List <News> >; var resultObject = okObjectResult.Value as List <Context.Model.News>; Assert.Single(resultObject); Context.Model.News newsObject = resultObject.First(); Assert.Equal(newsId, newsObject.Id); Assert.Equal(authorId, newsObject.AuthorId); Assert.Equal(authorId, newsObject.Author.Id); Assert.Null(newsObject.Article); Assert.Null(newsObject.Preamble); Assert.Null(newsObject.Title); Assert.Null(newsObject.Author.FullName); } }
public ActionResult Index(Novelty news) { news.Date = DateTime.Now; // add news in db db.News.Add(news); // save all changes in db db.SaveChanges(); var view_news = db.News.ToList(); view_news.Reverse(); ViewBag.News = view_news; return(View()); }
//======================== CREATE public bool CreatePost(NewsViewModel news) { var nameOfImage = Path.GetFileNameWithoutExtension(news.FormFile.FileName); var extensionOfImage = Path.GetExtension(news.FormFile.FileName); var guid = Guid.NewGuid(); var newFileName = nameOfImage + guid + extensionOfImage; var rootPath = Path.Combine(_webHost.WebRootPath, "images", "PostsGallery", newFileName); using (var fileStream = new FileStream(rootPath, FileMode.Create)) { news.FormFile.CopyTo(fileStream); } var newPost = new News() { PostDate = DateTime.Now.ToString("MMMM dd"), PostTime = DateTime.Now.ToString("HH:mm"), LikeAmount = 0, DislikeAmount = 0, VisitedAmount = 0, Title = news.Title, FileName = newFileName }; _context.News.Add(newPost); var result = _context.SaveChanges(); if (result > 0) { return(true); } else { return(false); } }
public ActionResult Create([Bind(Include = "NewsArticleId,Header,IsFeatured, NewsEditor")] NewsArticle newsArticle) { newsArticle.Content = newsArticle.NewsEditor; if (ModelState.IsValid) { db.NewsArticles.Add(newsArticle); db.SaveChanges(); return(RedirectToAction("Index")); } var newsEditorModel = new NewsEditorModel { Editor = new Editor(System.Web.HttpContext.Current, "NewsEditor"), SelectedArticle = newsArticle }; newsEditorModel.Editor.LoadFormData(newsArticle.Content); newsEditorModel.Editor.MvcInit(); return(View(newsEditorModel)); }
protected override void Seed(NewsContext context) { var defaultRssSources = new List <NewsRssSource> { NewsRssSource.Create("Nasdaq: Business News", "http://articlefeeds.nasdaq.com/nasdaq/categories?category=Business", true), NewsRssSource.Create("Nasdaq: Forex and currencies", "http://articlefeeds.nasdaq.com/nasdaq/categories?category=Forex+and+Currencies", true), NewsRssSource.Create("DailyFX: Forex market news and analysis", "https://rss.dailyfx.com/feeds/all", true) }; context.Set <NewsRssSource>().AddOrUpdate(x => x.Url, defaultRssSources.ToArray()); context.SaveChanges(); }
public static void SeedTheAuthors() { var author1 = new Author("Godzilla Hårddisksson"); var author2 = new Author("Tord Yvel"); var author3 = new Author("Billy Texas"); using (var context = new NewsContext()) { context.AddRange(author1, author2, author3); context.SaveChanges(); } }
static void ConcurrencyTest(NewsContext contextOne, NewsContext contextTwo) { var originalNews = contextTwo.News.Find(1); var contextOneNews = contextOne.News.Find(1); Console.WriteLine("Application started.\nText from DB: {0}\nEnter the corrected text:", contextOneNews.Content); string firstUserInput = Console.ReadLine(); Console.WriteLine("User input: {0}", firstUserInput); contextOneNews.Content = firstUserInput; contextOne.SaveChanges(); Console.WriteLine("Changes successfully saved in the DB."); var contextTwoNews = contextTwo.News.Find(1); Console.WriteLine("Application started.\nText from DB: {0}\nEnter the corrected text:", originalNews.Content); string secondUserInput = Console.ReadLine(); contextTwoNews.Content = secondUserInput; try { contextTwo.SaveChanges(); Console.WriteLine("Changes successfully saved in the DB."); } catch (DbUpdateConcurrencyException) { Console.WriteLine("Conflict! Text from DB: {0}. Enter the corrected text:", contextOneNews.Content); string secondUserSecondTry = Console.ReadLine(); var newContextTwo = new NewsContext(); var newContextTwoNews = newContextTwo.News.Find(1); newContextTwoNews.Content = secondUserSecondTry; newContextTwo.SaveChanges(); Console.WriteLine("Changes successfully saved in the DB."); } }
public void Post_ShouldReturn201CreatedPlusTheNewlyCreatedItemOnCorrectData() { var context = new NewsContext(); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "New news"), new KeyValuePair<string, string>("content", "The news is new") }); var response = httpClient.PostAsync("api/news", content).Result; var news = response.Content.ReadAsAsync<NewsModel>().Result; Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); Assert.AreEqual("New news", news.Title); Assert.AreEqual("The news is new", news.Content); Assert.AreEqual(4, context.News.Count()); context.News.Attach(news); context.News.Remove(news); context.SaveChanges(); }
public void Put_ShouldReturn200OKOnCorrectData() { var context = new NewsContext(); var updateNews = new NewsModel() { Title = "Update news title", Content = "Update news content", PublishDate = DateTime.Now }; var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "Update news"), new KeyValuePair<string, string>("content", "Update news"), new KeyValuePair<string, string>("publishDate", "09/06/2015") }); context.News.Add(updateNews); context.SaveChanges(); var response = httpClient.PutAsync(string.Format("api/news/{0}", updateNews.Id), content).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); context.News.Remove(updateNews); context.SaveChanges(); }
private static void CleanDatabase() { // Clean all data in all database tables var dbContext = new NewsContext(); dbContext.News.Delete(); dbContext.Users.Delete(); dbContext.SaveChanges(); }
public void Delete_ShouldReturn200OKOnExistingItem() { var context = new NewsContext(); var newNews = new NewsModel() { Title = "Delete news", Content = "Delete news", PublishDate = DateTime.Now }; context.News.Add(newNews); context.SaveChanges(); var response = httpClient.DeleteAsync(string.Format("api/news/{0}", newNews.Id)).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); }
private void CleanDatabase() { using (var dbContext = new NewsContext()) { dbContext.News.Delete(); dbContext.Users.Delete(); dbContext.SaveChanges(); } this.repo = new NewsData(NewsContext.Create()); var user = new ApplicationUser { UserName = "******", Email = "*****@*****.**" }; this.repo.Users.Add(user); var news = new List<News> { new News { Title = "Seeding repositories", Content = "Some content.", PublishDate = DateTime.Parse("2000-01-20") }, new News { Title = "Web and cloud exam", Content = "There won't be any prepared unit tests.", PublishDate = DateTime.Parse("2015-09-12") } }; user.News.Add(news[0]); user.News.Add(news[1]); this.repo.Users.Add(user); this.repo.SaveChanges(); }