示例#1
0
        public void CanUpdate()
        {
            UnitTestHelper.SetupBlog();

            Image image = CreateImageInstance();

            Assert.GreaterEqualThan(Config.CurrentBlog.Id, 0);
            Assert.AreEqual(Config.CurrentBlog.Id, image.BlogId);
            int imageId = Images.InsertImage(image, singlePixelBytes);

            Image saved = ObjectProvider.Instance().GetImage(imageId, true /* activeOnly */);

            Assert.AreEqual(Config.CurrentBlog.Id, saved.BlogId, "The blog id for the image does not match!");
            saved.LocalDirectoryPath = Path.GetFullPath(TestDirectory);
            Assert.AreEqual("Test Image", saved.Title);

            saved.Title = "A Better Title";
            Images.Update(saved, singlePixelBytes);

            Image loaded = ObjectProvider.Instance().GetImage(imageId, true /* activeOnly */);

            Assert.AreEqual(Config.CurrentBlog.Id, loaded.BlogId, "The blog id for the image does not match!");
            loaded.LocalDirectoryPath = Path.GetFullPath(TestDirectory);

            Assert.AreEqual("A Better Title", loaded.Title, "The title was not updated");
        }
        public void SettingDateSyndicatedToNullRemovesItemFromSyndication()
        {
            //arrange
            Config.CreateBlog("", "username", "password", _hostName, string.Empty);
            BlogRequest.Current.Blog = Config.GetBlog(_hostName, string.Empty);

            Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("Haacked", "Title Test", "Body Rocking");

            UnitTestHelper.Create(entry);

            Assert.IsTrue(entry.IncludeInMainSyndication,
                          "Failed to setup this test properly.  This entry should be included in the main syndication.");
            Assert.IsFalse(NullValue.IsNull(entry.DateSyndicated),
                           "Failed to setup this test properly. DateSyndicated should be null.");

            //act
            entry.DateSyndicated = NullValue.NullDateTime;

            //assert
            Assert.IsFalse(entry.IncludeInMainSyndication,
                           "Setting the DateSyndicated to a null date should have reset 'IncludeInMainSyndication'.");

            //save it
            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog);
            subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
            UnitTestHelper.Update(entry, subtextContext.Object);
            Entry savedEntry = UnitTestHelper.GetEntry(entry.Id, PostConfig.None, false);

            //assert again
            Assert.IsFalse(savedEntry.IncludeInMainSyndication,
                           "This item should still not be included in main syndication.");
        }
示例#3
0
 public DiscrepancyController()
 {
     objectProvider = objectProvider == null ? new ObjectProvider() : objectProvider;
     unitOfWork     = unitOfWork == null ? objectProvider.UnitOfWork : unitOfWork;
     stockUnavailableReasonRepository   = stockUnavailableReasonRepository == null ? unitOfWork.StockUnavailableReasonRepository : stockUnavailableReasonRepository;
     confirmedOrderlineChangeRepository = confirmedOrderlineChangeRepository == null ? unitOfWork.ConfirmedOrderlineChangeRepository : confirmedOrderlineChangeRepository;
 }
        public void CanGetItemsFlaggedAsSpam()
        {
            Entry entry = SetupBlogForCommentsAndCreateEntry();

            CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.FalsePositive);
            CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.Approved);
            CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment, FeedbackStatusFlag.ConfirmedSpam);
            FeedbackItem included = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
                                                                           FeedbackStatusFlag.FlaggedAsSpam);
            FeedbackItem includedToo = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
                                                                              FeedbackStatusFlag.FlaggedAsSpam |
                                                                              FeedbackStatusFlag.NeedsModeration);

            //We expect 2 of the four.
            IPagedCollection <FeedbackItem> feedback = ObjectProvider.Instance().GetPagedFeedback(0, 10,
                                                                                                  FeedbackStatusFlag.
                                                                                                  FlaggedAsSpam,
                                                                                                  FeedbackStatusFlag.
                                                                                                  Approved |
                                                                                                  FeedbackStatusFlag.
                                                                                                  Deleted,
                                                                                                  FeedbackType.Comment);

            Assert.AreEqual(2, feedback.Count, "We expected two to match.");

            //Expect reverse order
            Assert.AreEqual(included.Id, feedback[1].Id, "The first does not match");
            Assert.AreEqual(includedToo.Id, feedback[0].Id, "The second does not match");
        }
        static FeedbackItem CreateAndUpdateFeedbackWithExactStatus(Entry entry, FeedbackType type,
                                                                   FeedbackStatusFlag status)
        {
            var feedback = new FeedbackItem(type);

            feedback.Title   = UnitTestHelper.GenerateUniqueString();
            feedback.Body    = UnitTestHelper.GenerateUniqueString();
            feedback.EntryId = entry.Id;
            feedback.Author  = "TestAuthor";

            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.Setup(c => c.Cache).Returns(new TestCache());
            subtextContext.SetupBlog(Config.CurrentBlog);
            subtextContext.SetupRepository(ObjectProvider.Instance());
            subtextContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());
            subtextContext.Setup(c => c.HttpContext).Returns(new HttpContextWrapper(HttpContext.Current));

            var service = new CommentService(subtextContext.Object, null);
            int id      = service.Create(feedback, true /*runFilters*/);

            feedback        = FeedbackItem.Get(id);
            feedback.Status = status;
            FeedbackItem.Update(feedback);

            return(FeedbackItem.Get(id));
        }
        public void CreateTrackbackSetsFeedbackTypeCorrectly()
        {
            string hostname = UnitTestHelper.GenerateUniqueString();

            Config.CreateBlog("", "username", "password", hostname, string.Empty);
            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty, string.Empty);
            Blog blog = Config.GetBlog(hostname, string.Empty);

            BlogRequest.Current.Blog = blog;

            Entry entry    = UnitTestHelper.CreateEntryInstanceForSyndication("phil", "title", "body");
            int   parentId = UnitTestHelper.Create(entry);

            var trackback      = new Trackback(parentId, "title", new Uri("http://url"), "phil", "body", blog.TimeZone.Now);
            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog);
            //TODO: FIX!!!
            subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
            subtextContext.Setup(c => c.Cache).Returns(new TestCache());
            subtextContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());
            var commentService = new CommentService(subtextContext.Object, null);
            int id             = commentService.Create(trackback, true /*runFilters*/);

            FeedbackItem loadedTrackback = FeedbackItem.Get(id);

            Assert.IsNotNull(loadedTrackback, "Was not able to load trackback from storage.");
            Assert.AreEqual(FeedbackType.PingTrack, loadedTrackback.FeedbackType, "Feedback should be a PingTrack");
        }
        public void CanGetAllApprovedComments()
        {
            Entry entry = SetupBlogForCommentsAndCreateEntry();

            FeedbackItem commentOne = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
                                                                             FeedbackStatusFlag.Approved);
            FeedbackItem commentTwo = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
                                                                             FeedbackStatusFlag.ApprovedByModerator);
            FeedbackItem commentThree = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
                                                                               FeedbackStatusFlag.ConfirmedSpam);

            FeedbackItem.ConfirmSpam(commentThree, null);
            FeedbackItem commentFour = CreateAndUpdateFeedbackWithExactStatus(entry, FeedbackType.Comment,
                                                                              FeedbackStatusFlag.FalsePositive);

            //We expect three of the four.
            IPagedCollection <FeedbackItem> feedback = ObjectProvider.Instance().GetPagedFeedback(0, 10,
                                                                                                  FeedbackStatusFlag.
                                                                                                  Approved,
                                                                                                  FeedbackStatusFlag.None,
                                                                                                  FeedbackType.Comment);

            Assert.AreEqual(3, feedback.Count, "We expected three to match.");

            //Expect reverse order
            Assert.AreEqual(commentOne.Id, feedback[2].Id, "The first does not match");
            Assert.AreEqual(commentTwo.Id, feedback[1].Id, "The first does not match");
            Assert.AreEqual(commentFour.Id, feedback[0].Id, "The first does not match");
        }
示例#8
0
 /// <summary>
 /// Loads the host from the Object Provider. This is provided for
 /// those cases when we really need to hit the data strore. Calling this
 /// method will also reload the HostInfo.Instance from the data store.
 /// </summary>
 /// <param name="suppressException">If true, won't throw an exception.</param>
 /// <returns></returns>
 public static HostInfo LoadHost(bool suppressException)
 {
     try
     {
         _instance = ObjectProvider.Instance().LoadHostInfo(new HostInfo());
         if (_instance != null)
         {
             _instance.BlogAggregationEnabled =
                 String.Equals(ConfigurationManager.AppSettings["AggregateEnabled"], "true",
                               StringComparison.OrdinalIgnoreCase);
             if (_instance.BlogAggregationEnabled)
             {
                 InitAggregateBlog(_instance);
             }
         }
         return(_instance);
     }
     catch (SqlException e)
     {
         // LoadHostInfo now executes the stored proc subtext_GetHost, instead of checking the table subtext_Host
         if (e.Message.IndexOf("Invalid object name 'subtext_Host'") >= 0 ||
             e.Message.IndexOf("Could not find stored procedure 'subtext_GetHost'") >= 0)
         {
             if (suppressException)
             {
                 return(null);
             }
             throw new HostDataDoesNotExistException();
         }
         throw;
     }
 }
示例#9
0
 public override void SaveModel()
 {
     if (this.Validation())
     {
         DIC_DOITUONG  doituong = (DIC_DOITUONG)this.GetModel();
         SqlResultType flag;
         if (this.actions == Common.Common.Class.Actions.AddNew)
         {
             flag = new ObjectProvider().Insert(doituong);
         }
         else
         {
             flag = new ObjectProvider().Update(doituong);
         }
         SaveCompleteEventArgs args = new SaveCompleteEventArgs();
         args.Result  = flag == SqlResultType.OK;
         args.Model   = doituong;
         args.Message = "Không lưu được thông tin đối tượng";
         this.SaveCompleteSuccess(doituong, args);
     }
     else
     {
         XtraMessageBox.Show("Thông tin chưa hợp lệ kiểm tra lại thông tin.");
     }
 }
示例#10
0
 public void LoadData()
 {
     using (var db = ObjectProvider.CreateDB())
     {
         _tickets.AddRange(db.Tickets);
     }
 }
示例#11
0
        private void GetPosts(XmlNode connectorNode, string currentFolder)
        {
            IPagedCollection <EntryStatsView> posts;

            if (currentFolder.Equals("/"))
            {
                posts = Repository.GetEntries(PostType.BlogPost, -1, 0, 1000);
            }
            else
            {
                string       categoryName = currentFolder.Substring(1, currentFolder.Length - 2);
                LinkCategory cat          = ObjectProvider.Instance().GetLinkCategory(categoryName, false);
                posts = Repository.GetEntries(PostType.BlogPost, cat.Id, 0, 1000);
            }

            // Create the "Files" node.
            XmlNode oFilesNode = XmlUtil.AppendElement(connectorNode, "Files");

            foreach (var entry in posts)
            {
                // Create the "File" node.
                if (entry.IsActive)
                {
                    XmlNode oFileNode = XmlUtil.AppendElement(oFilesNode, "File");

                    //TODO: Seriously refactor.
                    var urlHelper = new UrlHelper(null, null);

                    XmlUtil.SetAttribute(oFileNode, "name",
                                         string.Format(CultureInfo.InvariantCulture, "{0}|{1}", entry.Title,
                                                       urlHelper.EntryUrl(entry).ToFullyQualifiedUrl(Config.CurrentBlog)));
                    XmlUtil.SetAttribute(oFileNode, "size", entry.DateModified.ToShortDateString());
                }
            }
        }
示例#12
0
        public void CanUpdateEnclosure(string title, string url, string mimetype, long size, bool addToFeed,
                                       bool showWithPost)
        {
            UnitTestHelper.SetupBlog(string.Empty);
            Entry e = UnitTestHelper.CreateEntryInstanceForSyndication("Simone Chiaretta", "Post for testing Enclosures",
                                                                       "Listen to my great podcast");
            int       entryId = UnitTestHelper.Create(e);
            Enclosure enc     = UnitTestHelper.BuildEnclosure(title, url, mimetype, entryId, size, addToFeed, showWithPost);

            Enclosures.Create(enc);

            string randomStr = UnitTestHelper.GenerateUniqueString().Left(20);

            enc.Url = url + randomStr;

            if (!string.IsNullOrEmpty(title))
            {
                enc.Title = title + randomStr;
            }

            enc.MimeType = mimetype + randomStr;

            int randomSize = new Random().Next(10, 100);

            enc.Size = size + randomSize;

            Assert.IsTrue(Enclosures.Update(enc), "Should have updated the Enclosure");

            Entry newEntry = ObjectProvider.Instance().GetEntry(entryId, true, false);

            UnitTestHelper.AssertEnclosures(enc, newEntry.Enclosure);
        }
        private ObjectModel ProcessObject(SceneObject sceneObject)
        {
            var objectModel = new ObjectModel();

            try
            {
                var objectPath = sceneObject.MeshedObject.Reference;
                objectModel = ObjectProvider.ParseObject(objectPath);

                var rotate    = sceneObject.Transform.Rotation;
                var scale     = sceneObject.Transform.Scale;
                var translate = sceneObject.Transform.Position;

                var transformation = new Transformation.Transformation();
                transformation.RotateX((float)rotate.X);
                transformation.RotateY((float)rotate.Y);
                transformation.RotateZ((float)rotate.Z);
                transformation.Scale(new Vector3((float)scale.X, (float)scale.Y, (float)scale.Z));
                transformation.Translate(new Vector3((float)translate.X, (float)translate.Y, (float)translate.Z));
                transformation.Transform(ref objectModel);
            }
            catch (Exception)
            {
                // ignored
            }

            return(objectModel);
        }
        public void RssWriterProducesValidFeedWithEnclosureFromDatabase()
        {
            string hostName = UnitTestHelper.GenerateUniqueString() + ".com";

            Config.CreateBlog("Test", "username", "password", hostName, string.Empty);

            UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "");
            BlogRequest.Current.Blog = Config.GetBlog(hostName, string.Empty);
            Config.CurrentBlog.Email = "*****@*****.**";
            Config.CurrentBlog.RFC3229DeltaEncodingEnabled = false;

            Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("Author", "testtitle", "testbody", null,
                                                                           NullValue.NullDateTime);

            entry.DateCreated    = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture);
            entry.DateSyndicated = entry.DateCreated;
            int entryId = UnitTestHelper.Create(entry); //persist to db.

            string enclosureUrl      = "http://perseus.franklins.net/hanselminutes_0107.mp3";
            string enclosureMimeType = "audio/mp3";
            long   enclosureSize     = 26707573;

            Enclosure enc =
                UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
                                              enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true);

            Enclosures.Create(enc);

            var    subtextContext = new Mock <ISubtextContext>();
            string rssOutput      = null;

            subtextContext.FakeSyndicationContext(Config.CurrentBlog, "/", s => rssOutput = s);
            subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
            Mock <UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);

            urlHelper.Setup(u => u.BlogUrl()).Returns("/");
            urlHelper.Setup(u => u.EntryUrl(It.IsAny <Entry>())).Returns("/archive/2008/01/23/testtitle.aspx");

            XmlNodeList itemNodes = GetRssHandlerItemNodes(subtextContext.Object, ref rssOutput);

            Assert.AreEqual(1, itemNodes.Count, "expected one item nodes.");

            string urlFormat   = "http://{0}/archive/2008/01/23/{1}.aspx";
            string expectedUrl = string.Format(urlFormat, hostName, "testtitle");

            Assert.AreEqual("testtitle", itemNodes[0].SelectSingleNode("title").InnerText,
                            "Not what we expected for the title.");
            Assert.AreEqual(expectedUrl, itemNodes[0].SelectSingleNode("link").InnerText,
                            "Not what we expected for the link.");
            Assert.AreEqual(expectedUrl, itemNodes[0].SelectSingleNode("guid").InnerText,
                            "Not what we expected for the guid.");
            Assert.AreEqual(enclosureUrl, itemNodes[0].SelectSingleNode("enclosure/@url").InnerText,
                            "Not what we expected for the enclosure url.");
            Assert.AreEqual(enclosureMimeType, itemNodes[0].SelectSingleNode("enclosure/@type").InnerText,
                            "Not what we expected for the enclosure mimetype.");
            Assert.AreEqual(enclosureSize.ToString(), itemNodes[0].SelectSingleNode("enclosure/@length").InnerText,
                            "Not what we expected for the enclosure size.");
            Assert.AreEqual(expectedUrl + "#feedback", itemNodes[0].SelectSingleNode("comments").InnerText,
                            "Not what we expected for the link.");
        }
        public void newPost_WithCategory_CreatesEntryWithCategory()
        {
            //arrange
            var blog = new Blog {
                Id = 42, UserName = "******", Password = "******", AllowServiceAccess = true, Host = "localhost"
            };

            var   entryPublisher = new Mock <IEntryPublisher>();
            Entry publishedEntry = null;

            entryPublisher.Setup(publisher => publisher.Publish(It.IsAny <Entry>())).Callback <Entry>(e => publishedEntry = e);
            var subtextContext = new Mock <ISubtextContext>();

            subtextContext.Setup(c => c.Blog).Returns(blog);
            subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
            subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock <IServiceLocator>().Object);

            var api  = new MetaWeblog(subtextContext.Object, entryPublisher.Object);
            var post = new Post
            {
                categories  = new[] { "CategoryA" },
                description = "A unit test",
                title       = "A unit testing title",
                dateCreated = DateTime.UtcNow
            };

            //act
            api.newPost("42", "username", "password", post, true);

            //assert
            Assert.IsNotNull(publishedEntry);
            Assert.AreEqual(1, publishedEntry.Categories.Count);
            Assert.AreEqual("CategoryA", publishedEntry.Categories.First());
        }
示例#16
0
        public Account GetCurrentUserAccount()
        {
            var http     = ObjectProvider.CreateHttpHelper();
            var userName = http.GetCurrentUserName();

            return(GetUserAccount(userName));
        }
示例#17
0
        public void CanGetPostsByCategoryArchive()
        {
            UnitTestHelper.SetupBlog();
            ICollection <ArchiveCount> counts = Archives.GetPostCountByCategory();

            Assert.AreEqual(0, counts.Count);

            Entry entry      = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title", "body");
            int   categoryId = UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, "Test");
            int   entryId    = UnitTestHelper.Create(entry);

            ObjectProvider.Instance().SetEntryCategoryList(entryId, new[] { categoryId });
            counts = Archives.GetPostCountByCategory();
            Assert.AreEqual(1, counts.Count);

            foreach (ArchiveCount archiveCount in counts)
            {
                Assert.AreEqual(1, archiveCount.Count, "Expected one post in the archive.");
                archiveCount.Title = "Test";
                Assert.AreEqual("Test", archiveCount.Title);
                archiveCount.Id = 10;
                Assert.AreEqual(10, archiveCount.Id);
                return;
            }
        }
        public void GetEntriesByTagIncludesEnclosure()
        {
            Entry entryZero = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero");

            Thread.Sleep(100);
            Entry entryOne = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one");

            UnitTestHelper.Create(entryZero);
            UnitTestHelper.Create(entryOne);


            Enclosure enc = UnitTestHelper.BuildEnclosure("Nothing to see here.", "httP://blablabla.com", "audio/mp3",
                                                          entryZero.Id, 12345678, true, true);

            Enclosures.Create(enc);

            var tags = new List <string>(new[] { "Tag1", "Tag2" });

            new DatabaseObjectProvider().SetEntryTagList(entryZero.Id, tags);
            new DatabaseObjectProvider().SetEntryTagList(entryOne.Id, tags);


            ICollection <Entry> entries = ObjectProvider.Instance().GetEntriesByTag(3, "Tag1");

            //Test outcome
            Assert.AreEqual(2, entries.Count, "Should have retrieved two entries.");

            Assert.AreEqual(entries.First().Id, entryOne.Id, "Ordering is off.");
            Assert.AreEqual(entries.ElementAt(1).Id, entryZero.Id, "Ordering is off.");

            Assert.IsNull(entries.First().Enclosure, "Entry should not have enclosure.");
            Assert.IsNotNull(entries.ElementAt(1).Enclosure, "Entry should have enclosure.");
            UnitTestHelper.AssertEnclosures(enc, entries.ElementAt(1).Enclosure);
        }
 public DeletePostCommand(ObjectProvider repository, int postID, ISearchEngineService searchEngineService)
 {
     _targetName  = "Post";
     _targetID    = postID;
     Repository   = repository;
     SearchEngine = searchEngineService;
 }
 public InternalAppController()
 {
     objectProvider      = objectProvider == null ? new ObjectProvider() : objectProvider;
     unitOfWork          = unitOfWork == null ? objectProvider.UnitOfWork : unitOfWork;
     orderRepository     = orderRepository == null ? unitOfWork.OrderRepository : orderRepository;
     orderLineRepository = orderLineRepository == null ? unitOfWork.OrderLineRepository : orderLineRepository;
 }
        public void GetPreviousAndNextEntriesReturnsBoth()
        {
            string hostname = UnitTestHelper.GenerateUniqueString();

            Config.CreateBlog("", "username", "password", hostname, string.Empty);
            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty);
            BlogRequest.Current.Blog = Config.GetBlog(hostname, string.Empty);

            Entry previousEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body",
                                                                                   UnitTestHelper.GenerateUniqueString(),
                                                                                   DateTime.Now.AddDays(-2));
            Entry currentEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body",
                                                                                  UnitTestHelper.GenerateUniqueString(),
                                                                                  DateTime.Now.AddDays(-1));
            Entry nextEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body",
                                                                               UnitTestHelper.GenerateUniqueString(),
                                                                               DateTime.Now);

            int previousId = UnitTestHelper.Create(previousEntry);

            Thread.Sleep(100);
            int currentId = UnitTestHelper.Create(currentEntry);

            Thread.Sleep(100);
            int nextId = UnitTestHelper.Create(nextEntry);

            var entries = ObjectProvider.Instance().GetPreviousAndNextEntries(currentId,
                                                                              PostType.BlogPost);

            Assert.AreEqual(2, entries.Count, "Expected both previous and next.");

            //The more recent one is next because of desceding sort.
            Assert.AreEqual(nextId, entries.First().Id, "The next entry does not match expectations.");
            Assert.AreEqual(previousId, entries.ElementAt(1).Id, "The previous entry does not match expectations.");
        }
示例#22
0
        public void ProcessRequest_WithGetRequest_SendsRssResponse()
        {
            //arrange
            UnitTestHelper.SetupBlog();
            Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("phil", "this is the title", "body");

            entry.DateCreated          =
                entry.DateSyndicated   =
                    entry.DateModified = DateTime.ParseExact("2006/05/25", "yyyy/MM/dd", CultureInfo.InvariantCulture);
            int id = UnitTestHelper.Create(entry);

            Blog blog = Config.CurrentBlog;

            blog.TrackbacksEnabled = true;

            var          subtextContext = new Mock <ISubtextContext>();
            StringWriter writer         = subtextContext.FakeSubtextContextRequest(blog, "/trackbackhandler", "/", string.Empty);

            subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance());
            subtextContext.Object.RequestContext.RouteData.Values.Add("id", id.ToString());
            Mock <UrlHelper> urlHelper = Mock.Get(subtextContext.Object.UrlHelper);

            urlHelper.Setup(u => u.TrackbacksUrl(It.IsAny <int>())).Returns("/whatever/trackback");
            subtextContext.SetupBlog(blog);
            var handler = new TrackBackHandler(subtextContext.Object);

            //act
            handler.ProcessRequest();

            //assert
            Assert.IsTrue(writer.ToString().Contains("this is the title"));
        }
示例#23
0
        // Saves a new blog group.  Any exceptions are propagated up to the caller.
        void SaveNewGroup()
        {
            int displayOrder;

            if (!Int32.TryParse(txtDisplayOrder.Text, out displayOrder))
            {
                displayOrder = NullValue.NullInt32;
            }

            var blogGroup = new BlogGroup
            {
                Title        = txtTitle.Text,
                Description  = txtDescription.Text,
                IsActive     = true,
                DisplayOrder = displayOrder,
            };

            if (ObjectProvider.Instance().InsertBlogGroup(blogGroup) > 0)
            {
                messagePanel.ShowMessage(Resources.GroupsEditor_BlogGroupCreated);
            }
            else
            {
                messagePanel.ShowError(Resources.Message_UnexpectedError);
            }
        }
        public void CanAddAndRemoveAllCategories()
        {
            string hostname = UnitTestHelper.GenerateUniqueString();

            Config.CreateBlog("empty title", "username", "password", hostname, string.Empty);

            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty, "/");
            BlogRequest.Current.Blog = Config.GetBlog(hostname, "");
            Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("Me", "Unit Test Entry", "Body");
            int   id    = UnitTestHelper.Create(entry);

            int categoryId = UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, "My Subtext UnitTest Category");

            ObjectProvider.Instance().SetEntryCategoryList(id, new[] { categoryId });

            Entry loaded = UnitTestHelper.GetEntry(id, PostConfig.None, true);

            Assert.AreEqual("My Subtext UnitTest Category", loaded.Categories.First(),
                            "Expected a category for this entry");

            ObjectProvider.Instance().SetEntryCategoryList(id, new int[] { });

            loaded = UnitTestHelper.GetEntry(id, PostConfig.None, true);
            Assert.AreEqual(0, loaded.Categories.Count, "Expected that our category would be removed.");
        }
示例#25
0
        // Saves changes to a blog group.  Any exceptions are propagated up to the caller.
        void SaveGroupEdits()
        {
            int displayOrder;

            if (!Int32.TryParse(txtDisplayOrder.Text, out displayOrder))
            {
                displayOrder = NullValue.NullInt32;
            }

            var blogGroup = new BlogGroup
            {
                Id           = GroupId,
                Title        = txtTitle.Text,
                Description  = txtDescription.Text,
                IsActive     = Convert.ToBoolean(hfActive.Value),
                DisplayOrder = displayOrder,
            };


            if (ObjectProvider.Instance().UpdateBlogGroup(blogGroup))
            {
                messagePanel.ShowMessage(Resources.GroupsEditor_BlogGroupSaved);
            }
            else
            {
                messagePanel.ShowError(Resources.Message_UnexpectedError);
            }
        }
示例#26
0
 private void DeleteGroup()
 {
     if (ObjectProvider.Instance().DeleteBlogGroup(GroupId))
     {
         BindList();
     }
 }
示例#27
0
        public void CanUpdateLink()
        {
            UnitTestHelper.SetupBlog();
            // Create the categories
            CreateSomeLinkCategories();

            int categoryId =
                Links.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds",
                                                        CategoryType.LinkCollection, true));
            Link link   = CreateLink("Test", categoryId, null);
            int  linkId = link.Id;

            Link loaded = ObjectProvider.Instance().GetLink(linkId);

            Assert.AreEqual("Test", loaded.Title);

            Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "test");

            //Make changes then update.
            link.PostId    = entry.Id;
            link.Title     = "Another title";
            link.NewWindow = true;
            ObjectProvider.Instance().UpdateLink(link);
            loaded = ObjectProvider.Instance().GetLink(linkId);
            Assert.AreEqual("Another title", loaded.Title);
            Assert.IsTrue(loaded.NewWindow);
            Assert.AreEqual(entry.Id, loaded.PostId);
        }
示例#28
0
        public void CanGetCategoriesByPostId()
        {
            UnitTestHelper.SetupBlog();

            int category1Id =
                Links.CreateLinkCategory(CreateCategory("Post Category 1", "Cody roolz!", CategoryType.PostCollection,
                                                        true));
            int category2Id =
                Links.CreateLinkCategory(CreateCategory("Post Category 2", "Cody roolz again!",
                                                        CategoryType.PostCollection, true));

            Links.CreateLinkCategory(CreateCategory("Post Category 3", "Cody roolz and again!",
                                                    CategoryType.PostCollection, true));

            Entry entry   = UnitTestHelper.CreateEntryInstanceForSyndication("phil", "title", "body");
            int   entryId = UnitTestHelper.Create(entry);

            ObjectProvider.Instance().SetEntryCategoryList(entryId, new[] { category1Id, category2Id });

            ICollection <LinkCategory> categories = Links.GetLinkCategoriesByPostId(entryId);

            Assert.AreEqual(2, categories.Count, "Expected two of the three categories");

            Assert.AreEqual(category1Id, categories.First().Id);
            Assert.AreEqual(category2Id, categories.ElementAt(1).Id);

            Assert.AreEqual(Config.CurrentBlog.Id, categories.First().BlogId);
        }
示例#29
0
        public void CanGetRecentImages()
        {
            //arrange
            UnitTestHelper.SetupBlog();
            ObjectProvider provider = ObjectProvider.Instance();
            var            category = new LinkCategory
            {
                BlogId      = Config.CurrentBlog.Id,
                Description = "Whatever",
                IsActive    = true,
                Title       = "Whatever"
            };
            int categoryId = provider.CreateLinkCategory(category);

            var image = new Image
            {
                Title      = "Title",
                CategoryID = categoryId,
                BlogId     = Config.CurrentBlog.Id,
                FileName   = "Foo",
                Height     = 10,
                Width      = 10,
                IsActive   = true,
            };
            int imageId = provider.InsertImage(image);

            //act
            ICollection <Image> images = provider.GetImages(Config.CurrentBlog.Host, null, 10);

            //assert
            Assert.AreEqual(1, images.Count);
            Assert.AreEqual(imageId, images.First().ImageID);
        }
        public void GetPostsByCategoryIDReturnsDaysWithEnclosure()
        {
            //Create Category
            int blogId     = Config.CurrentBlog.Id;
            int categoryId = UnitTestHelper.CreateCategory(blogId, "Test Category");

            //Create some entries.
            Entry entryZero = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-zero", "body-zero");

            Thread.Sleep(100);
            Entry entryOne = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-one", "body-one");

            Thread.Sleep(100);
            Entry entryTwo = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-two", "body-two");

            Thread.Sleep(100);
            Entry entryThree = UnitTestHelper.CreateEntryInstanceForSyndication("me", "title-two", "body-two");

            entryThree.DateCreated = DateTime.Now.AddDays(1);

            //Associate Category
            entryZero.Categories.Add("Test Category");
            entryOne.Categories.Add("Test Category");
            entryThree.Categories.Add("Test Category");


            //Persist entries.
            UnitTestHelper.Create(entryZero);
            UnitTestHelper.Create(entryOne);
            UnitTestHelper.Create(entryTwo);
            UnitTestHelper.Create(entryThree);

            //Add Enclosure
            Enclosure enc = UnitTestHelper.BuildEnclosure("Nothing to see here.", "httP://blablabla.com", "audio/mp3",
                                                          entryZero.Id, 12345678, true, true);

            Enclosures.Create(enc);

            //Get EntryDay
            ICollection <EntryDay> entryList = ObjectProvider.Instance().GetBlogPostsByCategoryGroupedByDay(10, categoryId).ToList();

            var days = new EntryDay[2];

            entryList.CopyTo(days, 0);

            //Test outcome
            Assert.AreEqual(2, entryList.Count, "Expected to find two days.");

            EntryDay entries = days[1];

            Assert.AreEqual(2, entries.Count, "Expected to find two entries.");

            Assert.AreEqual(entries.First().Id, entryOne.Id, "Ordering is off.");
            Assert.AreEqual(entries.ElementAt(1).Id, entryZero.Id, "Ordering is off.");

            Assert.IsNull(entries.First().Enclosure, "Entry should not have enclosure.");
            Assert.IsNotNull(entries.ElementAt(1).Enclosure, "Entry should have enclosure.");
            UnitTestHelper.AssertEnclosures(enc, entries.ElementAt(1).Enclosure);
        }
 public void FixtureSetUp()
 {
     objectProvider = ObjectProviderFactory.CreateObjectProvider (new UniqueInstanceComponentAssembler ());
     client = objectProvider.GetInjectedObject <ClientWithFieldInjection> ();
 }
        internal void WriteObjectDefinition(ObjectProvider provider)
        {
            try
            {
                // Check to see if the company specific directory has been created yet or not, if not create it and copy all of the base configs into it
                // if it has, then we assume that the base configs are there since the copy always occurs after the directory creation
                if (!Directory.Exists(this.GetConfigPath(true)))
                {
                    this.SetupCompanyConfig(ConfigurationOption.Install);
                }

                var providerObjectDefinition = this.LoadObjectDefinitionsFromConfigs().FirstOrDefault(str => str.RootDefinition.TypeName.ToUpperInvariant() == provider.Name.ToUpperInvariant());
                string configFileName = providerObjectDefinition == null ?
                    CultureInfo.CurrentCulture.TextInfo.ToTitleCase(provider.DisplayName.ConvertToValidFileName().Replace(" ", string.Empty)) + "ObjectProvider.config" :
                    providerObjectDefinition.RootDefinition.DisplayName.ConvertToValidFileName().Replace(" ", string.Empty) + "ObjectProvider.config";

                var filePath = Path.Combine(this.GetConfigPath(false), configFileName);
                Common.ObjectDefinition objDef = new Common.ObjectDefinition();
                this.PublishPreConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.StartGeneratingProviderConfiguration, provider.Name));

                // Check to see if the object def is stored at the root, which means it is a base or version 1 definition
                if (File.Exists(filePath))
                {
                    provider.Name = Path.GetFileNameWithoutExtension(configFileName);
                    objDef = provider.ObjectDefinition;
                    this.FillObjectDef(objDef);
                }
                else
                {
                    // This is a new configuration file and we need to add the id attribute to it so the framework knows what this object provider's id is
                    XmlDocument doc = new XmlDocument();
                    XmlAttribute idAttrib = doc.CreateAttribute(CRM2011AdapterUtilities.EntityMetadataId);
                    idAttrib.Value = provider.Id.ToString();
                    TypeDefinition typeDef = new ComplexType() { ClrType = typeof(System.Collections.Generic.Dictionary<string, object>), Name = provider.Name };
                    FieldDefinition rootDef = new FieldDefinition() { DisplayName = provider.DisplayName, Name = provider.Name, TypeDefinition = typeDef, TypeName = provider.Name, AdditionalAttributes = new XmlAttribute[] { idAttrib } };
                    objDef.Types.Add(typeDef);
                    objDef.RootDefinition = rootDef;
                    this.FillObjectDef(objDef);
                }

                using (var fs = File.Create(Path.Combine(this.GetConfigPath(true), configFileName)))
                {
                    using (var xr = XmlWriter.Create(fs, new XmlWriterSettings() { Indent = true }))
                    {
                        var serializer = new XmlSerializer(typeof(ObjectDefinition));
                        serializer.Serialize(xr, objDef);
                    }
                }

                this.PublishPostConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.FinishedGeneratingProviderConfiguration, provider.Name));
            }
            catch (IOException e)
            {
                // Log any exceptions the occur and publish them to any listeners
                TraceLog.Error(string.Format(CultureInfo.InvariantCulture, Resources.ExceptionDump), e);
                this.PublishExceptionConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.ProviderConfigurationExceptionMessage, provider.Name));
            }
        }