Inheritance: Data
Exemplo n.º 1
0
 public void Populate(Post post, DirectoryInfo directory)
 {
     var fileInfos = directory.GetFiles("meta.txt");
     var reader = new StreamReader(fileInfos.First().OpenRead());
     post.Tags = GetTags(reader.ReadLine());
     post.Timestamp = GetTime(reader.ReadLine());
 }
Exemplo n.º 2
0
        /// <summary>
        ///     Gets Post objects out of XML files, which follow the BlogEngine.NET format.
        /// </summary>
        /// <param name = "folderSystemPath">Folder where XML files are located</param>
        /// <returns>zasz.me.Models.Post objects</returns>
        public IEnumerable<Post> GetFromFolder(string folderSystemPath)
        {
            if (String.IsNullOrEmpty(folderSystemPath))
                die("Null Path");

            Debug.Assert(folderSystemPath != null, "folderSystemPath != null");
            var files = Directory.GetFiles(folderSystemPath);
            var xmlFiles = (from file in files
                           where file.EndsWith(".xml")
                           select file).ToList();

            if (!xmlFiles.Any())
                die("No XML Files found");
            // ReSharper disable PossibleNullReferenceException
            foreach (var postFile in xmlFiles)
            {
                log("Working on file : " + postFile);
                var newPost = new Post();
                var postDoc = new XmlDocument();
                postDoc.Load(postFile);
                newPost.Title = postDoc.SelectSingleNode("post/title").InnerText;
                log("Title : " + newPost.Title);
                newPost.Content = HttpUtility.HtmlDecode(postDoc.SelectSingleNode("post/content").InnerText);
                newPost.Timestamp = DateTime.Parse(postDoc.SelectSingleNode("post/pubDate").InnerText);
                newPost.Slug = postDoc.SelectSingleNode("post/slug").InnerText;
                newPost.Tags = new List<Tag>();
                postDoc.SelectNodes("post/tags/tag")
                    .Cast<XmlNode>()
                    .Where(node => !string.IsNullOrEmpty(node.InnerText))
                    .ForEach( x => newPost.Tags.Add(new Tag(x.InnerText)));
                yield return newPost;
            }
            // ReSharper restore PossibleNullReferenceException
        }
Exemplo n.º 3
0
 public static void Delete(Post post)
 {
     var posts = GetAllPosts();
     string file = Path.Combine(_folder, post.ID + ".xml");
     File.Delete(file);
     posts.Remove(post);
 }
Exemplo n.º 4
0
        public void DeleteAPost(int postID)
        {

            NewsfeedDAL newsfeedDAL = new NewsfeedDAL();
            Post aPost = new Post(postID);
            newsfeedDAL.FlagPost(aPost);
        }
Exemplo n.º 5
0
        public string AddComment(int postID, string commentTxt)
        {
            Comments comment = new Comments();
            comment.MemberId = Context.Session["memberID"].ToString();
            comment.CommentText = commentTxt;
            comment.PostId = postID;
            messageDAL.InsertComment(comment);

            //Insert notification
            NotificationDAL notificationDAL = new NotificationDAL();

            Post aPost = new Post(postID);

            List<Member> MemberList = new List<Member>();
            MemberList = notificationDAL.GetPostOwner(aPost);
            string friendId = MemberList[0].MemberId;
            Member aFriend = new Member(friendId);

            Member aMember = new Member(Context.Session["memberID"].ToString());

            if (aMember.MemberId != aFriend.MemberId)
            {
                notificationDAL.InsertCommentedOnPostNotification(aMember, aFriend, aPost);
            }
            //Refreshing the Comment count
            Post post = new Post();
            post.PostId = comment.PostId;

            return messageDAL.CountComments(post).ToString();
        }
Exemplo n.º 6
0
 public static bool Matches(this PostViewModel candidate, Post actual)
 {
     if (candidate.Author != actual.Author) return false;
     if (candidate.Content != actual.Content) return false;
     if (candidate.PublishDate != actual.PublishDate) return false;
     return candidate.Title == actual.Title;
 }
Exemplo n.º 7
0
 public static void ShouldMatch(this PostViewModel candidate, Post actual)
 {
     candidate.Author.ShouldEqual(actual.Author);
     candidate.Content.ShouldEqual(actual.Content);
     candidate.PublishDate.ShouldEqual(actual.PublishDate);
     candidate.Title.ShouldEqual(actual.Title);
 }
        protected override void Given()
        {
            stashedPost = new Post
                {
                    Title = "My Super Blog",
                    PostedAt = new DateTime(2010, 03, 19, 13, 33, 34),
                    Text = "This is my super blog. Check out my awesome post",
                    Comments = new List<Comment>
                        {
                            new Comment
                                {
                                    Author = "Andy Hitchman",
                                    AuthorsEmail = "*****@*****.**",
                                    CommentedAt = new DateTime(2010, 03, 19, 13, 36, 01),
                                    Text = "This blog is teh suck"
                                }
                        }
                };

            var internalId = new InternalId(Guid.NewGuid());
            var registeredGraph = Kernel.Registry.GetRegistrationFor<Post>();
            var serializedGraph = registeredGraph.Serialize(stashedPost, null);
            var projectedIndexes = registeredGraph.IndexersOnGraph.SelectMany(_ => _.GetUntypedProjections(stashedPost));
            var tracked = new TrackedGraph(new StoredGraph(internalId, registeredGraph.GraphType, serializedGraph), projectedIndexes, registeredGraph);

            Kernel.Registry.BackingStore.InTransactionDo(_ => _.InsertGraph(tracked));
        }
Exemplo n.º 9
0
        public ActionResult Create(FormCollection formCollection)
        {
            string title = formCollection.Get("Title");
            string body = formCollection.Get("Body");
            bool isPublic = formCollection.Get("IsPublic").Contains("true");

            IRepository<Category> categoriesRepo = new CategoryRepository();
            IRepository<Post> postsRepo = new PostRepository();
            List<Category> allCategories = (List<Category>)categoriesRepo.GetAll();

            Post post = new Post();
            post.Body = body;
            post.Title = title;
            post.CreationDate = DateTime.Now;
            post.IsPublic = isPublic;

            foreach (Category category in allCategories)
            {
                if (formCollection.Get(category.Id.ToString()).Contains("true"))
                    post.Categories.Add(category);

            }

            postsRepo.Save(post);


            return RedirectToAction("Index");
        }
Exemplo n.º 10
0
    private static void Save(HttpContext context, Post post)
    {
        string name = context.Request.Form["name"];
        string email = context.Request.Form["email"];
        string website = context.Request.Form["website"];
        string content = context.Request.Form["content"];

        Validate(name, email, content);

        Comment comment = new Comment()
        {
            Author = name.Trim(),
            Email = email.Trim(),
            Website = GetUrl(website),
            Ip = context.Request.UserHostAddress,
            UserAgent = context.Request.UserAgent,
            IsAdmin = context.User.Identity.IsAuthenticated,
            Content = HttpUtility.HtmlEncode(content.Trim()).Replace("\n", "<br />"),
        };

        post.Comments.Add(comment);
        post.Save();

        string wrapper = VirtualPathUtility.ToAbsolute("~/views/commentwrapper.cshtml") + "?postid=" + post.ID + "&commentid=" + comment.ID;
        context.Response.Write(wrapper);
    }
Exemplo n.º 11
0
 public void get_column_value()
 {
     var post = new Post() {Title = "title12"};
     var id = _db.Insert(post).InsertedId<int>();
     Assert.Equal("title12",_db.GetColumnValue<Post,string>(p=>p.Title,p => p.Id == id));
     Assert.Null(_db.GetColumnValue<Post, string>(p => p.Title, p => p.Id == 2890));
 }
Exemplo n.º 12
0
 protected static Post SavePost(Post post)
 {
     string conn = ConfigurationManager.AppSettings["mongolab"];
     PostData postData = new PostData(conn);
     postData.SavePost(post);
     return post;
 }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            Client client = new Client("2", "a18632aa82be8e925ef349164314311a", "http://hook.dev/public/index.php/");
            Collection posts = client.Collection ("posts");

            var post = new Post ();
            post.title = "Hello there!";
            post.score = 15;
            post.date = new DateTime (2014, 07, 07, 17, 30, 0);

            posts.Create (post).ContinueWith<Post> (result => {
                Console.WriteLine(result.ToString());
            });

            posts.Get ().ContinueWith<Post[]> (result => {
                Console.WriteLine(result.ToString());
            });

            req = posts.Sort ("created_at", Order.DESCENDING).Limit(1).First().ContinueWith<Post> (data => {
                Console.WriteLine("Post id: ");
                Console.WriteLine(data._id);
            });

            NSApplication.Init ();
            NSApplication.Main (args);
        }
Exemplo n.º 14
0
 public ActionResult FindByLatLong(Post post)
 {
     PostServiceClient service = new PostServiceClient();
     //Davi ira fazer o metodo
     service.findAllByLatitudeAndLongitude(post);
     return View();
 }
Exemplo n.º 15
0
 //
 public ActionResult FindByLegend(Post post)
 {
     PostServiceClient service = new PostServiceClient();
     //Davi ira fazer o metodo
     //service.findByLegend(post);
     return PartialView("_FindPost");
 }
Exemplo n.º 16
0
 public void InsertPost(Post post)
 {
     using(Connection = new SQLiteConnection(this.DbPath))
     {
         this.Connection.Insert(post);
     }
 }
Exemplo n.º 17
0
        public ActionResult FindById(Post post)
        {
            PostServiceClient service = new PostServiceClient();

            service.find(post);
            return View();
        }
Exemplo n.º 18
0
        public void FetchEnum_Join_on_a_HasMany_property_should_not_return_duplicate_records()
        {
            Blog[] blogs = Blog.FindAll();

            Assert.IsNotNull(blogs);
            Assert.AreEqual(0, blogs.Length);

            var blog = new Blog() { Name = "Test blog", Author = "Eric Bowen" };

            blog.Save();

            var post = new Post(blog, "Post1", "Content1", "Category1");
            post.Save();

            blog.Posts.Add(post);

            var post2 = new Post(blog, "Post2", "Content2", "Category2");
            post2.Save();

            blog.Posts.Add(post2);

            blog.Save();

            blogs = Blog.FindAll();

            Assert.IsNotNull(blogs);
            Assert.AreEqual(1, blogs.Length);
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            var post = new Post() 
            { 
                SourceCode = "Console.WriteLine(\"Hello C#\");",
                AuthorMail = "*****@*****.**", 
                Rating = 0,
                Category = "C#"
            };

            // Add post to database
            AddPost(post);

            // Get all posts
            var responseStr = Client.GetStringAsync("api/posts").Result;
            var posts = JsonConvert.DeserializeObject<IEnumerable<Post>>(responseStr);

            // If we have posts in db get one one update its rating
            if (posts != null)
            {
                // If vote = true this mean +1
                UpdateVode(posts.FirstOrDefault(), true);
            }

            // Print all posts
            PrintAllPosts();
        }
        public List<Post> GetPostByUserId(int Id)
        {
            List<Post> lstPosts = new List<Post>();
            using (DatabaseLayer dbLayer = new DatabaseLayer())
            {
                SqlCommand cmd = new SqlCommand("GetPostByUserId");
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@id", Id);

                DataSet postDataset = dbLayer.FillDataSet(cmd);

                if (postDataset != null && postDataset.Tables.Count > 0)
                {
                    foreach (DataRow row in postDataset.Tables[0].Rows)
                    {
                        Post post = new Post();
                        post.Id = Convert.ToInt32(row["Id"].ToString());
                        post.Message = row["Message"].ToString();
                        post.CreatedOn = Convert.ToDateTime(row["CreatedOn"].ToString());
                        post.CreatedByString = row["CreatedByString"].ToString();
                        post.CreatedBy = Convert.ToInt32(row["CreatedBy"].ToString());
                        lstPosts.Add(post);
                    }
                }
            }

            return lstPosts;
        }
        public void AddPost()
        {
            IList<Post> posts = new List<Post>();
            Person creator = _personRepository.GetById(1);

            for (int i = 0; i < 10; i++)
            {
                Post person = new Post
                {
                    Creator = creator,
                    Content = "blah" + i,
                    CreatedDateTime = DateTime.Now
                };
                posts.Add(person);
            }

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            _repository.UnitOfWork.BeginTransaction();
            _repository.Add(posts);
            _repository.UnitOfWork.CommitTransaction();
            stopwatch.Stop();

            Console.WriteLine("Time Elapsed: " + stopwatch.Elapsed);
        }
Exemplo n.º 22
0
	private void SaveFilesToDisk(Post post)
	{
		foreach (Match match in Regex.Matches(post.Content, "(src|href)=\"(data:([^\"]+))\"(>.*?</a>)?"))
		{
			string extension = string.Empty;
			string filename = string.Empty;

			// Image
			if (match.Groups[1].Value == "src")
			{
				extension = Regex.Match(match.Value, "data:([^/]+)/([a-z]+);base64").Groups[2].Value;
			}
			// Other file type
			else
			{
				// Entire filename
				extension = Regex.Match(match.Value, "data:([^/]+)/([a-z0-9+-.]+);base64.*\">(.*)</a>").Groups[3].Value;
			}

			byte[] bytes = ConvertToBytes(match.Groups[2].Value);
			string path = Blog.SaveFileToDisk(bytes, extension);

			string value = string.Format("src=\"{0}\" alt=\"\" ", path);

			if (match.Groups[1].Value == "href")
				value = string.Format("href=\"{0}\"", path);

			Match m = Regex.Match(match.Value, "(src|href)=\"(data:([^\"]+))\"");
			post.Content = post.Content.Replace(m.Value, value);
		}
	}
Exemplo n.º 23
0
 public ActionResult Database()
 {
     posts.DeleteAll();
     var folders = Directory.GetDirectories(Server.MapPath("~" + Constants.PostsFolder));
     var messagesAndErrors = new List<Pair<string, bool>>();
     foreach (var folder in folders)
     {
         var entry = new Post();
         var dir = new DirectoryInfo(folder);
         var postMessagesAndErrors = populators.Select(x =>
                                              {
                                                  try
                                                  {
                                                      x.Populate(entry, dir);
                                                      return new Pair<string, bool>(string.Format("{0} | {1} is OK.", entry.Slug, x.GetType().Name), true);
                                                  }
                                                  catch (Exception e)
                                                  {
                                                      return new Pair<string, bool>(string.Format("{0} | {1} | {2}", entry.Slug, e.GetType(), e.Message), false);
                                                  }
                                              }).ToList();
         messagesAndErrors.AddRange(postMessagesAndErrors);
         if (postMessagesAndErrors.All(x => x.Other)) posts.Save(entry);
         posts.Commit();
     }
     return View(messagesAndErrors);
 }
        private void setup_sample_post(User user)
        {
            var oxiteTag = new Tag {Name = "Oxite", CreatedDate = DateTime.Parse("12 NOV 2008")};

            var defaultPost = new Post
            {
                Title = "World.Hello()",
                Slug = "World_Hello",
                BodyShort = "Welcome to Oxite! &nbsp;This is a sample application targeting developers built on <a href=\"http://asp.net/mvc\">ASP.NET MVC</a>. &nbsp;Make any changes you like. &nbsp;If you build a feature you think other developers would be interested in and would like to share your code go to the <a href=\"http://www.codeplex.com/oxite\">Oxite Code Plex project</a> to see how you can contribute.<br /><br />To get started, sign in with \"Admin\" and \"pa$$w0rd\" and click on the Admin tab.<br /><br />For more information about <a href=\"http://oxite.net\">Oxite</a> visit the default <a href=\"/About\">About</a> page.",
                Body = "Welcome to Oxite! &nbsp;This is a sample application targeting developers built on <a href=\"http://asp.net/mvc\">ASP.NET MVC</a>. &nbsp;Make any changes you like. &nbsp;If you build a feature you think other developers would be interested in and would like to share your code go to the <a href=\"http://www.codeplex.com/oxite\">Oxite Code Plex project</a> to see how you can contribute.<br /><br />To get started, sign in with \"Admin\" and \"pa$$w0rd\" and click on the Admin tab.<br /><br />For more information about <a href=\"http://oxite.net\">Oxite</a> visit the default <a href=\"/About\">About</a> page.",
                Published = DateTime.Parse("2008-12-05 09:29:03.270"),
                User = user
            };
            defaultPost.AddTag(oxiteTag);

            _repository.Save(defaultPost);

            var defaultPost1 = new Post
            {
                Title = "World.Hello()",
                Slug = "World_Hello2",
                BodyShort = "Welcome to Oxite! &nbsp;This is a sample application targeting developers built on <a href=\"http://asp.net/mvc\">ASP.NET MVC</a>. &nbsp;Make any changes you like. &nbsp;If you build a feature you think other developers would be interested in and would like to share your code go to the <a href=\"http://www.codeplex.com/oxite\">Oxite Code Plex project</a> to see how you can contribute.<br /><br />To get started, sign in with \"Admin\" and \"pa$$w0rd\" and click on the Admin tab.<br /><br />For more information about <a href=\"http://oxite.net\">Oxite</a> visit the default <a href=\"/About\">About</a> page.",
                Body = "Welcome to Oxite! &nbsp;This is a sample application targeting developers built on <a href=\"http://asp.net/mvc\">ASP.NET MVC</a>. &nbsp;Make any changes you like. &nbsp;If you build a feature you think other developers would be interested in and would like to share your code go to the <a href=\"http://www.codeplex.com/oxite\">Oxite Code Plex project</a> to see how you can contribute.<br /><br />To get started, sign in with \"Admin\" and \"pa$$w0rd\" and click on the Admin tab.<br /><br />For more information about <a href=\"http://oxite.net\">Oxite</a> visit the default <a href=\"/About\">About</a> page.",
                Published = DateTime.Parse("2008-12-05 09:29:03.270"),
                User = user
            };
            defaultPost1.AddTag(oxiteTag);
            defaultPost1.AddTag(new Tag { Name = "AltOxite", CreatedDate = DateTime.Parse("30 DEC 2008") });
            defaultPost1.AddComment(new Comment { Post = defaultPost1, User = user, Body = "test comment", Published = DateTime.Parse("31 DEC 2008") });

            _repository.Save(defaultPost1);
        }
Exemplo n.º 25
0
        public void SetUp()
        {
            _siteConfiguration = new SiteConfiguration
            {
                TwitterUserName = "******",
                TwitterPassword = "******",
            };

            _twitterClient = MockRepository.GenerateStub<ITwitterClient>();
            _tinyUrlService = MockRepository.GenerateStub<ITinyUrlService>();
            _urlResolver = MockRepository.GenerateStub<IUrlResolver>();

            _twitterService = new TwitterService(_siteConfiguration, _twitterClient, _tinyUrlService, _urlResolver);

            _user = new User
            {
                TwitterUserName = "******",
            };

            _post = new Post
            {
                User = _user,
                Title = "Test title",
            };
        }
    private static void Save(HttpContext context, Post post)
    {
        string name = context.Request.Form["name"];
        string email = context.Request.Form["email"];
        string website = context.Request.Form["website"];
        string content = context.Request.Form["content"];

        Validate(name, email, content);

        Comment comment = new Comment()
        {
            Author = name.Trim(),
            Email = email.Trim(),
            Website = GetUrl(website),
            Ip = context.Request.UserHostAddress,
            UserAgent = context.Request.UserAgent,
            IsAdmin = context.User.Identity.IsAuthenticated,
            Content = HttpUtility.HtmlEncode(content.Trim()).Replace("\n", "<br />"),
        };

        post.Comments.Add(comment);
        Storage.Save(post);

        if (!context.User.Identity.IsAuthenticated)
            System.Threading.ThreadPool.QueueUserWorkItem((s) => SendEmail(comment, post, context.Request));

        RenderComment(context, comment);
    }
        static void Main(string[] args)
        {
            var post = new Post();

            post["title"] = "MyPost";
            post["description"] = "This is a description of my post";
            Console.WriteLine(post["title"]);
            Console.WriteLine(post["description"]);
            Console.WriteLine("This post was created: " + post.TimeCreated());

            for (var i = 0; i < 5; i++)
            {
                Console.WriteLine("\n\nTo UpVote this post, press 1.");
                Console.WriteLine("To DownVote this post, press  2.");
                if (Console.ReadLine() == "1")
                {
                    post.UpVote++;
                }
                else if (Console.ReadLine() == "2")
                {
                    post.DownVote++;
                }
                Console.WriteLine("\nThere are currently " + post.UpVote + " UpVotes " + "And " + post.DownVote + " Down Votes");
            }
        }
Exemplo n.º 28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Permission.Check("post.read", true)) return;

        if (!Page.IsPostBack)
        {
            using (MooDB db = new MooDB())
            {
                if (Request["id"] != null)
                {
                    int postID = int.Parse(Request["id"]);
                    post = (from p in db.Posts
                            where p.ID == postID
                            select p).SingleOrDefault<Post>();
                }

                if (post == null)
                {
                    PageUtil.Redirect(Resources.Moo.FoundNothing, "~/");
                    return;
                }

                ViewState["postID"] = post.ID;
                Page.DataBind();
            }
        }
    }
Exemplo n.º 29
0
        public void AnExceptionInvalidatesTheScopeAndPreventItsFlushing()
        {
            using (new SessionScope()) {
                Post.DeleteAll();
                Blog.DeleteAll();
            }

            Post post;

            // Prepare
            using(new SessionScope())
            {
                var blog = new Blog {Author = "hammett", Name = "some name"};
                blog.Save();

                post = new Post(blog, "title", "contents", "castle");
                post.Save();
            }

            using(var session = new SessionScope())
            {
                Assert.IsFalse(session.HasSessionError);

                Assert.Throws<ActiveRecordException>(() => {
                    post = new Post(new Blog(100), "title", "contents", "castle");
                    post.Save();
                    session.Flush();
                });

                Assert.IsTrue(session.HasSessionError);
            }
        }
        public Post CreatePost(string message,string emailAddress)
        {
            Post post = new Post();
            using (DatabaseLayer dbLayer = new DatabaseLayer())
            {
                SqlCommand cmd = new SqlCommand("CreatePost");
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
                cmd.Parameters.AddWithValue("@message", message);

                DataSet postDataset = dbLayer.FillDataSet(cmd);

                if (postDataset != null && postDataset.Tables.Count > 0)
                {
                    foreach (DataRow row in postDataset.Tables[0].Rows)
                    {
                        post.Id = Convert.ToInt32(row["Id"].ToString());
                        post.Message = row["Message"].ToString();
                        post.CreatedOn = Convert.ToDateTime(row["CreatedOn"].ToString());
                        post.CreatedByString = row["CreatedByString"].ToString();
                        post.CreatedBy = Convert.ToInt32(row["CreatedBy"].ToString());

                    }
                }
            }

            return post;
        }
Exemplo n.º 31
0
 public async Task Add(Post post)
 {
     post.Created = DateTime.Now;
     _context.Add(post);
     await _context.SaveChangesAsync();
 }
Exemplo n.º 32
0
 public bool CreateNewPost(Post p)
 {
     return(postInterface.CreateNewPost(p));
 }
Exemplo n.º 33
0
 private void gv_FavoritePosts_ItemClick(object sender, ItemClickEventArgs e)
 {
     Post post = e.ClickedItem as Post;
     this.Frame.Navigate(typeof(PostReadingPage), post);
 }
Exemplo n.º 34
0
 public VoteModel(UserInfo user, Post post, VoteType type) : base(user)
 {
     Post = post;
     Type = type;
 }
Exemplo n.º 35
0
        /// <summary>
        /// Saves the model.
        /// </summary>
        /// <returns>Whether the action was successful or not</returns>
        public bool SaveAll(bool draft = true)
        {
            using (IDbTransaction tx = Database.OpenConnection().BeginTransaction()) {
                try {
                    bool permalinkfirst = Post.IsNew;

                    // Save permalink before the post if this is an insert
                    if (permalinkfirst)
                    {
                        // Permalink
                        if (Permalink.IsNew && String.IsNullOrEmpty(Permalink.Name))
                        {
                            Permalink.Name = Permalink.Generate(Post.Title);
                        }
                        Permalink.Save(tx);
                    }

                    // Post
                    if (draft)
                    {
                        Post.Save(tx);
                    }
                    else
                    {
                        Post.SaveAndPublish(tx);
                    }

                    // Save permalink after the post if this is an update
                    if (!permalinkfirst)
                    {
                        Permalink.Save(tx);
                    }
                    // Properties
                    Properties.ForEach(p => {
                        p.IsDraft = true;
                        p.Save(tx);
                        if (!draft)
                        {
                            if (Property.GetScalar("SELECT COUNT(property_id) FROM property WHERE property_id=@0 AND property_draft=0", p.Id) == 0)
                            {
                                p.IsNew = true;
                            }
                            p.IsDraft = false;
                            p.Save(tx);
                        }
                    });

                    // Save extensions
                    foreach (var ext in Extensions)
                    {
                        ext.ParentId = Post.Id;
                        ext.Save(tx);
                        if (!draft)
                        {
                            if (Extension.GetScalar("SELECT COUNT(extension_id) FROM extension WHERE extension_id=@0 AND extension_draft=0", ext.Id) == 0)
                            {
                                ext.IsNew = true;
                            }
                            ext.IsDraft = false;
                            ext.Save(tx);
                        }
                    }

                    // Update categories
                    Relation.DeleteByDataId(Post.Id, tx, true);
                    List <Relation> relations = new List <Relation>();
                    PostCategories.ForEach(pc => relations.Add(new Relation()
                    {
                        DataId = Post.Id, RelatedId = pc, Type = Relation.RelationType.POSTCATEGORY
                    })
                                           );
                    relations.ForEach(r => r.Save(tx));

                    // Publish categories
                    if (!draft)
                    {
                        Relation.DeleteByDataId(Post.Id, tx, false);
                        relations.ForEach(r => {
                            r.IsDraft = false;
                            r.IsNew   = true;
                        });
                        relations.ForEach(r => r.Save(tx));
                    }
                    tx.Commit();
                } catch { tx.Rollback(); throw; }
            }
            return(true);
        }
Exemplo n.º 36
0
 public async Task<Post> UpdatePost(Post post)
 {
     DbContext.Posts.Update(post);
     await DbContext.SaveChangesAsync();
     return post;
 }
Exemplo n.º 37
0
 public async Task<Post> AddPost(Post post)
 {
     DbContext.Posts.Add(post);
     await DbContext.SaveChangesAsync();
     return post;
 }
Exemplo n.º 38
0
        public IPostViewModel GetPostViewModel(int postId)
        {
            Post post = this.forumData.Posts.FirstOrDefault(p => p.Id == postId);

            return(new PostViewModel(post.Title, this.userService.GetUserName(post.AuthorId), post.Content, this.GetPostReplies(postId)));
        }
Exemplo n.º 39
0
 public void Add(Post post)
 {
     _postRepository.Add(post);
 }
Exemplo n.º 40
0
        public ActionResult Create([Bind(Include = "Id,Title,Image,Time,Description,Tags,Id_Category,DisabledComments,Visits")] Post post, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (Directory.Exists(Server.MapPath("~/Files/")) == false)
                {
                    Directory.CreateDirectory(Server.MapPath("~/Files/"));
                }

                //Guardar la Imagen
                if (file != null)
                {
                    string fileNameOP = string.Empty;
                    if (file.FileName.LastIndexOf("\\") > 0)
                    {
                        fileNameOP = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1);
                    }
                    else
                    {
                        fileNameOP = file.FileName;
                    }

                    string filename = Path.GetFileName(DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + "_" + fileNameOP);
                    file.SaveAs(Server.MapPath("~/Files/") + filename);
                    post.Image = filename;
                }

                post.DisabledComments = false;
                post.Visits           = 0;
                post.Time             = DateTime.Now;

                db.Post.Add(post);
                db.SaveChanges();

                int id_post = post.Id;

                string[]  tag      = post.Tags.Split(new string[] { "," }, StringSplitOptions.None);
                Post_Tags postTags = new Post_Tags();

                TagsController tagController = new TagsController();
                Tags           tags          = new Tags();
                int            id_tag        = 0;

                for (int i = 0; i < tag.Length; i++)
                {
                    int id_registro = VerificarRegistro(tag[i]);
                    //Verificar si el registro existe
                    if (id_registro == 0)
                    {
                        //Crear Tags
                        tags.Name = tag[i];
                        id_tag    = tagController.CreateTag(tags);
                        //Crear PostTags
                        CreateTagPost(id_post, id_tag);
                    }
                    else
                    {
                        CreateTagPost(id_post, id_registro);
                    }
                }

                return(RedirectToAction("Index"));
            }

            ViewBag.Category = new SelectList(db.Category, "Id", "Name", post.Category);
            return(View(post));
        }
Exemplo n.º 41
0
 public async Task UpdateAsync(Post post)
 {
     await Task.CompletedTask;
 }
Exemplo n.º 42
0
 public void Update(Post post)
 {
     _postRepository.Update(post);
 }
Exemplo n.º 43
0
 public async Task <IEnumerable <User> > GetAllUsersInvolvedAsync(Post post)
 => await Task.FromResult(post.UsersInvolved);
 public void AddPost(Post post)
 {
     _posts.Add(post);
 }
Exemplo n.º 45
0
 public bool EditPost(string postid, string username, string password, Post post, bool publish)
 {
     // TODO
     return(false);
 }
Exemplo n.º 46
0
 public async Task AddAsync(Post post)
 => await Task.FromResult(_posts.Add(post));
Exemplo n.º 47
0
 public void Insert(Post post)
 {
     postRepository.Insert(post);
     unitOfWork.SaveChanges();
 }
Exemplo n.º 48
0
 public async Task <IEnumerable <Comment> > GetAllCommentsAsync(Post post)
 => await Task.FromResult(post.Comments);
 public void Remove(Post post)
 {
     _posts.Remove(post);
 }
Exemplo n.º 50
0
 public string AddPost(string blogid, string username, string password, Post post, bool publish)
 {
     // TODO
     return(null);
 }
Exemplo n.º 51
0
 public IActionResult Post(Post post)
 {
     _postRepository.Add(post);
     return(CreatedAtAction("Get", new { id = post.Id }, post));
 }
Exemplo n.º 52
0
 public void Delete(Post post)
 {
     postRepository.Delete(post);
     unitOfWork.SaveChanges();
 }
Exemplo n.º 53
0
        public static string CreatePermalink(Post post)
        {
            var title = post.Title.ToLowerInvariant().Replace(Constants.Space, Constants.Dash, StringComparison.OrdinalIgnoreCase);

            return(CleanString(title).ToLowerInvariant());
        }
Exemplo n.º 54
0
 Post IPostRepository.Add(Post Post)
 {
     context.Posts.Add(Post);
     context.SaveChanges();
     return(Post);
 }
Exemplo n.º 55
0
        /// <summary>
        /// Creates a new post on disk and returns the filename
        /// </summary>
        /// <param name="post"></param>
        /// <param name="weblogName"></param>
        /// <returns></returns>
        public string  CreateDownloadedPostOnDisk(Post post, string weblogName = null)
        {
            if (post == null)
            {
                return(null);
            }

            string filename = GetSafeFilename(post.Title);

            if (string.IsNullOrEmpty(weblogName))
            {
                weblogName = WeblogInfo.Name;
            }


            var mmPostFolder = Path.Combine(WeblogAddinConfiguration.Current.PostsFolder,
                                            "Downloaded", weblogName,
                                            filename);

            if (!Directory.Exists(mmPostFolder))
            {
                Directory.CreateDirectory(mmPostFolder);
            }


            var outputFile = Path.Combine(mmPostFolder, StringUtils.ToCamelCase(filename) + ".md");

            string body          = post.Body;
            string featuredImage = null;
            string categories    = null;

            if (post.Categories != null && post.Categories.Length > 0)
            {
                categories = string.Join(",", post.Categories);
            }



            // Create the new post by creating a file with title preset
            var meta = new WeblogPostMetadata()
            {
                Title            = post.Title,
                RawMarkdownBody  = body,
                Categories       = categories,
                Keywords         = post.mt_keywords,
                Abstract         = post.mt_excerpt,
                PostId           = post.PostId?.ToString(),
                WeblogName       = weblogName,
                FeaturedImageUrl = featuredImage,
                PostDate         = post.DateCreated,
                PostStatus       = post.PostStatus,
                Permalink        = post.Permalink
            };

            var postMarkdown = meta.SetPostYamlFromMetaData();

            var jekyllPostFolder = Path.Combine(WeblogInfo.ApiUrl, "assets", meta.PostId);

            postMarkdown = CopyImagesToLocal(postMarkdown, jekyllPostFolder, mmPostFolder);

            try
            {
                File.WriteAllText(outputFile, postMarkdown);
            }
            catch (Exception ex)
            {
                this.SetError($@"Couldn't write new file at:
{outputFile}

{ex.Message}");

                return(null);
            }
            mmApp.Configuration.LastFolder = Path.GetDirectoryName(outputFile);

            return(outputFile);
        }
Exemplo n.º 56
0
 public void Post(Post post)
 {
 }
Exemplo n.º 57
0
    //Localhost Connection
    // System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["LocalhostConnectionString"].ToString());

    protected void Page_Load(object sender, EventArgs e)
    {
        // Bind current posts from the database to the page
        GridViewPosts.DataSource = Post.getAllPostInfo();
        GridViewPosts.DataBind();
    }
Exemplo n.º 58
0
        /// <summary>
        /// Retrieves Weblog Metadata and Post Data from a Jekyll post on disk
        /// </summary>
        /// <param name="jekyllPostFilename">Full path to a Jekyll post on disk</param>
        /// <returns></returns>
        private WeblogPostMetadata GetPostMetaDataFromFile(string jekyllPostFilename, Post post)
        {
            string content = null;

            try
            {
                content = File.ReadAllText(jekyllPostFilename);
                if (string.IsNullOrEmpty(content))
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }

            var meta = WeblogPostMetadata.GetPostYamlConfigFromMarkdown(content, post);

            if (meta == null)
            {
                return(null);
            }

            string   dateString = MarkdownUtilities.ExtractYamlValue(meta.YamlFrontMatter, "date");
            DateTime date;

            if (!DateTime.TryParse(dateString, out date))
            {
                dateString = jekyllPostFilename.Substring(0, 10);
                if (!DateTime.TryParse(dateString, out date))
                {
                    date = DateTime.Now.Date;
                }
            }
            post.DateCreated = date;
            meta.PostDate    = date;

            content         = Markdown.ToPlainText(meta.MarkdownBody);
            post.mt_excerpt = StringUtils.TextAbstract(content, 180);

            return(meta);
        }
Exemplo n.º 59
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,BlogId,Created,Slug,Title,Abstract,Content,PublishState,ImageData,ContentType")] Post post, IFormFile newImageFile)
        {
            if (User.Identity.IsAuthenticated)
            {
                ViewData["HeaderText"] = $"Dear {(await _userManager.GetUserAsync(User)).GivenName}";
            }
            else
            {
                ViewData["HeaderText"] = "Dear Coder";
            }

            ViewData["SubheaderText"] = "Please edit your post.";
            if (id != post.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var newSlug = _slugService.UrlFriendly(post.Title);
                    //I need to compare the original slug with the current slug
                    if (post.Slug != newSlug)
                    {
                        if (!_slugService.IsUnique(newSlug))
                        {
                            ModelState.AddModelError("Title", "There is an issue with the Title, please try again");
                        }
                        post.Slug = newSlug;
                    }

                    //Change the "Created" Date to reflect the date of publication
                    Post oldpost = await _context.Posts.AsNoTracking().FirstOrDefaultAsync(p => p.Id == post.Id);

                    PublishState oldPublishState = oldpost.PublishState;

                    if (post.PublishState != oldPublishState && post.PublishState == PublishState.ProductionReady)
                    {
                        post.Created = DateTime.Now;
                    }

                    if (newImageFile is not null)
                    {
                        post.ImageData = await _fileService.EncodeFileAsync(newImageFile);

                        post.ContentType = _fileService.ContentType(newImageFile);
                    }

                    post.Updated = DateTime.Now;

                    _context.Update(post);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PostExists(post.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Details), new { slug = post.Slug }));
            }
            ViewData["BlogId"] = new SelectList(_context.Blogs, "Id", "Description", post.BlogId);
            return(View(post));
        }
Exemplo n.º 60
0
        private Like GetLike(Post post, AppUser user)
        {
            var like = post.Likes.FirstOrDefault(l => l.User.Alias == user.Alias);

            return(like);
        }