public ActionResult Create([Bind(Include = "Id,Name,BlogPostId")] Tag tag) { if (ModelState.IsValid) { db.Tags.Add(tag); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.BlogPostId = new SelectList(db.BlogPosts, "Id", "Title", tag.BlogPostId); return(View(tag)); }
public ActionResult Create([Bind(Include = "Id,Title,CreatedOn")] BlogPost blogPost) { if (ModelState.IsValid) { db.BlogPosts.Add(blogPost); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(blogPost)); }
public ActionResult Create(BlogPost blogPost) { blogPost.Created = DateTime.Now; db.BlogPosts.Add(blogPost); db.SaveChanges(); return(RedirectToAction("Index")); }
public void DeleteBlogPost(int id) { using (BlogPostContext context = new BlogPostContext(_connectionName, _schemaName)) { Data.Model.BlogPost post = context.BlogPosts.Find(id); context.Entry(post).State = System.Data.EntityState.Deleted; context.SaveChanges(); } }
public void UpdateBlogPost(Domain.Model.BlogPost post) { using (BlogPostContext context = new BlogPostContext(_connectionName, _schemaName)) { context.Entry(new Data.Model.BlogPost { Id = post.Id, Post = post.Post, Title = post.Title }).State = System.Data.EntityState.Modified; context.SaveChanges(); } }
public ActionResult Create(BlogPost blogPost) { using (var db = new BlogPostContext()) { blogPost.Created = DateTime.Now; db.BlogPosts.Add(blogPost); db.SaveChanges(); } return(RedirectToAction("Index")); }
private void SetupDatabase() { Options = new DbContextOptionsBuilder <BlogPostContext>() .UseInMemoryDatabase(databaseName: "StudentContextOptions") .Options; using var dbContext = new BlogPostContext(Options); var itCourse = new Course { Name = "IT Programming" }; var math = new Course { Name = "Math" }; var student1 = new Student { Name = "John Doe", Courses = new List <StudentCourse> { new StudentCourse { Course = itCourse }, new StudentCourse { Course = math } } }; var student2 = new Student { Name = "Martin B", Courses = new List <StudentCourse> { new StudentCourse { Course = itCourse }, new StudentCourse { Course = math } } }; dbContext.Add(student1); dbContext.Add(student2); dbContext.SaveChanges(); allStudents = new List <Student> { student1, student2 }; ExpectedStudents = Mapper.Map <IEnumerable <StudentResponse> >(allStudents); }
public BlogPostsController(BlogPostContext context) { _context = context; if (_context.BlogPostItems.Count() == 0) { _context.BlogPostItems.Add(new BlogPostItem { Title = "Item1" }); _context.SaveChanges(); } }
private static void InitilizeDatabase() { if (!context.Courses.Any()) { context.Courses.Add(new Course { Name = "Random" }); context.Courses.Add(new Course { Name = "New Course" }); context.SaveChanges(); } if (!context.Students.Any()) { context.Students.Add(new Student { Name = "Martin B", CourseId = 1 }); context.Students.Add(new Student { Name = "Witalian", CourseId = 2 }); context.Students.Add(new Student { Name = "SomeRandomStudent", CourseId = 1 }); context.SaveChanges(); } }
public ActionResult Register(RegisterModel model) { var IsExistData = _context.User.ToList().Where(b => b.Email.Trim() == model.Email.Trim()).FirstOrDefault(); if (IsExistData != null) { ModelState.AddModelError(string.Empty, "Email is already exist"); return(View(model)); } if (ModelState.IsValid) { Register register = new Register() { Email = model.Email, Name = model.Name, Password = model.Password }; _context.User.Add(register); _context.SaveChanges(); model.IsregisterSuccess = true; } return(View(model)); }
public BlogController(BlogPostContext context) { _context = context; if (_context.BlogPostItems.Count() == 0) { // Create a new BlogPost if collection is empty, _context.BlogPostItems.Add(new BlogPost { Title = "Wellcome to SimpleBlog Engine", Content = " This is a very basic blog engine with x feature and y feature It has a simple web editor to edit multi-line blog entries. If you have bug reports and suggestion please email to [email protected] " }); _context.SaveChanges(); } }
private static void InsertTestData(BlogPostContext context) { if (context.Authors.Any()) { return; } context.Authors.Add(new Author { Id = Guid.NewGuid(), Name = "Daan" }); context.SaveChanges(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, BlogPostContext context, IApiVersionDescriptionProvider apiVersionDescProvider) { if (!env.IsDevelopment()) { app.UseDeveloperExceptionPage(); context.Database.EnsureCreated(); if (!context.BlogPosts.Any()) { var posts = new List <BlogPost>(); for (int i = 1; i < 6; i++) { posts.Add(createBlogPost("title" + i, "desc" + i)); } context.BlogPosts.AddRange(posts); context.SaveChanges(); } } else { app.UseExceptionHandler("/api/v1/Error"); app.UseHsts(); } app.UseCors("MyPolicy"); app.UseHttpsRedirection(); app.UseMvc(); _logger.LogInformation("Adding Swagger UI"); app.UseSwagger(); app.UseSwaggerUI(c => { foreach (var description in apiVersionDescProvider.ApiVersionDescriptions) { c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } c.RoutePrefix = string.Empty; // serve the Swagger UI at the app's root }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider apiVersionProvider, BlogPostContext context) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/api/Error"); app.UseHsts(); context.Database.EnsureCreated(); if (!context.BlogPosts.Any()) { var posts = new List <BlogPost> { new BlogPost { Id = 1, Title = "RazDwaTrzy", Description = "CzteryPiecSzesc" } }; context.BlogPosts.AddRange(posts); context.SaveChanges(); } } app.UseHttpsRedirection(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(c => { foreach (var description in apiVersionProvider.ApiVersionDescriptions) { c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName); } //c.SwaggerEndpoint("/swagger/v1/swagger.json", "Blog Posts API v1"); c.RoutePrefix = string.Empty; }); }
public async Task <string> DeletePost(string slug) { if (db != null) { Models.BlogPost post = db.BlogPosts.Include(p => p.Tags).Where(p => p.Slug == slug).FirstOrDefault(); if (post != null) { //create BlogPostTag object for delete (relationship with BlogPost table BlogPostTag blogPostTag = new BlogPostTag(); //get BlogPostId from BlogPostTag table, include all Tags blogPostTag = db.BlogPostTag .Include(b => b.BlogPost) .Include(b => b.Tag) .Where(b => b.BlogPostId == post.Id).FirstOrDefault(); if (blogPostTag != null) { db.BlogPostTag.Remove(blogPostTag); db.BlogPosts.Remove(post); db.SaveChanges(); } } } return("Record successfully deleted!"); }
private void SeedDatabase(DbContextOptions <BlogPostContext> options) { using var context = new BlogPostContext(options); var assessments = new[] { new Assessment { WeightType = "Homework", Weight = 0.2f }, new Assessment { WeightType = "Quiz test", Weight = 0.3f }, new Assessment { WeightType = "Work at school", Weight = 0.6f }, new Assessment { WeightType = "Exam", Weight = 1.0f } }; var students = new[] { new Student { Name = "Martin B" }, new Student { Name = "Witalian" }, new Student { Name = " SomeRandom" } }; var courses = new[] { new Course { Name = "Informatic" }, new Course { Name = "Language" }, new Course { Name = "Math" } }; context.Students.AddRange(students); context.Courses.AddRange(courses); context.Assessments.AddRange(assessments); context.StudentCourses.AddRange( new StudentCourse { Student = students[0], Course = courses[0], Assessment = assessments[0], Mark = 4 }, new StudentCourse { Student = students[0], Course = courses[0], Assessment = assessments[1], Mark = 2 }, new StudentCourse { Student = students[0], Course = courses[0], Assessment = assessments[2], Mark = 5 }, new StudentCourse { Student = students[0], Course = courses[0], Assessment = assessments[3], Mark = 4 }, new StudentCourse { Student = students[0], Course = courses[1], Assessment = assessments[3], Mark = 1 }, new StudentCourse { Student = students[0], Course = courses[1], Assessment = assessments[0], Mark = 5 }, new StudentCourse { Student = students[1], Course = courses[0], Assessment = assessments[0], Mark = 3 }, new StudentCourse { Student = students[1], Course = courses[0], Assessment = assessments[1], Mark = 3 }, new StudentCourse { Student = students[1], Course = courses[0], Assessment = assessments[2], Mark = 5 }, new StudentCourse { Student = students[1], Course = courses[0], Assessment = assessments[3], Mark = 4 }, new StudentCourse { Student = students[1], Course = courses[1], Assessment = assessments[1], Mark = 1 }, new StudentCourse { Student = students[1], Course = courses[1], Assessment = assessments[2], Mark = 4 }, new StudentCourse { Student = students[2], Course = courses[2], Assessment = assessments[1], Mark = 5 } ); context.SaveChanges(); ExpectedMissingGrades = GetMissingGrades(assessments, courses, students); }
/// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The API Gateway response.</returns> public async Task <APIGatewayProxyResponse> Update(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogLine("Update Request\n"); APIGatewayProxyResponse response; Console.WriteLine(request); Console.WriteLine("Request body:::" + request.Body); string idStr = request.PathParameters["id"]; string user = request.PathParameters["user"]; int id = 0; if (!Int32.TryParse(idStr, out id)) { response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = "Illegal parameter " + id, Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" } } }; } BlogPostModel bpm = JsonSerializer.Deserialize <BlogPostModel>(request.Body); Console.WriteLine("Deserialized body"); Console.WriteLine($"Updating blog with Id :: {id}"); // create a db model var base64hash = Utilities.CreateBlogPostHash(user, bpm, id); Console.WriteLine("New has will be:::" + base64hash); // do some checking - last hash, new key. var latesthash = (from blog in bpc.BlogPost where (blog.Id == id) orderby blog.Date descending select blog).First <DBBlogPost>().Hash; bool condition = string.Compare(latesthash, bpm.Hash) == 0; // need identical hashes. Console.WriteLine("Comparing " + latesthash + " and " + bpm.Hash); Console.WriteLine($"Condition is now {condition}"); int newVersion = bpm.Version + 1; var newkey = from blog in bpc.BlogPost where (blog.Id == id) && (blog.Version == newVersion) select blog; condition = condition && (newkey.ToList <DBBlogPost>().Count == 0); Console.WriteLine($"Condition after key test is now {condition}"); if (!condition) { return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = "Either duplicate key or the hash is NOT the latest hash!" }); } string fileKey = Utilities.MakeBlogFileName(user, id, newVersion); // save the db model DBBlogPost dbbp = new DBBlogPost(id, newVersion, bpm.Title, DateTime.Now, fileKey, bpm.Status, base64hash, user); try { bpc.BlogPost.Add(dbbp); bpc.SaveChanges(); Console.WriteLine("Written to DB"); } catch (Exception ex) { //bpc = GetConnectionString.GetContext(secrets); return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = "{ \"Exception\": \"" + ex.GetBaseException().ToString() + "\" " + ((!(ex.InnerException is null)) ? ("\"Inner\":\"" + ex.InnerException.ToString() + "\"") : "") + "}" });
/// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The API Gateway response.</returns> public async Task <APIGatewayProxyResponse> Create(APIGatewayProxyRequest request, ILambdaContext context) { string user = request.PathParameters["user"]; context.Logger.LogLine($"USER PARAMETER IS =--= {user}"); // We expect a model that fits BlogPostModel - so a version, but no id. Console.WriteLine("Create Request\n"); APIGatewayProxyResponse response; Console.WriteLine(request); Console.WriteLine("Request body:::" + request.Body); BlogPostModel bpm = JsonSerializer.Deserialize <BlogPostModel>(request.Body); Console.WriteLine("Deserialized body"); Console.WriteLine($"{bpm.Title} {bpm.Date} {bpm.Text} {bpm.Status}"); if (bpm.Version != 0) { response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = $"Version {bpm.Version} Not Zero" }; } else { Console.WriteLine("About to create a new id"); // we create an id. int id = 0; //(new Random()).Next(1000000); var addid = bpc.BlogIds.Add(new DBBlogId("A")); int x = 0; try { x = bpc.SaveChanges(); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.ToString()); if (e.InnerException != null) { Console.WriteLine("==================="); Console.WriteLine(e.InnerException.Message); Console.WriteLine(e.InnerException.ToString()); } } if (x == 0) { Console.WriteLine("No changes made to db - so that's no good!"); return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = "Nope, not having the id db thing again" }); } id = addid.CurrentValues.GetValue <int>("Id"); Console.WriteLine($"New Id created :: {id}"); string fileKey = Utilities.MakeBlogFileName(user, id, bpm.Version); // let's save the body text to our S3 bucket in a file of our choosing AmazonS3Client s3client = new AmazonS3Client(Amazon.RegionEndpoint.EUWest2);//S3Region.EUW2); var resp = await s3client.PutObjectAsync(new Amazon.S3.Model.PutObjectRequest { BucketName = secrets["blogstore"], Key = fileKey, ContentBody = bpm.Text }); Console.WriteLine("Written to S3"); // create a db model // save the db model string base64hash = Utilities.CreateBlogPostHash(user, bpm, id); try { DBBlogPost dbbp = new DBBlogPost(id, bpm.Version, bpm.Title, DateTime.Now, fileKey, bpm.Status, base64hash, user); bpc.BlogPost.Add(dbbp); bpc.SaveChanges(); Console.WriteLine("Written to DB"); } catch (Exception e) { context.Logger.LogLine(e.Message); context.Logger.LogLine(e.ToString()); if (e.InnerException != null) { context.Logger.LogLine("==================="); context.Logger.LogLine(e.InnerException.Message); context.Logger.LogLine(e.InnerException.ToString()); } return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest }); } // create a response containing the new id - perhaps also a URL - maybe just the URL? response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "{ \"URL\": \"/blog/" + $"{id}" + "\" }", Headers = new Dictionary <string, string> { { "Content-Type", "application/json" } , { "Access-Control-Allow-Origin", "*" } } }; } return(response); }
private static void InitilizeDatabase() { if (!context.Courses.Any() && !context.Students.Any()) { var students = new[] { new Student { Name = "Martin B" }, new Student { Name = "Witalian" }, new Student { Name = " SomeRandom" } }; var courses = new[] { new Course { Name = "Informatic" }, new Course { Name = "Language" }, new Course { Name = "Math" } }; context.StudentCourses.AddRange( new StudentCourse { Student = students[0], Course = courses[0], AssessmentId = 1, Mark = 4 }, new StudentCourse { Student = students[0], Course = courses[0], AssessmentId = 2, Mark = 2 }, new StudentCourse { Student = students[0], Course = courses[0], AssessmentId = 3, Mark = 5 }, new StudentCourse { Student = students[0], Course = courses[0], AssessmentId = 4, Mark = 4 }, new StudentCourse { Student = students[0], Course = courses[1], AssessmentId = 4, Mark = 1 }, new StudentCourse { Student = students[0], Course = courses[1], AssessmentId = 1, Mark = 5 }, new StudentCourse { Student = students[1], Course = courses[0], AssessmentId = 1, Mark = 3 }, new StudentCourse { Student = students[1], Course = courses[0], AssessmentId = 2, Mark = 3 }, new StudentCourse { Student = students[1], Course = courses[0], AssessmentId = 3, Mark = 5 }, new StudentCourse { Student = students[1], Course = courses[0], AssessmentId = 4, Mark = 4 }, new StudentCourse { Student = students[1], Course = courses[1], AssessmentId = 2, Mark = 1 }, new StudentCourse { Student = students[1], Course = courses[1], AssessmentId = 3, Mark = 4 }, new StudentCourse { Student = students[2], Course = courses[2], AssessmentId = 2, Mark = 5 } ); context.SaveChanges(); } }