/// <summary> /// Gets an blog post /// </summary> /// <param name="BlogPostID">Blog post identifier</param> /// <returns>Blog post</returns> public static BlogPost GetBlogPostByID(int BlogPostID) { if (BlogPostID == 0) { return(null); } string key = string.Format(BLOGPOST_BY_ID_KEY, BlogPostID); object obj2 = NopCache.Get(key); if (BlogManager.CacheEnabled && (obj2 != null)) { return((BlogPost)obj2); } DBBlogPost dbItem = DBProviderManager <DBBlogProvider> .Provider.GetBlogPostByID(BlogPostID); BlogPost blogPost = DBMapping(dbItem); if (BlogManager.CacheEnabled) { NopCache.Max(key, blogPost); } return(blogPost); }
public ActionResult <BlogId> Create(BlogPost post) { DBBlogPost dbpost = DBToAPIModelTransforms.APItoDBBlogPost(post); DBBlogPost creation = database.createBlogPost(dbpost); BlogId newid = new BlogId(creation.Id, "/blogs/" + creation.Id); return(newid); }
public DBBlogPost createBlogPost(DBBlogPost bp) { // Uses a Blog Ids table to generate unique ids for blog entries. var res = bpc.BlogIds.Add(new DBBlogId()); bpc.SaveChanges(); bp.Version = 0; bp.Id = res.CurrentValues.GetValue <int>("Id"); bpc.SaveChanges(); return(bp); }
private DBBlogPost GetBlogPostFromReader(IDataReader dataReader) { DBBlogPost blogPost = new DBBlogPost(); blogPost.BlogPostID = NopSqlDataHelper.GetInt(dataReader, "BlogPostID"); blogPost.LanguageID = NopSqlDataHelper.GetInt(dataReader, "LanguageID"); blogPost.BlogPostTitle = NopSqlDataHelper.GetString(dataReader, "BlogPostTitle"); blogPost.BlogPostBody = NopSqlDataHelper.GetString(dataReader, "BlogPostBody"); blogPost.BlogPostAllowComments = NopSqlDataHelper.GetBoolean(dataReader, "BlogPostAllowComments"); blogPost.CreatedByID = NopSqlDataHelper.GetInt(dataReader, "CreatedByID"); blogPost.CreatedOn = NopSqlDataHelper.GetUtcDateTime(dataReader, "CreatedOn"); return blogPost; }
public static DBBlogPost APItoDBBlogPost(BlogPost bp) { DBBlogPost dbbp = new DBBlogPost { Version = bp.Version, Title = bp.Title, Date = bp.Date, File = bp.File, Status = bp.Status }; return(dbbp); }
public DBBlogPost updateBlogPost(DBBlogPost bp) { var maxver = from blog in bpc.BlogPost where blog.Id == bp.Id group blog by blog.Id into g select new { version = g.Max(x => x.Version) }; if (maxver.First().version == bp.Version) { bp.Version += 1; bpc.BlogPost.Update(bp); //.Add(bp); bpc.SaveChanges(); return(bp); } throw new Exception("aaarggh!"); }
private static BlogPost DBMapping(DBBlogPost dbItem) { if (dbItem == null) return null; BlogPost item = new BlogPost(); item.BlogPostID = dbItem.BlogPostID; item.LanguageID = dbItem.LanguageID; item.BlogPostTitle = dbItem.BlogPostTitle; item.BlogPostBody = dbItem.BlogPostBody; item.BlogPostAllowComments = dbItem.BlogPostAllowComments; item.CreatedByID = dbItem.CreatedByID; item.CreatedOn = dbItem.CreatedOn; return item; }
public void testUpdate() { var ctx = newContext(); var wrapper = new BlogPostCtxWrapper(ctx); var oldblog = wrapper.getBlogPost(1); // copied because oldblog is written over by the update function, unfortunately. var updblog = new DBBlogPost() { Id = oldblog.Id, Title = "Flimsey Fool", Date = DateTime.Now, File = oldblog.File, Status = oldblog.Status, Version = oldblog.Version }; wrapper.updateBlogPost(updblog); var newblog = wrapper.getBlogPost(1); Assert.Equal(oldblog.Id, newblog.Id); Assert.NotEqual(oldblog.Version, newblog.Version); }
/// <summary> /// Updates the blog post /// </summary> /// <param name="LanguageID">The language identifier</param> /// <param name="BlogPostID">Blog post identifier</param> /// <param name="BlogPostTitle">The blog post title</param> /// <param name="BlogPostBody">The blog post title</param> /// <param name="BlogPostAllowComments">A value indicating whether the blog post comments are allowed</param> /// <param name="CreatedByID">The user identifier who created the blog post</param> /// <param name="CreatedOn">The date and time of instance creation</param> /// <returns>Blog post</returns> public static BlogPost UpdateBlogPost(int BlogPostID, int LanguageID, string BlogPostTitle, string BlogPostBody, bool BlogPostAllowComments, int CreatedByID, DateTime CreatedOn) { CreatedOn = DateTimeHelper.ConvertToUtcTime(CreatedOn); DBBlogPost dbItem = DBProviderManager <DBBlogProvider> .Provider.UpdateBlogPost(BlogPostID, LanguageID, BlogPostTitle, BlogPostBody, BlogPostAllowComments, CreatedByID, CreatedOn); BlogPost blogPost = DBMapping(dbItem); if (BlogManager.CacheEnabled) { NopCache.RemoveByPattern(BLOGPOST_PATTERN_KEY); } return(blogPost); }
private static BlogPost DBMapping(DBBlogPost dbItem) { if (dbItem == null) { return(null); } var item = new BlogPost(); item.BlogPostId = dbItem.BlogPostId; item.LanguageId = dbItem.LanguageId; item.BlogPostTitle = dbItem.BlogPostTitle; item.BlogPostBody = dbItem.BlogPostBody; item.BlogPostAllowComments = dbItem.BlogPostAllowComments; item.CreatedById = dbItem.CreatedById; item.CreatedOn = dbItem.CreatedOn; return(item); }
/// <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() + "\"") : "") + "}" });
public static BlogPost DBtoAPIBlogPost(DBBlogPost bp) { return(new BlogPost(bp.Version, bp.Title, bp.Date, bp.File, bp.Status)); }
/// <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> Get(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogLine("Get Request\n"); APIGatewayProxyResponse response; 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" } , { "Access-Control-Allow-Origin", "*" } } }; } else { bool statusClause = false; bool statusStr = false; bool versionClause = false; int selectVersion = 0; if (!(request.QueryStringParameters is null)) { if (request.QueryStringParameters.ContainsKey("status")) { if (!Boolean.TryParse(request.QueryStringParameters["status"], out statusStr)) { return new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = "{ \"error\":\"Bad status parameter\"}" } } ; statusClause = true; context.Logger.LogLine("Selection with status = " + statusStr); } if (request.QueryStringParameters.ContainsKey("version")) { if (!Int32.TryParse(request.QueryStringParameters["version"], out selectVersion)) { return new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = "Poor choice of version." } } ; versionClause = true; context.Logger.LogLine("Selecting version " + selectVersion); } } if (statusClause && versionClause) { return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.BadRequest, Body = "Can't have both status and version clause when choosing." }); } DBBlogPost latest = null; if (statusClause) { var versions = from blog in bpc.BlogPost where (blog.User == user) && (blog.Id == id) && (blog.Status == statusStr) orderby blog.Version descending select blog; if (versions.Count() != 0) { latest = versions.First(); } } else { if (versionClause) { var versions = from blog in bpc.BlogPost where (blog.Id == id) && (blog.Version == selectVersion) select blog; if (versions.Count() != 0) { latest = versions.First(); } } else { var versions = from blog in bpc.BlogPost where (blog.User == user) && (blog.Id == id) orderby blog.Version descending select blog; if (versions.Count() != 0) { latest = versions.First(); } } } if (latest is null) { response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.NotFound, Body = "", Headers = new Dictionary <string, string> { { "Access-Control-Allow-Origin", "*" } } }; } else { // Fetch file from S3 AmazonS3Client s3client = new AmazonS3Client(Amazon.RegionEndpoint.EUWest2); var resp = await s3client.GetObjectAsync(new GetObjectRequest { BucketName = secrets["blogstore"], Key = latest.File }); var outstream = new StreamReader(resp.ResponseStream); var text = outstream.ReadToEnd(); // Create model var model = new BlogPostModel(latest.Version, latest.Title, latest.Date, text, latest.Status, latest.Hash); foreach (var(k, v) in request.Headers) { Console.WriteLine($"Header {k} with value {v}"); } // Return response response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = JsonSerializer.Serialize <BlogPostModel>(model), Headers = new Dictionary <string, string> { { "Content-Type", "application/json" } , { "Access-Control-Allow-Origin", "*" } } }; } } return(response); } } }
/// <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); }