Пример #1
0
        /// <summary>
        /// Used to process the current request.
        /// </summary>
        public override void ProcessRequest()
        {
            //Assemble page parts.
            RootElement.RemoveAll();
            GetQueryParameters();

            if (_userId == 0)
            {
                return;
            }

            var siteName = string.Empty;
            if(_siteId != 0)
            {
                siteName = InputContext.TheSiteList.GetSite(_siteId).SiteName;
            }

            var commentsListObj = new Comments(InputContext.Diagnostics, AppContext.ReaderCreator, AppContext.DnaCacheManager, InputContext.TheSiteList);

            commentsListObj.StartIndex = _startIndex;
            if (_displayContactFormPosts)
            {
                commentsListObj.FilterBy = FilterBy.ContactFormPosts;
                commentsListObj.SortDirection = SortDirection.Descending;
            }

            var CommentsList = commentsListObj.GetCommentsListByForumId(_forumId, InputContext.CurrentSite);

            string str = StringUtils.SerializeToXmlReturnAsString(CommentsList);

            var actualXml = str.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
            actualXml = actualXml.Replace(" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"BBC.Dna.Api\"","").Trim();

            //Making all the XML Nodes uppercase
            actualXml = StringUtils.ConvertXmlTagsToUppercase(actualXml);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(actualXml);
            XmlNode appendNode = doc.DocumentElement;

            if (_displayContactFormPosts)
            {
                RenderContactDetails(appendNode);
            }

            XmlAttribute newForumIdAttr = doc.CreateAttribute("FORUMID");
            newForumIdAttr.Value = _forumId.ToString();
            appendNode.Attributes.Append(newForumIdAttr);

            XmlAttribute newForumTitleAttr = doc.CreateAttribute("FORUMTITLE");
            newForumTitleAttr.Value = _forumTitle;
            appendNode.Attributes.Append(newForumTitleAttr);

            XmlAttribute newSiteNameAttr = doc.CreateAttribute("SITENAME");
            newSiteNameAttr.Value = siteName;
            appendNode.Attributes.Append(newSiteNameAttr);

            ImportAndAppend(appendNode, "");
        }
Пример #2
0
 /// <summary>
 /// Constructor
 /// </summary>
 public CommentCreateTests()
 {
     using (FullInputContext inputcontext = new FullInputContext(""))
     {
         _siteList = SiteList.GetSiteList();
         site = _siteList.GetSite("h2g2");
         _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
     }
     
 }
Пример #3
0
 public CommentsService() : base(Global.connectionString, Global.siteList, Global.dnaDiagnostics)
 {
     _commentObj = new Comments(dnaDiagnostic, readerCreator, cacheManager, Global.siteList);
     _commentObj.ItemsPerPage = itemsPerPage;
     _commentObj.StartIndex = startIndex;
     _commentObj.SignOnType = signOnType;
     _commentObj.SortBy = sortBy;
     _commentObj.SortDirection = sortDirection;
     _commentObj.FilterBy = filterBy;
     _commentObj.SummaryLength = summaryLength;
     if (bbcUidCookie != Guid.Empty)
     {
         _commentObj.BbcUid = bbcUidCookie;
     }
     _commentObj.IpAddress = _iPAddress;
     _commentObj.BasePath = ConfigurationManager.AppSettings["ServerBasePath"];
 }
Пример #4
0
        public void StartUp()
        {
            SnapshotInitialisation.ForceRestore();
            Statistics.InitialiseIfEmpty();

            using (FullInputContext inputcontext = new FullInputContext(""))
            {
                _siteList = SiteList.GetSiteList();
                site = _siteList.GetSite("h2g2");

                _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                
                ICacheManager groupsCache = new StaticCacheManager();
                var g = new UserGroups(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
                var p = new ProfanityFilter(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
                var b = new BannedEmails(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
            }
        }
        public void StartUp()
        {
            SnapshotInitialisation.RestoreFromSnapshot();
            Statistics.InitialiseIfEmpty(null,false);
            Statistics.ResetCounters();

            using (FullInputContext inputcontext = new FullInputContext(""))
            {
                using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
                {//force processpremod out...
                    reader.ExecuteDEBUGONLY("delete from siteoptions where SiteID=1 and Name='ProcessPreMod'");
                }
                _siteList = SiteList.GetSiteList();
                site = _siteList.GetSite("h2g2");

                _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                var bannedEmails = new BannedEmails(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics, CacheFactory.GetCacheManager(), null, null);//no sending signals from here
                var userGroups = new UserGroups(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics, CacheFactory.GetCacheManager(), null, null);//no sending signals from here
                var profanityFilter = new ProfanityFilter(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics, CacheFactory.GetCacheManager(), null, null);//no sending signals from here            
            }
        }
Пример #6
0
        /// <summary>
        /// Create a new comment forum
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="commentObj"></param>
        /// <param name="commentForum"></param>
        /// <param name="site"></param>
        /// <returns></returns>
        private BaseResult CreateCommentForum(string siteName, Comments commentObj, CommentForum commentForum, ISite site)
        {
            CommentForum commentForumData = commentObj.CreateAndUpdateCommentForum(commentForum, site,false);

            if (commentForumData != null && commentForumData.Id == _profileId)
            {
                string[] str = InputContext.CurrentDnaRequest.UrlReferrer.AbsoluteUri.Split('?').ToArray();

                var commentforumlistURI = str[0].Replace("moderation", siteName);
                commentforumlistURI = commentforumlistURI.Replace("twitterprofile", "commentforumlist?dnahostpageurl=" + commentForumData.ParentUri.Trim());

                return new Result("TwitterProfileCreated", String.Format("Twitter profile, {0} created successfully.", _profileId), commentforumlistURI);
            }
            else
            {
                return new Error { Type = "COMMENTFORUMCREATIONINVALIDACTION", ErrorMessage = "Comment Forum creation failed: " + _profileId };
            }
        }
Пример #7
0
        /// <summary>
        /// Twitter Profile creation on Buzz
        /// </summary>
        /// <param name="siteName"></param>
        /// <returns></returns>
        private BaseResult CreateUpdateProfileOnBuzz(string siteName)
        {
            BuzzTwitterProfile twitterProfile = null;
            var isProfileCreated = string.Empty;

            BuzzClient client;
            try
            {
                client = new BuzzClient();
                twitterProfile = new BuzzTwitterProfile();
                ISite site;

                try
                {
                    site = InputContext.TheSiteList.GetSite(siteName);

                    if (site != null)
                    {
                        twitterProfile.SiteURL = site.SiteName;
                    }
                    else
                    {
                        return new Error { Type = "SITEINVALIDACTION", ErrorMessage = String.Format("Site, '{0}' doesn't exist", siteName) };
                    }
                }
                catch (Exception exc)
                {
                    InputContext.Diagnostics.WriteExceptionToLog(exc);
                    return new Error { Type = "SITEINVALIDACTION", ErrorMessage = String.Format("Site, '{0}' doesn't exist", siteName) };
                }

                if (string.IsNullOrEmpty(_profileId) || string.IsNullOrEmpty(_title) || string.IsNullOrEmpty(_commentForumURI) || twitterUserScreenNameList.Count < 1)
                {
                    return new Error { Type = "TWITTERPROFILEMANDATORYFIELDSMISSING", ErrorMessage = "Please fill in the mandatory fields for creating/updating a profile" };
                }

                twitterProfile.ProfileId = _profileId;
                twitterProfile.Title = _title;
                twitterProfile.SearchKeywords = _searchterms.Split(',').Where(x => x != " " && !string.IsNullOrEmpty(x)).Distinct().Select(p => p.Trim()).ToList();
                
                twitterProfile.ProfileCountEnabled = _isCountsEnabled;
                twitterProfile.ProfileKeywordCountEnabled = _keywordCountsEnabled;
                twitterProfile.ModerationEnabled = _isModerationEnabled;
                twitterProfile.TrustedUsersEnabled = _isTrustedUsersEnabled;

                twitterProfile.Active = _isActive;

                var invalidTwitterName = string.Empty;

                List<string> twitterUserIds = AddValidUserToTheList(twitterUserScreenNameList, site, out invalidTwitterName);

                if (twitterUserIds != null && twitterUserIds.Count > 0)
                {
                    twitterProfile.Users = twitterUserIds;
                }
                else
                {
                    twitterProfile.Users = twitterUserScreenNameList;
                    
                    if (false == string.IsNullOrEmpty(_pageAction) && _pageAction.ToUpper().Equals("UPDATEPROFILE"))
                    {
                        CreateTwitterProfileXML(twitterProfile, _commentForumURI, true);
                        return new Error { Type = "TWITTERRETRIEVEUSERINVALIDACTIONONUPDATE", ErrorMessage = "Error while retrieving the twitter user, '" + invalidTwitterName + "'. Check if the twitter screen name entered is valid on update" };
                    }
                    else
                    {
                        CreateTwitterProfileXML(twitterProfile, _commentForumURI, false);
                        return new Error { Type = "TWITTERRETRIEVEUSERINVALIDACTIONONCREATION", ErrorMessage = "Error while retrieving the twitter user, '" + invalidTwitterName + "'. Check if the twitter screen name entered is valid" };
                    }
                }

                isProfileCreated = client.CreateUpdateProfile(twitterProfile);

                twitterProfile.Users = twitterUserScreenNameList; //Filling the xml with the screennames entered

            }
            catch (Exception ex)
            {
                twitterProfile.Users = twitterUserScreenNameList;

                CreateTwitterProfileXML(twitterProfile, _commentForumURI, false);

                InputContext.Diagnostics.WriteExceptionToLog(ex);

                return new Error { Type = "TWITTERPROFILECREATIONINVALIDACTION", ErrorMessage = String.Format("Twitter Profile, '{0}' creation failed", isProfileCreated) };
            }

            if (isProfileCreated.Equals("OK"))
            {
                //Create and map commentforum
                Comments commentObj = new Comments(dnaDiagnostic,readerCreator, AppContext.DnaCacheManager, InputContext.TheSiteList);

                CommentForum commentForum = new CommentForum();
                commentForum.isContactForm = false;
                commentForum.SiteName = siteName;
                if (false == string.IsNullOrEmpty(_commentForumURI))
                    commentForum.ParentUri = _commentForumURI; 
                else
                    commentForum.ParentUri = string.Empty;

                commentForum.Id = _profileId;
                commentForum.Title = _title;

                try
                {
                    ISite site = InputContext.TheSiteList.GetSite(siteName);
                    BaseResult result;
                    if ((string.IsNullOrEmpty(_pageAction)) || (false == _pageAction.ToLower().Equals("updateprofile")))
                    {
                        result = CreateCommentForum(siteName, commentObj, commentForum, site);
                    }
                    else
                    {
                        result = UpdateCommentForum(siteName, commentObj, site, commentForum);
                    }

                    if (!result.IsError())
                    {
                        ((Result)result).Message += " Your profile has been created, now please contact the DNA team to activate it.";
                    }

                    CreateTwitterProfileXML(twitterProfile, commentForum.ParentUri, true);

                    return result;
                }
                catch (Exception e)
                {
                    CreateTwitterProfileXML(twitterProfile, commentForum.ParentUri, true);

                    InputContext.Diagnostics.WriteExceptionToLog(e);

                    return new Error { Type = "SITEINVALIDACTION", ErrorMessage = String.Format("Site, '{0}' doesn't exist", siteName) };
                }
            }
            else
            {
                return new Error { Type = "TWITTERPROFILECREATIONINVALIDACTION", ErrorMessage = String.Format("Twitter Profile, '{0}' creation failed", isProfileCreated) };
            }
        }
Пример #8
0
        /// <summary>
        /// Get specific profile details from Buzz
        /// </summary>
        /// <param name="twitterProfileId"></param>
        /// <returns></returns>
        private BaseResult GetProfileFromBuzz(string twitterProfileId)
        {
            BuzzClient client;
            BuzzTwitterProfile twitterProfile = null;
            CommentForum commentForum = null;
            Comments commentObj = new Comments(dnaDiagnostic, readerCreator, AppContext.DnaCacheManager, InputContext.TheSiteList);
            try
            {
                client = new BuzzClient();
                twitterProfile = new BuzzTwitterProfile();
                commentForum = new CommentForum();

                //Get the twitter profile from Buzz

                twitterProfile = client.GetProfile(twitterProfileId);

                if (twitterProfile != null)
                {
                    var twitterUserIds = string.Empty;

                    if (twitterProfile.Users.Count > 0)
                    {
                        twitterUserIds = string.Join(",", twitterProfile.Users.ToArray());
                        twitterProfile.Users = GetTwitterScreenNamesFromDNA(twitterUserIds);
                    }

                    try
                    {
                        ISite site = InputContext.TheSiteList.GetSite(_siteName);

                        if (site != null)
                        {
                            commentForum = commentObj.GetCommentForumByUid(twitterProfile.ProfileId, site);

                            if (commentForum != null)
                            {
                                _commentForumURI = commentForum.ParentUri;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        InputContext.Diagnostics.WriteExceptionToLog(ex);
                    }

                    //seperate method to fill up the twitter profile xml
                    CreateTwitterProfileXML(twitterProfile, _commentForumURI, true);
                   
                    string[] str1 = InputContext.CurrentDnaRequest.UrlReferrer.AbsoluteUri.Split('?').ToArray();

                    var commentforumlistURI = string.Empty;

                    if (commentForum != null && (false == String.IsNullOrEmpty(commentForum.SiteName)) )
                    {
                        commentforumlistURI = str1[0].Replace("moderation", commentForum.SiteName);
                        commentforumlistURI = commentforumlistURI.Replace("twitterprofilelist", "commentforumlist?dnahostpageurl=" + commentForum.ParentUri.Trim());

                        return new Result("TwitterProfileRetrieved", String.Format("Twitter profile, '{0}' retrieved successfully.", twitterProfileId), commentforumlistURI);
                    }

                    return new Result("TwitterProfileRetrieved", String.Format("Twitter profile, '{0} retrieved successfully but comment forum hasn't been created yet.", twitterProfileId));
                }
                else
                {
                    return new Error { Type = "GETTWITTERPROFILEINVALIDACTION", ErrorMessage = "Twitter Profile retrieval from Buzz failed" };
                }
            }
            catch (Exception ex)
            {
                InputContext.Diagnostics.WriteExceptionToLog(ex);
                return new Error { Type = "GETTWITTERPROFILEINVALIDACTION", ErrorMessage = "Twitter Profile retrieval failed" };
            }
        }
Пример #9
0
 private void SetCharLimitTo15ForSite()
 {
     //set max char option
     using (FullInputContext inputcontext = new FullInputContext(""))
     {
         using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
         {
             reader.ExecuteDEBUGONLY("insert into siteoptions (SiteID,Section,Name,Value,Type, Description) values(" + site.SiteID.ToString() + ",'CommentForum', 'MaxCommentCharacterLength','15',0,'test MaxCommentCharacterLength value')");
             _siteList = SiteList.GetSiteList();
             _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
         }
     }
 }
Пример #10
0
 private void RemoveCharLimitForSite()
 {
     using (FullInputContext inputcontext = new FullInputContext(""))
     {
         using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
         {
             reader.ExecuteDEBUGONLY("delete from siteoptions where SiteID=" + site.SiteID.ToString() + " and Name='MaxCommentCharacterLength'");
             _siteList = new SiteList(DnaMockery.CreateDatabaseReaderCreator(), DnaDiagnostics.Default, CacheFactory.GetCacheManager(), null, null);
             _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
         }
     }
 }
Пример #11
0
        public void ThenTheDistressMessageWillAppearInTheCommentsModuleAsAReplyToTheReferredMessage()
        {
            var comments = new BBC.Dna.Api.Comments(Diagnostics.Object,
                                                    DataReaderCreator,
                                                    CacheManager.Object,
                                                    SiteList);

            //see if this comment forum already exists
            comments.SortBy = (SortBy)Enum.Parse(typeof(SortBy), SortBy);
            comments.SortDirection = (SortDirection)Enum.Parse(typeof(SortDirection), SortDirection);
            var commentForum = comments.GetCommentForumByUid(Forum.Id, Site.Object, true);
            if (commentForum != null)
            {
                foreach (var comment in commentForum.commentList.comments)
                {
                    if (comment.DistressMessage != null)
                    {
                        Assert.AreEqual("body", comment.DistressMessage.text);
                        return;
                    }
                }
            }
            Assert.Fail("No distress message found");
        }
Пример #12
0
         /// <summary>
        /// Method called to update the statuses of any of the comment forums. 
        /// </summary>
        private bool TryUpdateCommentForum()
        {
            string action = String.Empty;
            if (InputContext.TryGetParamString("dnaaction", ref action, "Action to take on this request. 'update' is the only action currently recognised"))
            {
                if (action == "create")
                {
                    string uid = String.Empty;
                    if (InputContext.DoesParamExist("dnauid", "The uid of the given comment forum."))
                    {
                        InputContext.TryGetParamString("dnauid", ref uid, "The uid of the given comment forum.");
                        if (uid == String.Empty)
                        {
                            return AddErrorXml("invalidparameters", "blank unique id provided", null);
                        }
                    }
                    else
                    {
                        //Cannot continue.
                        return AddErrorXml("invalidparameters", "No unique id provided", null);
                    }

                    string hostPageUrl = String.Empty;
                    if (InputContext.DoesParamExist("dnahostpageurl", "The url of the given comment forum."))
                    {
                        InputContext.TryGetParamString("dnahostpageurl", ref hostPageUrl, "The url of the given comment forum.");
                        if (hostPageUrl == String.Empty)
                        {
                            return AddErrorXml("invalidparameters", "blank url provided", null);
                        }
                    }
                    else
                    {
                        //Cannot continue.
                        return AddErrorXml("invalidparameters", "No url provided", null);
                    }

                    string title = String.Empty;
                    if (InputContext.DoesParamExist("dnatitle", "The title of the given comment forum."))
                    {
                        InputContext.TryGetParamString("dnatitle", ref title, "The title of the given comment forum.");
                        if (title == String.Empty)
                        {
                            return AddErrorXml("invalidparameters", "blank title provided", null);
                        }
                    }
                    else
                    {
                        //Cannot continue.
                        return AddErrorXml("invalidparameters", "No title provided", null);
                    }

                    ISite siteForForum = InputContext.CurrentSite;
                    if (InputContext.DoesParamExist("dnasitename", "The name of the dna site you want to use"))
                    {
                        string siteURLName = "";
                        if (InputContext.TryGetParamString("dnasitename", ref siteURLName, "The name of the dna site you want to use"))
                        {
                            siteForForum = InputContext.TheSiteList.GetSite(siteURLName);
                            if (siteForForum == null)
                            {
                                return AddErrorXml("invalidparameters", "invalid dna site name", null);
                            }
                        }
                    }

                    CommentForum forum = new CommentForum()
                    {
                        Id = uid,
                        ParentUri = hostPageUrl,
                        Title = title
                    };

                    Comments comments = new Comments(AppContext.TheAppContext.Diagnostics, AppContext.ReaderCreator, CacheFactory.GetCacheManager(), InputContext.TheSiteList);
                    try
                    {
                        comments.CreateCommentForum(forum, siteForForum);
                    }
                    catch(ApiException e) 
                    {
                        return AddErrorXml(e.type.ToString(), e.Message, null);
                    }


                }
                if (action == "update")
                {
                    string newCloseDateParam = String.Empty;
                    object newCloseDate = null;
                    int newModStatus = 0;
                    int newCanWrite = 0;
                    string uid = String.Empty;

                    string docUid = "The uid of the given comment forum.";
                    bool uidExists = false;
                    uidExists = InputContext.DoesParamExist("dnauid", docUid);
                    if (uidExists)
                    {
                        InputContext.TryGetParamString("dnauid", ref uid, docUid);
                        if (uid == String.Empty)
                        {
                            return AddErrorXml("invalidparameters", "blank unique id provided", null);
                        }
                    }
                    else
                    {
                        //Cannot continue.
                        return AddErrorXml("invalidparameters", "No unique id provided", null);
                    }

                    string docNewForumCloseDate = "The new CommentBoxForum Close Date for the given comment forum.";
                    bool newNewForumCloseDateExists = false;
                    newNewForumCloseDateExists = InputContext.DoesParamExist("dnanewforumclosedate", docNewForumCloseDate);
                    if (newNewForumCloseDateExists)
                    {
                        InputContext.TryGetParamString("dnanewforumclosedate", ref newCloseDateParam, docNewForumCloseDate);
                        // Try to parse the date
                        try
                        {
                            // Set the closing date from the value - The format of the date is YYYYMMDD.
                            newCloseDate = new DateTime(Convert.ToInt32(newCloseDateParam.Substring(0, 4)), Convert.ToInt32(newCloseDateParam.Substring(4, 2).TrimStart('0')), Convert.ToInt32(newCloseDateParam.Substring(6, 2).TrimStart('0')));
                        }
                        catch (Exception ex)
                        {
                            return AddErrorXml("invalidparameters", "Invalid date format given for forumclosedate. " + ex.Message, null);
                        }
                    }

                    string docNewModStatus = "The new Moderation Status for the given comment forum.";
                    bool newModStatusExists = false;
                    newModStatusExists = InputContext.DoesParamExist("dnanewmodstatus", docNewModStatus);
                    if (newModStatusExists)
                    {
                        string dnaNewModStatus = InputContext.GetParamStringOrEmpty("dnanewmodstatus", docNewModStatus);
                        if (dnaNewModStatus == "reactive")
                        {
                            newModStatus = 1;
                        }
                        else if (dnaNewModStatus == "postmod")
                        {
                            newModStatus = 2;
                        }
                        else if (dnaNewModStatus == "premod")
                        {
                            newModStatus = 3;
                        }
                        else
                        {
                            return AddErrorXml("invalidparameters", "Illegal New Moderation Status setting (" + dnaNewModStatus + ")", null);
                        }
                    }
                    int fastModStatus = 0;
                    bool newFastModStatusExists = InputContext.DoesParamExist("dnafastmod", "");
                    if (newFastModStatusExists)
                    {
                        var fastModVal = InputContext.GetParamStringOrEmpty("dnafastmod", "");
                        if (fastModVal.ToUpper() == "ENABLED")
                        {
                            fastModStatus = 1;
                        }
                        else
                        {
                            fastModStatus = 0;
                        }
                    }

                    string docNewCanWrite = "The new Open Close Status for the given comment forum.";
                    bool newNewCanWriteExists = false;
                    newNewCanWriteExists = InputContext.DoesParamExist("dnanewcanwrite", docNewCanWrite);
                    if (newNewCanWriteExists)
                    {
                        newCanWrite = InputContext.GetParamIntOrZero("dnanewcanwrite", docNewCanWrite);
                    }

                    #region Anonymous Posting

                    int forumId = 0;
                    if (InputContext.DoesParamExist("forumid", "Forum ID"))
                    {
                        forumId = InputContext.GetParamIntOrZero("forumid", "Forum ID");
                    }

                    bool anonymousPostingStatusExists = false;
                    anonymousPostingStatusExists = InputContext.DoesParamExist("dnaanonymoussetting", "");
                    if (anonymousPostingStatusExists && forumId != 0)
                    {
                        var anonPostVal = InputContext.GetParamStringOrEmpty("dnaanonymoussetting", "");
                        if (anonPostVal.ToUpper() == "ALLOW")
                        {
                            if (InputContext.TheSiteList.GetSiteOptionValueBool(InputContext.CurrentSite.SiteID, "CommentForum", "AllowNotSignedInCommenting"))
                            {
                                var user = new Dna.Users.User(AppContext.ReaderCreator, AppContext.TheAppContext.Diagnostics, AppContext.DnaCacheManager);
                                user.CreateAnonymousUserForForum(InputContext.CurrentSite.SiteID, forumId, "");
                            }
                        }
                    }

                    #endregion

                    if (newNewForumCloseDateExists || newModStatusExists || newNewCanWriteExists || newFastModStatusExists)
                    {

                        using (IDnaDataReader dataReader = InputContext.CreateDnaDataReader("updatecommentforumstatus"))
                        {
                            dataReader.AddParameter("uid", uid);

                            if (newNewForumCloseDateExists && newCloseDate != null)
                            {
                                dataReader.AddParameter("forumclosedate", newCloseDate);
                            }
                            else
                            {
                                dataReader.AddParameter("forumclosedate", DBNull.Value);
                            }

                            if (newModStatusExists)
                            {
                                dataReader.AddParameter("modstatus", newModStatus);
                            }
                            else
                            {
                                dataReader.AddParameter("modstatus", DBNull.Value);
                            }
                            if (newNewCanWriteExists)
                            {
                                dataReader.AddParameter("canwrite", newCanWrite);
                            }
                            else
                            {
                                dataReader.AddParameter("canwrite", DBNull.Value);
                            }
                            if (newFastModStatusExists)
                            {
                                dataReader.AddParameter("fastmod", fastModStatus);
                            }
                            else
                            {
                                dataReader.AddParameter("fastmod", DBNull.Value);
                            }
                            dataReader.Execute();
                        }
                    }
                }
            }

            return true;
        }
Пример #13
0
        public void CommentCreate_CommentOnEmergencyClosedSite()
        {
            //create comments objects

            _comments.CallingUser = new CallingUser(SignInSystem.DebugIdentity, null, null, null, TestUserAccounts.GetNormalUserAccount.UserName, _siteList);
            _comments.CallingUser.IsUserSignedInSecure(TestUtils.TestUserAccounts.GetNormalUserAccount.Cookie, TestUtils.TestUserAccounts.GetNormalUserAccount.SecureCookie, site.IdentityPolicy, site.SiteID, null, Guid.Empty);
            var callingUser = _comments.CallingUser;
            //set up test data
            CommentInfo comment = new CommentInfo
            {
                text = "this is a nunit generated comment."
            };
            comment.text += Guid.NewGuid().ToString();//have to randomize the string to post

            string IPAddress = String.Empty;
            Guid BBCUid = Guid.NewGuid();
            string commentForumID = "testCommentForum" + Guid.NewGuid().ToString();
            
            CommentForum commentForum = CommentForumCreate(commentForumID);

            try
            {//turn the site into emergency closed mode
                _siteList.GetSite(site.ShortName).IsEmergencyClosed = true;
                using (var inputcontext = new FullInputContext(""))
                {
                    _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator,
                                             CacheFactory.GetCacheManager(), _siteList);
                    _comments.CallingUser = callingUser;
                }
                CommentInfo result = _comments.CreateComment(commentForum, comment);
            }
            catch (ApiException ex)
            {
                Assert.AreEqual(ErrorType.SiteIsClosed, ex.type);
            }
            finally
            {//reset the site into emergency closed mode
                _siteList.GetSite(site.ShortName).IsEmergencyClosed = false;
            }
        }
Пример #14
0
        /// <summary>
        /// Creates a comment on a rating for a particular rating forum
        /// </summary>
        /// <param name="RatingForum">The forum to post to</param>
        /// <param name="int">The thread to add the comment to</param>
        /// <param name="comment">The comment to add</param>
        /// <returns>The created comment object</returns>
        public CommentInfo RatingCommentCreate(RatingForum ratingForum, int threadID, CommentInfo comment)
        {
            ISite site = SiteList.GetSite(ratingForum.SiteName);

            Comments commentsObj = new Comments(DnaDiagnostics, DnaDataReaderCreator, CacheManager, SiteList);
            commentsObj.CallingUser = CallingUser;
            commentsObj.BbcUid = BbcUid;
            commentsObj.IpAddress = IpAddress;

            CommentInfo createdRatingComment = commentsObj.CommentReplyCreate((Forum)ratingForum, threadID, comment);

            return createdRatingComment;
        }
        public void CommentForum_SiteEmergencyClose()
        {
            try
            {
                CommentForum commentForum = new CommentForum
                {
                    Id = Guid.NewGuid().ToString(),
                    ParentUri = "http://www.bbc.co.uk/dna/h2g2/",
                    Title = "testCommentForum"
                };

                CommentForum result = _comments.CreateCommentForum(commentForum, site);
                Assert.IsTrue(result != null);
                Assert.IsTrue(result.Id == commentForum.Id);
                Assert.IsTrue(result.ParentUri == commentForum.ParentUri);
                Assert.IsTrue(result.Title == commentForum.Title);
                Assert.IsTrue(result.commentSummary.Total == 0);

                //add a comment 
                CommentInfo comment = new CommentInfo { text = "this is a nunit generated comment." + Guid.NewGuid().ToString() };
                //normal user
                _comments.CallingUser = new CallingUser(SignInSystem.DebugIdentity, null, null, null, TestUserAccounts.GetNormalUserAccount.UserName, _siteList);
                _comments.CallingUser.IsUserSignedInSecure(TestUserAccounts.GetNormalUserAccount.Cookie, TestUserAccounts.GetNormalUserAccount.SecureCookie, site.IdentityPolicy, site.SiteID, null, Guid.Empty);
                _comments.CreateComment(result, comment);

                //get forum again
                result = _comments.GetCommentForumByUid(result.Id, site);
                Assert.IsTrue(result != null);
                Assert.IsTrue(result.Id == commentForum.Id);
                Assert.IsTrue(result.ParentUri == commentForum.ParentUri);
                Assert.IsTrue(result.Title == commentForum.Title);
                Assert.IsTrue(result.commentSummary.Total == 1);

                //close site
                _siteList.GetSite(site.ShortName).IsEmergencyClosed = true;
                using (FullInputContext inputcontext = new FullInputContext(""))
                {
                    _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                    
                }

                result = _comments.GetCommentForumByUid(result.Id, site);
                Assert.IsTrue(result != null);
                Assert.IsTrue(result.isClosed);

                //reopen site
                _siteList.GetSite(site.ShortName).IsEmergencyClosed = false;
            }
            finally
            {
                _siteList.GetSite(site.ShortName).IsEmergencyClosed = false;
                using (FullInputContext inputcontext = new FullInputContext(""))
                {
                    _siteList = SiteList.GetSiteList();
                    site = _siteList.GetSite("h2g2");
                    _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// If comment forum exists, then update an existing comment forum 
        /// Else create a new comment forum
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="commentObj"></param>
        /// <param name="site"></param>
        /// <param name="createCommentForum"></param>
        /// <returns></returns>
        private BaseResult UpdateCommentForum(string siteName, Comments commentObj, ISite site, CommentForum createCommentForum)
        {
            CommentForum commentForumUpdateData = commentObj.GetCommentForumByUid(_profileId, site);

            if (commentForumUpdateData != null)
            {
                commentForumUpdateData.ParentUri = _commentForumURI;
                commentForumUpdateData.Title = _title;
                commentForumUpdateData = commentObj.CreateAndUpdateCommentForum(commentForumUpdateData, site, false);

                if (commentForumUpdateData != null && commentForumUpdateData.Id == _profileId)
                {
                    string[] str = InputContext.CurrentDnaRequest.UrlReferrer.AbsoluteUri.Split('?').ToArray();

                    var commentforumlistURI = str[0].Replace("moderation", siteName);
                    commentforumlistURI = commentforumlistURI.Replace("twitterprofile", "commentforumlist?dnauid=" + commentForumUpdateData.Id.Trim());

                    return new Result("TwitterProfileUpdated", String.Format("Twitter profile, {0} updated successfully.", _profileId), commentforumlistURI);
                }
                else
                {
                    return new Error { Type = "COMMENTFORUMUPDATEINVALIDACTION", ErrorMessage = "Comment Forum update failed: " + _profileId };
                }
            }
            else
            {
                return CreateCommentForum(siteName, commentObj, createCommentForum, site);
            }
        }
Пример #17
0
        public void CommentCreate_WithCharLimit()
        {
            try
            {
                //set max char option
                using (FullInputContext inputcontext = new FullInputContext(""))
                {
                    using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
                    {
                        reader.ExecuteDEBUGONLY("insert into siteoptions (SiteID,Section,Name,Value,Type, Description) values(" + site.SiteID.ToString() + ",'CommentForum', 'MaxCommentCharacterLength','15',0,'test MaxCommentCharacterLength value')");
                        _siteList = SiteList.GetSiteList();
                        _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                    }
                }
                string commentForumID = "good" + Guid.NewGuid().ToString();
                CommentForum commentForum = CommentForumCreate(commentForumID);
                //set up test data
                CommentInfo comment = new CommentInfo{text = Guid.NewGuid().ToString().Substring(0,10)};
                //normal user
                _comments.CallingUser = new CallingUser(SignInSystem.DebugIdentity, null, null, null, TestUserAccounts.GetNormalUserAccount.UserName, _siteList);
                _comments.CallingUser.IsUserSignedInSecure(TestUtils.TestUserAccounts.GetNormalUserAccount.Cookie, TestUtils.TestUserAccounts.GetNormalUserAccount.SecureCookie, site.IdentityPolicy, site.SiteID, null, Guid.Empty);
                CommentInfo result = _comments.CreateComment(commentForum, comment);//should pass successfully
                Assert.IsTrue(result != null);
                Assert.IsTrue(result.ID > 0);
                Assert.IsTrue(result.text == comment.text);

                //with some markup
                comment.text = String.Format("<div><b><i><u>{0}</u></i></b></div>", Guid.NewGuid().ToString().Substring(0, 10));
                result = _comments.CreateComment(commentForum, comment);//should pass successfully
                Assert.IsTrue(result != null);
                Assert.IsTrue(result.ID > 0);
                Assert.IsTrue(result.text == comment.text);

                //string too large with html
                comment.text = String.Format("<div><b><i><u>{0}</u></i></b></div>", "stringtopad".PadRight(20));
                try
                {
                    result = _comments.CreateComment(commentForum, comment);
                }
                catch (ApiException ex)
                {
                    Assert.IsTrue(ex.type == ErrorType.ExceededTextLimit);
                }

                //string too large without html
                comment.text = String.Format("{0}", "stringtopad".PadRight(20));
                try
                {
                    result = _comments.CreateComment(commentForum, comment);
                }
                catch (ApiException ex)
                {
                    Assert.IsTrue(ex.type == ErrorType.ExceededTextLimit);
                }
            }
            finally 
            {
                using (FullInputContext inputcontext = new FullInputContext(""))
                {
                    using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
                    {
                        reader.ExecuteDEBUGONLY("delete from siteoptions where SiteID=" + site.SiteID.ToString() + " and Name='MaxCommentCharacterLength'");
                        _siteList = new SiteList(DnaMockery.CreateDatabaseReaderCreator(), DnaDiagnostics.Default, CacheFactory.GetCacheManager(), null, null);
                        _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                    }
                }
            }
        }
Пример #18
0
 /// <summary>
 /// Returns last update for given forum
 /// </summary>
 /// <param name="uid"></param>
 /// <param name="siteID"></param>
 /// <returns></returns>
 public DateTime RatingForumGetLastUpdate(object[] args)
 {
     string uid = (string)args[0];
     int siteID = (int)args[1];
     Comments commentsObj = new Comments(DnaDiagnostics, DnaDataReaderCreator, CacheManager, SiteList);
     commentsObj.CallingUser = CallingUser;
     commentsObj.BbcUid = BbcUid;
     commentsObj.IpAddress = IpAddress;
     return commentsObj.CommentForumGetLastUpdate(uid, siteID);
 }
Пример #19
0
        public void CommentCreate_PreModSiteWithProcessPreMod()
        {

            using (FullInputContext inputcontext = new FullInputContext(""))
            {
                using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
                {
                    reader.ExecuteDEBUGONLY("update sites set premoderation=1 where siteid=" + site.SiteID.ToString());//set premod
                    reader.ExecuteDEBUGONLY("insert into siteoptions (SiteID,Section,Name,Value,Type, Description) values(" + site.SiteID.ToString() +",'Moderation', 'ProcessPreMod','1',1,'test premod value')");

                    
                }
                _siteList = SiteList.GetSiteList();
                site = _siteList.GetSite("h2g2");
                _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), inputcontext.SiteList);
            }

            try
            {

                //set up test data
                CommentInfo comment = new CommentInfo
                {
                    text = "this is a nunit generated comment."
                };
                comment.text += Guid.NewGuid().ToString();//have to randomize the string to post

                string IPAddress = String.Empty;
                Guid BBCUid = Guid.NewGuid();
                string commentForumID = "testCommentForum" + Guid.NewGuid().ToString();

                CommentForum commentForum = CommentForumCreate(commentForumID, ModerationStatus.ForumStatus.Unknown);//should override this with the site value
                //normal user
                _comments.CallingUser = new CallingUser(SignInSystem.DebugIdentity, null, null, null, TestUserAccounts.GetNormalUserAccount.UserName, _siteList);
                _comments.CallingUser.IsUserSignedInSecure(TestUtils.TestUserAccounts.GetNormalUserAccount.Cookie, TestUtils.TestUserAccounts.GetNormalUserAccount.SecureCookie, site.IdentityPolicy, site.SiteID, null, Guid.Empty);

                CommentInfo result = _comments.CreateComment(commentForum, comment);

                Assert.IsTrue(result != null);
                Assert.IsTrue(result.ID == 0);//should be have no post ID
                Assert.IsTrue(result.text == "This post is awaiting moderation.");

                //check if post in PreModPostings queue table
                using (FullInputContext inputcontext = new FullInputContext(""))
                {
                    using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
                    {
                        reader.ExecuteDEBUGONLY("select top 1 * from PreModPostings where dateposted > DATEADD(mi, -1, getdate())");//must be within 2 mins of post date
                        if (!reader.Read() || !reader.HasRows)
                        {
                            Assert.Fail("Post not in ThreadMod PreModPostings and moderation queue");
                        }
                    }
                }
            }
            finally 
            { 
                //reset h2g2 site
                using (FullInputContext inputcontext = new FullInputContext(""))
                {
                    using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
                    {
                        reader.ExecuteDEBUGONLY("update sites set premoderation=0 where siteid=" + site.SiteID.ToString());//set premod
                        reader.ExecuteDEBUGONLY("delete from siteoptions where SiteID=" + site.SiteID.ToString() + " and Name='ProcessPreMod'");
                    }
                    _siteList = new SiteList(DnaMockery.CreateDatabaseReaderCreator(), DnaDiagnostics.Default, CacheFactory.GetCacheManager(), null, null);
                    site = _siteList.GetSite("h2g2");
                    _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Creates a rating for the given rating forum
        /// </summary>
        /// <param name="RatingForum">The forum to post to</param>
        /// <param name="rating">The rating to add</param>
        /// <returns>The created rating object</returns>
        public RatingInfo RatingCreate(RatingForum RatingForum, RatingInfo rating)
        {
            ISite site = SiteList.GetSite(RatingForum.SiteName);
            //check for repeat posting
            ValidateRating(RatingForum, rating, site);

            Comments commentsObj = new Comments(DnaDiagnostics, DnaDataReaderCreator, CacheManager, SiteList);
            commentsObj.CallingUser = CallingUser;
            commentsObj.BbcUid = BbcUid;
            commentsObj.IpAddress = IpAddress;


            //create the thread entry
            RatingInfo createdRating = (RatingInfo)commentsObj.CreateComment((Forum)RatingForum, (CommentInfo)rating);
            using (var reader = CreateReader("ratingscreate"))
            {
                reader.AddParameter("entryid", createdRating.ID);
                reader.AddParameter("uid", RatingForum.Id);
                reader.AddParameter("rating", rating.rating);
                reader.AddParameter("userid", CallingUser.UserID);
                reader.AddParameter("siteid", site.SiteID);
                reader.Execute();
            }
            createdRating.rating = rating.rating;
            return createdRating;
        }
Пример #21
0
        public void GivenIHaveAnCommentInTheReferalQueue()
        {
            //To get to this stage we need:-
            //1. Create a comment forum (make it pre-mod)
            //2. Add at least 2 posts
            //3. Refer the first post
            //  a) for a post to be referred it should be in the mod queue (so - make the comment forum pre-mod
            //Let's not make a web request if possible - we'll need the databse though
            //SnapshotInitialisation.RestoreFromSnapshot(); //TODO: SnapshotInitialisation should not depend on IIS at all. 
            //Whatever info is required should be injected.
            //TODO: get this from config
            string connectionString =
                @"database=smallGuide; server=.\MSSQL2008R2; user id=sa; password=Thanatos99; pooling=false";
            
            DataReaderCreator = new DnaDataReaderCreator(connectionString, Diagnostics.Object);

            SiteList = new SiteList(DataReaderCreator,
                                    Diagnostics.Object,
                                    CacheManager.Object,
                                    RipleyServerAddresses,
                                    DotNetServerAddresses);

            var comments = new BBC.Dna.Api.Comments(Diagnostics.Object,
                                                    DataReaderCreator,
                                                    CacheManager.Object,
                                                    SiteList);

            Forum = new Forum();
            Forum.Id = "distress-message-fun-and-games";
            Forum.ParentUri = "http://www.bbc.co.uk/dna/h2g2";
            Forum.Title = "distress-message-fun-and-games";

            Forum.ModerationServiceGroup = ModerationStatus.ForumStatus.PostMod;
            
            Site.Setup(x => x.SiteID).Returns(1);
            Site.Setup(x => x.SiteName).Returns("h2g2");

            //see if this comment forum already exists
            var commentForum = comments.GetCommentForumByUid(Forum.Id, Site.Object, true);
            if (commentForum == null)
            {
                commentForum = comments.CreateCommentForum(Forum, Site.Object);
            }
            //save the forumid for later in the test
            CommentForumId = commentForum.ForumID;

            //if we have less than 2 comments we need to get up to 2
            int commentCount = commentForum.commentList.TotalCount;
            while (commentCount < 2)
            {
                //Ok this is what I want to do but...
                //commentForum.Post(new Comment(...));
                //TODO: can we add this method through a good refactor
                var commentInfo = new CommentInfo();
                commentInfo.text = "Simple comment text " + commentCount.ToString();
                
                var callingUser = new Mock<ICallingUser>();
                callingUser.Setup(x => x.UserID).Returns(TestUserAccounts.GetNormalUserAccount.UserID);
                callingUser.Setup(x => x.IsSecureRequest).Returns(true);
                comments.CallingUser = callingUser.Object;
                
                var info = comments.CreateComment(commentForum, commentInfo);

                commentCount++;
            }
        }