Exemplo n.º 1
0
        private void LoadControl()
        {
            SliderTopic result = new SliderTopic();
            TabTopicDisplayCollection listTabTopicDisplay = TabTopicDisplayCollection.GetTabTopicDisplayCollection();
            var    sliderTopic = listTabTopicDisplay.Where(item => item.DataId == Portlet.PortletInstance.Id).FirstOrDefault();
            string topicid1;
            string topicid2;

            if (sliderTopic != null)
            {
                result.TopicId1 = sliderTopic.TopicId;
                topicid1        = result.TopicId1.ToString();
                Topic topic = TopicCollection.GetTopic(topicid1 != "" ? topicid1 : "");
                result.TopicName1        = topic.Name;
                result.SliderArticleList = ArticleCollection.GetArticleCollection(sliderTopic.TopicId.ToString(), 0, sliderTopic.NumberDisplay);
                result.SliderArticleList.ForEach(d => d.Name = d.GetDescription().Replace("\"", "\\\""));
            }
            var secondTopic = listTabTopicDisplay.Where(item => item.DataId == Portlet.PortletInstance.Id).Skip(1).Take(1).SingleOrDefault();

            if (secondTopic != null)
            {
                result.TopicId2 = secondTopic.TopicId;
                topicid2        = result.TopicId2.ToString();
                Topic topic = TopicCollection.GetTopic(topicid2 != "" ? topicid2 : "");
                result.TopicName2        = topic.Name;
                result.SecondArticleList = ArticleCollection.GetArticleCollection(secondTopic.TopicId.ToString(), 0, secondTopic.NumberDisplay).Take(3).ToList();
            }
            var js = new JavaScriptSerializer();

            ListArticle = js.Serialize(result);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            /* TO DO: actualizar el nombre del servicio y el path al archivo mdf */
            string dbConnectionString = @"Data Source=.\SQLEXPRESS"
                                        + @";AttachDbFilename=""C:\bbdd\BD2012C.mdf"""
                                        + @";Integrated Security=True;Connect Timeout=30;User Instance=True";

            /* TO DO: instanciar el motor de búsqueda */
            RAI.SearchEngine.ISearchEngine engine = new MotorOkapiBM25F();

            /* TO DO: cambiar rutas a colección y topics */
            DocumentCollection docCol = new DocumentCollection(@"C:\data\2012-documents.biased.tar");
            TopicCollection    topCol = new TopicCollection(@"C:\data\2012-topics.xml");

            // 1. Indexar colección (SÓLO UNA VEZ!)
            //engine.BuildIndex(dbConnectionString, docCol);

            // 2. Hacer consultas
            List <IRun <IListResult> > runs = new List <IRun <IListResult> >();

            foreach (var topic in topCol)
            {
                runs.Add(engine.RunModulo1(dbConnectionString, docCol, topic));
                // 2.1. Opcional: mostrar resultados por pantalla, snippets, etc.
            }
            Formatter formatter = new Formatter();

            formatter.Write(runs, @"C:\data\2012_" + engine.Name + ".run");
        }
Exemplo n.º 3
0
        protected override void Render(HtmlTextWriter writer)
        {
            RssChannel channel = new RssChannel();

            TopicCollection topics = RepositoryRegistry.TopicRepository.FindByForumId(forumID);

            foreach (Topic topic in topics)
            {
                RssItem item = new RssItem();
                item.Title       = topic.Name;
                item.Description = topic.Name;
                item.PubDate     = DateTime.Now.ToUniversalTime();
                item.Author      = topic.Author.Name;
                item.Link        = new Uri(ForumApplication.Instance.GetLink(SharePointForumControls.ViewMessages, "topic={0}", topic.Id));
                channel.Items.Add(item);
            }

            channel.Title         = ForumApplication.Instance.Title;
            channel.Description   = ForumApplication.Instance.Title;
            channel.LastBuildDate = channel.Items.LatestPubDate();
            channel.Link          = new Uri(ForumApplication.Instance.BasePath);

            RssFeed feed = new RssFeed();

            feed.Channels.Add(channel);

            Page.Response.Clear();
            Page.Response.ContentType = "text/xml";
            feed.Write(Page.Response.OutputStream);
            Page.Response.End();
        }
Exemplo n.º 4
0
        protected void LoadData()
        {
            Topic  topic    = new Topic();
            string topicId  = Page.RouteData.Values["TopicId1"] != null ? Page.RouteData.Values["TopicId1"].ToString() : Request.QueryString["TopicId"];
            string topicId2 = Page.RouteData.Values["TopicId2"] != null ? Page.RouteData.Values["TopicId2"].ToString() : Request.QueryString["TopicId2"];

            if (topicId2 != null)
            {
                topicId = topicId2;
            }
            if (topicId == null)
            {
                return;
            }
            int index = topicId.IndexOf("/");

            if (index > 0)
            {
                topicId = topicId.Substring(0, index);
            }
            topic     = TopicCollection.GetTopic(topicId);
            TopicName = topic.Name;
            TopicId   = topic.Id.ToString();
            if (ListArticle.Count() <= 10)
            {
                pnPager.Visible = false;
            }
            IEnumerable <Article> ilist = ListArticle.Skip(CurrentPage * RPP);

            ilist = ilist.Take(CurrentPage * RPP + RPP > TotalRecord ? TotalRecord % RPP : RPP);
            RadListView1.DataSource = ilist;
            RadListView1.DataBind();
            UserLogin.TopicId = topicId;
        }
Exemplo n.º 5
0
 private void WriteTopic(XmlWriter writer, TopicCollection topicsList)
 {
     foreach (var topic in topicsList)
     {
         WriteTopic(writer, topic);
     }
 }
Exemplo n.º 6
0
        protected void BindGrid()
        {
            TopicCollection topics = TopicManager.GetAllTopics();

            gvTopics.DataSource = topics;
            gvTopics.DataBind();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Gets all topics
        /// </summary>
        /// <returns>topic collection</returns>
        public static TopicCollection GetAllTopics()
        {
            DBTopicCollection dbCollection = DBProviderManager <DBTopicProvider> .Provider.GetAllTopics();

            TopicCollection collection = DBMapping(dbCollection);

            return(collection);
        }
Exemplo n.º 8
0
        protected override void CreateChildControls()
        {
            Controls.Add(BuildPageLinks("Todays Topics", ""));
            TopicCollection topics = RepositoryRegistry.TopicRepository.FindByDate(DateTime.Now);

            StartTopicTable();
            DisplayTopics(topics);
            EndTopicTable();
        }
Exemplo n.º 9
0
        protected override void CreateChildControls()
        {
            Controls.Add(BuildPageLinks("Inactive Topics", ""));
            TopicCollection topics = RepositoryRegistry.TopicRepository.FindInactive();

            StartTopicTable();
            DisplayTopics(topics);
            EndTopicTable();
        }
Exemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of <see cref="BaseWampHost"/>.
 /// </summary>
 /// <param name="messageProvider">Message provider used for WAMP message JSON serialization/deserialization</param>
 /// <param name="typeResolver">Resolver used for converting deserialized JSON object into specific type instances</param>
 protected BaseWampHost(Uri listeningUri, IMessageProvider messageProvider, ITypeResolver typeResolver)
 {
     AddressUri = listeningUri;
     MessageProvider = messageProvider;
     Topics = new TopicCollection();
     ResponseQueue = new SocketResponseQueue();
     Scheduler = new ProcedureScheduler(ResponseQueue, typeResolver);
     Sessions = new DictionarySessionContainer();
     Procedures = new Dictionary<string, ProcedureDefinition>();
 }
Exemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of <see cref="BaseWampHost"/>.
 /// </summary>
 /// <param name="messageProvider">Message provider used for WAMP message JSON serialization/deserialization</param>
 /// <param name="typeResolver">Resolver used for converting deserialized JSON object into specific type instances</param>
 protected BaseWampHost(Uri listeningUri, IMessageProvider messageProvider, ITypeResolver typeResolver)
 {
     AddressUri      = listeningUri;
     MessageProvider = messageProvider;
     Topics          = new TopicCollection();
     ResponseQueue   = new SocketResponseQueue();
     Scheduler       = new ProcedureScheduler(ResponseQueue, typeResolver);
     Sessions        = new DictionarySessionContainer();
     Procedures      = new Dictionary <string, ProcedureDefinition>();
 }
Exemplo n.º 12
0
 private void WriteTopics(StringBuilder sb, TopicCollection topicCollection)
 {
     foreach (Topic topic in topicCollection)
     {
         LocalizedTopic localizedTopic = TopicManager.GetLocalizedTopic(topic.TopicId, NopContext.Current.WorkingLanguage.LanguageId);
         if (localizedTopic != null)
         {
             sb.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", SEOHelper.GetTopicUrl(localizedTopic.TopicId, localizedTopic.Title), (String.IsNullOrEmpty(localizedTopic.Title) ? localizedTopic.TopicId.ToString() : Server.HtmlEncode(localizedTopic.Title)));
         }
     }
 }
    public void SetTopic_Indexer_ReturnsTopic() {

      var topics = new TopicCollection();

      for (var i = 0; i < 10; i++) {
        topics.Add(TopicFactory.Create("Topic" + i, "Page"));
      }

      Assert.AreEqual<string>("Topic3", topics["Topic3"].Key);

    }
Exemplo n.º 14
0
        public TopicCollection FindInactive()
        {
            SharePointListDescriptor listItems = Provider.GetListItemsByField(
                ForumConstants.Lists_Topics, "NumPosts", "1");
            TopicCollection topics = new TopicCollection();

            foreach (SharePointListItem item in listItems.SharePointListItems)
            {
                topics.Add(TopicMapper.CreateDomainObject(item));
            }
            return(topics);
        }
Exemplo n.º 15
0
        public TopicCollection FindByDate(DateTime dateCriteria)
        {
            string isoDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(dateCriteria);
            SharePointListDescriptor listItems = Provider.GetListItemsByField(ForumConstants.Lists_Topics, "Modified", isoDate);
            TopicCollection          topics    = new TopicCollection();

            foreach (SharePointListItem item in listItems.SharePointListItems)
            {
                topics.Add(TopicMapper.CreateDomainObject(item));
            }
            return(topics);
        }
Exemplo n.º 16
0
        public void TopicCollection_MaxLevel()
        {
            // Arrange
            var maxLevel = Fixture.Create <int>();

            // Act
            var collection = new TopicCollection(maxLevel);

            // Assert
            collection.MaxLevel.Should()
            .Be(maxLevel, "because the provided value should be the upper bound");
        }
Exemplo n.º 17
0
        public TopicCollection FindByForumId(int id)
        {
            TopicCollection topicCollection = new TopicCollection();

            SharePointListDescriptor descriptor = Provider.GetListItemsByField(ForumConstants.Lists_Topics, "ForumID", id.ToString());

            foreach (SharePointListItem listItem in descriptor.SharePointListItems)
            {
                topicCollection.Add(TopicMapper.CreateDomainObject(listItem));
            }

            return(topicCollection);
        }
Exemplo n.º 18
0
        public static TopicCollection SelectAll()
        {
            TopicCollection List = new TopicCollection();

            using (IDataReader rd = SqlHelper.ExecuteReader(DAL.con(), CommandType.StoredProcedure, "tblRss_sp_tblRssTopic_Select_SelectAll_linhnx"))
            {
                while (rd.Read())
                {
                    List.Add(getFromReader(rd));
                }
            }
            return(List);
        }
Exemplo n.º 19
0
        public TopicCollection GetAll()
        {
            TopicCollection topicCollection = new TopicCollection();

            SharePointListDescriptor descriptor = Provider.GetAllListItems(ForumConstants.Lists_Topics);

            foreach (SharePointListItem listItem in descriptor.SharePointListItems)
            {
                topicCollection.Add(TopicMapper.CreateDomainObject(listItem));
            }

            return(topicCollection);
        }
    public void Constructor_IEnumerable_SeedsTopics() {

      var topics = new List<Topic>();

      for (var i = 0; i < 10; i++) {
        topics.Add(TopicFactory.Create("Topic" + i, "Page"));
      }

      var topicsCollection = new TopicCollection(topics);

      Assert.AreEqual<int>(10, topicsCollection.Count);

    }
Exemplo n.º 21
0
        public void AddTopic_OnBlankTopic()
        {
            // Arrange
            ITopicCollection collection = new TopicCollection(Fixture.Create <int>());

            // Act
            Action appendingEmptyTopic = () =>
                                         collection.AddTopic(string.Empty);

            // Assert
            appendingEmptyTopic.Should()
            .Throw <EmptyTopicException>("because an empty topic is not a valid one to be added");
        }
    public void AsReadOnly_ReturnsReadOnlyTopicCollection() {

      var topics = new TopicCollection();

      for (var i = 0; i < 10; i++) {
        topics.Add(TopicFactory.Create("Topic" + i, "Page"));
      }

      var readOnlyCollection = topics.AsReadOnly();

      Assert.AreEqual<int>(10, readOnlyCollection.Count);
      Assert.AreEqual<string>("Topic0", readOnlyCollection.First().Key);

    }
Exemplo n.º 23
0
        private static TopicCollection DBMapping(DBTopicCollection dbCollection)
        {
            if (dbCollection == null)
                return null;

            TopicCollection collection = new TopicCollection();
            foreach (DBTopic dbItem in dbCollection)
            {
                Topic item = DBMapping(dbItem);
                collection.Add(item);
            }

            return collection;
        }
Exemplo n.º 24
0
        public void AddTopic_OnTopicSeparator()
        {
            // Arrange
            ITopicCollection collection = new TopicCollection(Fixture.Create <int>());

            // Act
            Action appendingTopic = () =>
                                    collection.AddTopic(
                Mqtt.Topic.Separator.ToString());

            // Assert
            appendingTopic.Should()
            .Throw <InvalidTopicException>("because the topic separator is not a valid topic to be appended");
        }
Exemplo n.º 25
0
        public static TopicCollection SelectTopByHot(int Top)
        {
            TopicCollection List = new TopicCollection();

            SqlParameter[] obj = new SqlParameter[1];
            obj[0] = new SqlParameter("Top", Top);
            using (IDataReader rd = SqlHelper.ExecuteReader(DAL.con(), CommandType.StoredProcedure, "tblRss_sp_tblRssTopic_Select_SelectTopByHot_linhnx", obj))
            {
                while (rd.Read())
                {
                    List.Add(getFromReader(rd));
                }
            }
            return(List);
        }
Exemplo n.º 26
0
        //=====================================================================
        /// <summary>
        /// Constructor
        /// </summary>
        public Topic()
        {
            contentId = Guid.NewGuid().ToString();
            subtopics = new TopicCollection(null);
            helpAttributes = new MSHelpAttrCollection(null);
            keywords = new MSHelpKeywordCollection();
            this.Visible = true;

            subtopics.ListChanged += new ListChangedEventHandler(
                childList_ListChanged);
            helpAttributes.ListChanged += new ListChangedEventHandler(
                childList_ListChanged);
            keywords.ListChanged += new ListChangedEventHandler(
                childList_ListChanged);
        }
Exemplo n.º 27
0
 protected void DisplayTopics(TopicCollection topics)
 {
     topics.Sort("LastPost", SortDirection.Descending);
     foreach (Topic topic in topics)
     {
         Controls.Add(new LiteralControl("<tr class=\"ms-alternating\">"));
         Controls.Add(new LiteralControl(string.Format("<td valign=\"top\"><img src=\"{0}\"></td>", ForumApplication.Instance.ForumImage)));
         string postLink = ForumApplication.Instance.GetLink(SharePointForumControls.ViewMessages, "topic={0}", topic.Id);
         Controls.Add(new LiteralControl(string.Format("<td align=left><strong><a href=\"{0}\">{1}</a></strong></td>", postLink, topic.Name)));
         Controls.Add(new LiteralControl(string.Format("<td align=middle width=7%>{0}</td>", topic.Replies)));
         Controls.Add(new LiteralControl(string.Format("<td align=middle width=20%>{0}</td>", HtmlUtility.CreateProfileLink(topic.Author))));
         Controls.Add(new LiteralControl(string.Format("<td align=middle width=7%>{0}</td>", topic.Views)));
         Controls.Add(new LiteralControl(string.Format("<td align=middle width=25%>{0}<br>{1}</td>", topic.LastPost.ToString("ddd MMM d, yyyy h:m tt"), topic.Author.Name)));
         Controls.Add(new LiteralControl("</tr>"));
     }
 }
Exemplo n.º 28
0
        protected void LoadData()
        {
            string topicId = System.Configuration.ConfigurationManager.AppSettings["TopicFeedback"];

            try
            {
                Topic = TopicCollection.GetTopic(topicId);
                PSCPortal.CMS.ArticleCollection arList = PSCPortal.CMS.ArticleCollection.GetArticleCollectionPublish(Topic);
                System.Collections.Generic.IEnumerable <PSCPortal.CMS.Article> it = arList.Take(5);
                //RadListView1.DataSource = it;
                //RadListView1.DataBind();
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 29
0
        public void AddMultiLevelWildcard()
        {
            // Arrange
            ITopicCollection collection = new TopicCollection(Fixture.Create <int>());

            // Act
            collection = collection.AddMultiLevelWildcard();

            // Assert
            collection.Levels
            .Should()
            .Be(1, "because the wildcard consist of one level");

            collection.IsAppendingAllowed
            .Should()
            .BeFalse("because no addition should be allowed after a multi-level wildcard");
        }
Exemplo n.º 30
0
        public void AddSingleLevelWildcard()
        {
            // Arrange
            ITopicCollection collection = new TopicCollection(Fixture.Create <int>());

            // Act
            collection = collection.AddSingleLevelWildcard();

            // Assert
            collection.Levels
            .Should()
            .Be(1, "because the wildcard consist of one level");

            collection.IsAppendingAllowed
            .Should()
            .BeTrue("because a single level wildcard should not block topic appending");
        }
Exemplo n.º 31
0
        private static TopicCollection DBMapping(DBTopicCollection dbCollection)
        {
            if (dbCollection == null)
            {
                return(null);
            }

            var collection = new TopicCollection();

            foreach (var dbItem in dbCollection)
            {
                var item = DBMapping(dbItem);
                collection.Add(item);
            }

            return(collection);
        }
Exemplo n.º 32
0
        public void AddTopic_OnSingleLevelWildcard()
        {
            // Arrange
            ITopicCollection collection = new TopicCollection(Fixture.Create <int>());

            // Act
            collection = collection.AddTopic(
                Mqtt.Wildcard.SingleLevel.ToString());

            // Assert
            collection.Levels
            .Should()
            .Be(1, "because the wildcard consist of one level");

            collection.IsAppendingAllowed
            .Should()
            .BeTrue("because a topic appending is allowed after a single-level wildcard");
        }
Exemplo n.º 33
0
        public void AddTopic_OnValidTopic()
        {
            // Arrange
            var addCount = Fixture.Create <int>();
            ITopicCollection collection = new TopicCollection(addCount + 1);

            // Act
            for (var i = 0; i < addCount; ++i)
            {
                collection = collection.AddTopic(Fixture.Create <string>());
            }

            // Assert
            collection.Levels
            .Should()
            .Be(addCount,
                "because there should be as many levels as topics added");
        }
        /// <summary>
        /// This loads the tree view with table of contents file entries from the project
        /// </summary>
        /// <remarks>Token information is also loaded here and passed on to the converter.</remarks>
        private void LoadTableOfContentsInfo()
        {
            List<ITableOfContents> tocFiles;
            TopicCollection contentLayout;
            TokenCollection tokens;

            tvContent.ItemsSource = null;
            tableOfContents = null;
            lblCurrentProject.Text = null;
            browserHistory.Clear();
            historyLocation = -1;

            if(currentProject == null)
            {
                lblCurrentProject.Text = "None - Select a help file builder project in the Solution Explorer";
                return;
            }

            // Make sure the base path is set for imported code blocks
            this.SetImportedCodeBasePath();

            // Get content from open file editors
            var args = new FileContentNeededEventArgs(FileContentNeededEvent, this);
            base.RaiseEvent(args);

            lblCurrentProject.Text = currentProject.Filename;
            browserHistory.Clear();
            historyLocation = -1;
            tableOfContents = new TocEntryCollection();

            try
            {
                converter.MediaFiles.Clear();

                // Get the image files.  This information is used to resolve media link elements in the
                // topic files.
                foreach(var file in currentProject.ImagesReferences)
                    converter.MediaFiles[file.Id] = new KeyValuePair<string, string>(file.FullPath, file.AlternateText);
            }
            catch(Exception ex)
            {
                tableOfContents.Add(new TocEntry(currentProject)
                {
                    Title = "ERROR: Unable to load media info: " + ex.Message
                });
            }

            try
            {
                converter.Tokens.Clear();

                // Get the token files.  This information is used to resolve token elements in the topic files.
                foreach(var file in currentProject.ContentFiles(BuildAction.Tokens).OrderBy(f => f.LinkPath))
                {
                    // If open in an editor, use the edited values
                    if(!args.TokenFiles.TryGetValue(file.FullPath, out tokens))
                    {
                        tokens = new TokenCollection(file.FullPath);
                        tokens.Load();
                    }

                    // Store the tokens as XElements so that they can be parsed inline with the topic
                    foreach(var t in tokens)
                        converter.Tokens.Add(t.TokenName, XElement.Parse("<token>" + t.TokenValue +
                            "</token>"));
                }
            }
            catch(Exception ex)
            {
                tableOfContents.Add(new TocEntry(currentProject)
                {
                    Title = "ERROR: Unable to load token info: " + ex.Message
                });
            }

            try
            {
                converter.TopicTitles.Clear();

                // Load the content layout files.  Site maps are ignored as we don't support rendering them.
                tocFiles = new List<ITableOfContents>();

                foreach(var contentFile in currentProject.ContentFiles(BuildAction.ContentLayout))
                {
                    // If open in an editor, use the edited values
                    if(!args.ContentLayoutFiles.TryGetValue(contentFile.FullPath, out contentLayout))
                    {
                        contentLayout = new TopicCollection(contentFile);
                        contentLayout.Load();
                    }

                    tocFiles.Add(contentLayout);
                }

                tocFiles.Sort((x, y) =>
                {
                    ContentFile fx = x.ContentLayoutFile, fy = y.ContentLayoutFile;

                    if(fx.SortOrder < fy.SortOrder)
                        return -1;

                    if(fx.SortOrder > fy.SortOrder)
                        return 1;

                    return String.Compare(fx.Filename, fy.Filename, StringComparison.OrdinalIgnoreCase);
                });

                // Create the merged TOC.  For the purpose of adding links, we'll include everything even topics
                // marked as invisible.
                foreach(ITableOfContents file in tocFiles)
                    file.GenerateTableOfContents(tableOfContents, true);

                // Pass the topic IDs and titles on to the converter for use in hyperlinks
                foreach(var t in tableOfContents.All())
                    if(!String.IsNullOrEmpty(t.Id))
                        converter.TopicTitles[t.Id] = t.LinkText;
            }
            catch(Exception ex)
            {
                tableOfContents.Add(new TocEntry(currentProject)
                {
                    Title = "ERROR: Unable to load TOC info: " + ex.Message
                });
            }

            if(tableOfContents.Count != 0)
            {
                foreach(var t in tableOfContents.All())
                    t.IsSelected = false;

                tableOfContents[0].IsSelected = true;
            }

            tvContent.ItemsSource = tableOfContents;
        }
Exemplo n.º 35
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="source">The source path containing the HTML files</param>
        /// <param name="dest">The destination path for the MAML topics and
        /// supporting files</param>
        /// <param name="createCompanion">True to create companion files for
        /// all topic files or false to not create them.</param>
        /// <param name="moveIntroText">If true, move text before the first section into an introduction element.
        /// If false, insert a place holder introduction element.</param>
        public HtmlToMaml(string source, string dest, bool createCompanion, bool moveIntroText)
        {
            XPathDocument rulesFile;
            XPathNavigator navRules;
            StringBuilder sb;
            string name;

            sourcePath = source;
            destPath = dest;
            createCompanionFile = createCompanion;
            replaceIntro = moveIntroText;
            pathProvider = this;

            if(sourcePath.EndsWith("\\", StringComparison.Ordinal))
                sourcePath = sourcePath.Substring(0, sourcePath.Length - 1);

            if(destPath.EndsWith("\\", StringComparison.Ordinal))
                destPath = destPath.Substring(0, destPath.Length - 1);

            sourcePath = Path.GetFullPath(sourcePath);
            destPath = Path.GetFullPath(destPath);

            topics = new TopicCollection();
            images = new ImageReferenceCollection();

            topicDictionary = new Dictionary<FilePath, Topic>();
            imageDictionary = new Dictionary<FilePath, ImageReference>();

            conversionRules = new Dictionary<string, TagOptions>();
            markupSections = new List<string>();
            entities = new Dictionary<string, string>();
            tokens = new Dictionary<string, string>();

            // Load the conversion rules
            rulesFile = new XPathDocument(Path.Combine(Path.GetDirectoryName(
                Assembly.GetExecutingAssembly().Location), "ConversionRules.xml"));
            navRules = rulesFile.CreateNavigator();

            XPathNavigator bodyExpr = navRules.SelectSingleNode("//BodyExtract");

            if(bodyExpr != null)
                FileParser.BodyExtractExpression = bodyExpr.GetAttribute(
                    "expression", string.Empty);

            // Add the tags we will handle internally
            conversionRules.Add("a", null);
            conversionRules.Add("code", null);
            conversionRules.Add("h1", null);
            conversionRules.Add("h2", null);
            conversionRules.Add("h3", null);
            conversionRules.Add("h4", null);
            conversionRules.Add("h5", null);
            conversionRules.Add("h6", null);
            conversionRules.Add("img", null);
            conversionRules.Add("see", null);

            // Get the rules to process
            sb = new StringBuilder();

            foreach(XPathNavigator nav in navRules.Select("//Entities/Entity"))
                entities.Add(nav.GetAttribute("name", String.Empty),
                    nav.GetAttribute("value", String.Empty));

            foreach(XPathNavigator nav in navRules.Select("//MarkupWrapper/Tag"))
            {
                if(sb.Length != 0)
                    sb.Append("|");

                name = nav.GetAttribute("name", String.Empty).ToLower(
                    CultureInfo.InvariantCulture);
                conversionRules.Add(name, null);
                sb.Append(name);
            }

            name = sb.ToString();
            sb.Insert(0, @"<\s*(");
            sb.Append(@")[^>]*?>.*?<\s*/\s*(\1)[^>]*?>|<\s*(");
            sb.Append(name);
            sb.Append(@")\s*?((\s|/)[^>]*?)?>");
            reMarkupWrapper = new Regex(sb.ToString(), RegexOptions.IgnoreCase |
                RegexOptions.Singleline);
            reReplaceMarker= new Regex("\xFF");
            matchMarkupWrapper = new MatchEvaluator(OnMatchMarkupWrapper);
            matchMarker = new MatchEvaluator(OnMatchMarker);
            sb.Remove(0, sb.Length);

            foreach(XPathNavigator nav in navRules.Select("//Remove/Tag"))
            {
                if(sb.Length != 0)
                    sb.Append("|");

                name = nav.GetAttribute("name", String.Empty).ToLower(
                    CultureInfo.InvariantCulture);
                conversionRules.Add(name, null);
                sb.Append(name);
            }

            sb.Insert(0, @"<\s*/?\s*(");
            sb.Append(@")\s*?((\s|/)[^>]*?)?>");
            reRemoveTag = new Regex(sb.ToString(), RegexOptions.IgnoreCase |
                RegexOptions.Singleline);
            sb.Remove(0, sb.Length);

            foreach(XPathNavigator nav in navRules.Select("//Replace/Tag"))
            {
                if(sb.Length != 0)
                    sb.Append("|");

                name = nav.GetAttribute("name", String.Empty).ToLower(
                    CultureInfo.InvariantCulture);
                conversionRules.Add(name, new TagOptions(nav));
                sb.Append(name);
            }

            sb.Insert(0, @"<\s*(?<Closing>/?)\s*(?<Tag>");
            sb.Append(@")\s*(?<Attributes>(\s|/)[^>]*?)?>");
            reReplaceTag = new Regex(sb.ToString(), RegexOptions.IgnoreCase |
                RegexOptions.Singleline);
            matchReplace = new MatchEvaluator(OnMatchReplace);

            matchCode = new MatchEvaluator(OnMatchCode);
            matchSee = new MatchEvaluator(OnMatchSee);
            matchAnchor = new MatchEvaluator(OnMatchAnchor);
            matchImage = new MatchEvaluator(OnMatchImage);
            matchHeading = new MatchEvaluator(OnMatchHeading);
            matchIntroduction = new MatchEvaluator(OnMatchIntroduction);
            matchEntity = new MatchEvaluator(OnMatchEntity);
            matchToken = new MatchEvaluator(OnMatchToken);
        }
Exemplo n.º 36
0
Arquivo: Topic.cs Projeto: aeagle/SHFB
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        public Topic()
        {
            contentId = Guid.NewGuid().ToString();
            subtopics = new TopicCollection(null);
            keywords = new MSHelpKeywordCollection();
            this.Visible = true;

            subtopics.ListChanged += childList_ListChanged;
            keywords.ListChanged += childList_ListChanged;
        }
        //=====================================================================

        /// <summary>
        /// Load a content layout file for editing
        /// </summary>
        /// <param name="contentLayoutFile">The content layout file item to load</param>
        public void LoadContentLayoutFile(FileItem contentLayoutFile)
        {
            if(contentLayoutFile == null)
                throw new ArgumentNullException("contentLayoutFile",
                    "A content layout file item must be specified");

            topics = new TopicCollection(contentLayoutFile.ToContentFile());
            topics.Load();
            topics.ListChanged += new ListChangedEventHandler(topics_ListChanged);

            if(topics.Count !=0 && topics.Find(t => t.IsSelected, false).Count() == 0)
                topics[0].IsSelected = true;

            tvContent.ItemsSource = topics;

            this.topics_ListChanged(this, new ListChangedEventArgs(ListChangedType.Reset, -1));
        }
Exemplo n.º 38
0
        /// <summary>
        /// Add all topic files found in the selected folder
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void AddAllTopicsInFolder_Click(object sender, EventArgs e)
        {
            ToolStripItem tiAdd = (ToolStripItem)sender;
            TopicCollection parent, newTopics = new TopicCollection(null);
            Topic selectedTopic;
            int idx;

            using(FolderBrowserDialog dlg = new FolderBrowserDialog())
            {
                dlg.Description = "Select a folder to add all of its content";
                dlg.SelectedPath = Directory.GetCurrentDirectory();

                if(dlg.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        newTopics.AddTopicsFromFolder(dlg.SelectedPath,
                            dlg.SelectedPath, topics.FileItem.ProjectElement.Project);
                        MainForm.Host.ProjectExplorer.RefreshProject();
                    }
                    finally
                    {
                        Cursor.Current = Cursors.Default;
                    }
                }

                if(newTopics.Count != 0)
                {
                    if(tiAdd.Owner != cmsNewChildTopic)
                    {
                        // Insert as siblings
                        if(tvContent.SelectedNode == null)
                        {
                            parent = topics;
                            idx = 0;
                        }
                        else
                        {
                            selectedTopic = (Topic)tvContent.SelectedNode.Tag;
                            parent = selectedTopic.Parent;
                            idx = parent.IndexOf(selectedTopic) + 1;
                        }

                        foreach(Topic t in newTopics)
                        {
                            parent.Insert(idx, t);
                            idx++;
                        }
                    }
                    else    // Insert as children
                    {
                        parent = ((Topic)tvContent.SelectedNode.Tag).Subtopics;

                        foreach(Topic t in newTopics)
                            parent.Add(t);
                    }

                    // Take the easy way out and reload the tree
                    this.LoadTopics(newTopics[0]);
                }
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Add new topics from all files in a selected folder
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void cmdAddAllFromFolder_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            TopicCollection parent, newTopics = new TopicCollection(null);
            Topic selectedTopic = ucContentLayoutEditor.CurrentTopic;
            string projectPath = Path.GetDirectoryName(contentLayoutFile.Project.Filename);
            int idx;

            using(FolderBrowserDialog dlg = new FolderBrowserDialog())
            {
                dlg.Description = "Select a folder to add all of its content";
                dlg.SelectedPath = (selectedTopic != null && selectedTopic.TopicFile != null) ?
                    Path.GetDirectoryName(selectedTopic.TopicFile.FullPath) : projectPath;

                if(dlg.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        MouseCursor.Current = MouseCursors.WaitCursor;

                        newTopics.AddTopicsFromFolder(dlg.SelectedPath, dlg.SelectedPath,
                            contentLayoutFile.Project);

                        MainForm.Host.ProjectExplorer.RefreshProject();
                    }
                    finally
                    {
                        MouseCursor.Current = MouseCursors.Default;
                    }
                }

                if(newTopics.Count != 0)
                    if(e.Parameter == null || selectedTopic == null)
                    {
                        // Insert as siblings
                        if(selectedTopic == null)
                        {
                            parent = ucContentLayoutEditor.Topics;
                            idx = 0;
                        }
                        else
                        {
                            parent = selectedTopic.Parent;
                            idx = parent.IndexOf(selectedTopic) + 1;
                        }

                        foreach(Topic t in newTopics)
                            parent.Insert(idx++, t);
                    }
                    else
                    {
                        // Insert as children
                        parent = selectedTopic.Subtopics;

                        foreach(Topic t in newTopics)
                            parent.Add(t);

                        selectedTopic.IsExpanded = true;
                    }
            }
        }
Exemplo n.º 40
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="source">The source file or null to create an empty container node with no
        /// associated topic</param>
        public Topic(string source)
        {
            id = Guid.NewGuid();
            revisionNumber = "1";
            sortOrder = Int32.MaxValue;

            if(source != null)
                sourceFile = new FilePath(source, HtmlToMaml.PathProvider);

            subtopics = new TopicCollection();
        }
Exemplo n.º 41
0
 public static TopicCollection CreateTopicCollection(int ID, string title, byte[] rowVersion, int topicCollection_ActivityType)
 {
     TopicCollection topicCollection = new TopicCollection();
     topicCollection.Id = ID;
     topicCollection.Title = title;
     topicCollection.RowVersion = rowVersion;
     topicCollection.TopicCollection_ActivityType = topicCollection_ActivityType;
     return topicCollection;
 }
Exemplo n.º 42
0
 public void AddToTopicCollections(TopicCollection topicCollection)
 {
     base.AddObject("TopicCollections", topicCollection);
 }
Exemplo n.º 43
0
        /// <summary>
        /// Add child nodes to the tree view recursively
        /// </summary>
        /// <param name="children">The collection of entries to add</param>
        /// <param name="root">The root to which they are added</param>
        private void AddChildren(TopicCollection children, TreeNode root)
        {
            TreeNode node;
            Topic defTopic = topics.DefaultTopic, apiTopic = topics.ApiContentInsertionPoint,
                rootContainer = topics.MSHVRootContentContainer;

            foreach(Topic t in children)
            {
                node = root.Nodes.Add(t.DisplayTitle);
                node.Name = t.Id;
                node.Tag = t;

                if(t == defTopic)
                    defaultNode = node;

                if(t == apiTopic)
                    apiInsertionNode = node;

                if(t == rootContainer)
                    rootContainerNode = node;

                if(t == firstSelection)
                    firstNode = node;

                if(t.Subtopics.Count != 0)
                    this.AddChildren(t.Subtopics, node);
            }
        }
Exemplo n.º 44
0
        public SyncReturn Sync(Catalog catalog, String topicID, out TreeNode node)
        {
            node = null;
            if (catalog == null || !catalog.IsOpen || treeview == null || String.IsNullOrEmpty(topicID))
                return SyncReturn.BadParam;

            try
            {
                // returns topic[0] (level 0 root); topic[1] (level 1); ... topic[n] ( topicID )
                if (topicID != lastTopicID || ancestors == null)
                {
                    ancestors = (TopicCollection)catalogRead.GetTableOfContents(catalog, topicID, null, TocReturnDetail.TocAncestors);
                }
                lastTopicID = topicID;

                TreeNode lastMatch = null;

                //Fix: Beta release had item[0] = -1 but the release version no longer includes the artificial node. So we need to

                if (ancestors.Count > 0 && topicID != "-1")
                {
                    ancestors.MoveTo(0);
                    Topic topic = (Topic)ancestors.Current;
                    if (topic.Id != "-1")
                    {
                        node = NodesContainId(treeview.Nodes, "-1");  //check "-1"
                    }
                }

                for (int i = 0; i < ancestors.Count; i++)
                {
                    ancestors.MoveTo(i);
                    Topic topic = (Topic)ancestors.Current;

                    // Find the ID (starting from root node) in the tree nodes

                    if (node == null)
                        node = NodesContainId(treeview.Nodes, topic.Id);  //root tree nodes
                    else
                    {
                        lastMatch = node;
                        node = NodesContainId(node.Nodes, topic.Id);
                    }

                    // Make some decisions

                    if (i == ancestors.Count - 1 && node != null)   //end of the array is topicId -- we an exact match
                    {
                        return SyncReturn.ExactMatch;
                    }
                    else if (node == null) // no match - return last good node match in the ancester match
                    {
                        node = lastMatch;
                        if (node == null)
                        {
                            return SyncReturn.NoMatch;    // this topic id is not in the master TOC
                        }
                        else
                        {
                            return SyncReturn.ParialMatch;   // We got matched just so far then ran out of nodes
                        }
                    }
                }

            }
            catch
            {
                return SyncReturn.Exception;
            }
            return SyncReturn.NoMatch;
        }
        //=====================================================================

        /// <summary>
        /// This loads the tree view with table of contents file entries from the project
        /// </summary>
        private List<EntityReference> LoadTableOfContentsInfo()
        {
            List<ITableOfContents> tocFiles;
            TopicCollection contentLayout;
            TocEntryCollection siteMap, mergedToc;
            EntityReference er;
            bool hasSelectedItem = false;

            if(tableOfContents != null)
                return tableOfContents;

            tableOfContents = new List<EntityReference>();

            // Get content from open file editors
            var args = new FileContentNeededEventArgs(FileContentNeededEvent, this);
            base.RaiseEvent(args);

            try
            {
                tocFiles = new List<ITableOfContents>();

                // Load all content layout files and add them to the list
                foreach(var contentFile in currentProject.ContentFiles(BuildAction.ContentLayout))
                {
                    // If open in an editor, use the edited values
                    if(!args.ContentLayoutFiles.TryGetValue(contentFile.FullPath, out contentLayout))
                    {
                        contentLayout = new TopicCollection(contentFile);
                        contentLayout.Load();
                    }

                    tocFiles.Add(contentLayout);
                }

                // Load all site maps and add them to the list
                foreach(var contentFile in currentProject.ContentFiles(BuildAction.SiteMap))
                {
                    // If open in an editor, use the edited values
                    if(!args.SiteMapFiles.TryGetValue(contentFile.FullPath, out siteMap))
                    {
                        siteMap = new TocEntryCollection(contentFile);
                        siteMap.Load();
                    }

                    tocFiles.Add(siteMap);
                }

                tocFiles.Sort((x, y) =>
                {
                    ContentFile fx = x.ContentLayoutFile, fy = y.ContentLayoutFile;

                    if(fx.SortOrder < fy.SortOrder)
                        return -1;

                    if(fx.SortOrder > fy.SortOrder)
                        return 1;

                    return String.Compare(fx.Filename, fy.Filename, StringComparison.OrdinalIgnoreCase);
                });

                // Create the merged TOC.  For the purpose of adding links, we'll include everything even topics
                // marked as invisible.
                mergedToc = new TocEntryCollection();

                foreach(ITableOfContents file in tocFiles)
                    file.GenerateTableOfContents(mergedToc, true);

                // Convert the TOC info to entity references
                foreach(var t in mergedToc)
                {
                    er = new EntityReference
                    {
                        EntityType = EntityType.TocEntry,
                        Id = t.Id,
                        Label = (t.Title ?? t.Id ?? "(No title)"),
                        ToolTip = String.Format(CultureInfo.CurrentCulture, "ID: {0}\nFile: {1}",
                            (t.Id ?? t.Title ?? "(No ID)"), t.SourceFile),
                        Tag = t,
                        IsExpanded = t.IsExpanded,
                        IsSelected = (t.IsSelected && !hasSelectedItem)
                    };

                    // Only use the first selected item
                    if(er.IsSelected)
                        hasSelectedItem = true;

                    tableOfContents.Add(er);

                    if(t.Children.Count != 0)
                        hasSelectedItem = this.AddChildTocEntries(t, er, hasSelectedItem);
                }
            }
            catch(Exception ex)
            {
                tableOfContents.Add(new EntityReference
                {
                    EntityType = EntityType.File,
                    Label = "Unable to load TOC info: " + ex.Message,
                    ToolTip = "Error"
                });
            }

            if(!hasSelectedItem && tableOfContents.Count != 0)
                tableOfContents[0].IsSelected = true;

            return tableOfContents;
        }
Exemplo n.º 46
0
        //=====================================================================
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="fileItem">The project file item to edit</param>
        public ContentLayoutWindow(FileItem fileItem)
        {
            EventHandler onClick = new EventHandler(templateFile_OnClick);
            ToolStripMenuItem miTemplate;
            Image itemImage;
            string name;

            InitializeComponent();

            sbStatusBarText.InstanceStatusBar = MainForm.Host.StatusBarTextLabel;

            // Add the topic templates to the New Topic context menu
            string[] files = Directory.GetFiles(Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "ConceptualTemplates"), "*.aml");

            if(files.Length == 0)
                miStandardSibling.Enabled = miStandardChild.Enabled = false;
            else
                foreach(string file in files)
                {
                    name = Path.GetFileNameWithoutExtension(file);
                    itemImage = null;

                    // For Conceptual.aml, make it the default action when the
                    // toolbar button is clicked.
                    if(name == "Conceptual")
                    {
                        tsbAddSiblingTopic.ButtonClick -= new EventHandler(
                            tsbAddTopic_ButtonClick);
                        tsbAddChildTopic.ButtonClick -= new EventHandler(
                            tsbAddTopic_ButtonClick);
                        tsbAddSiblingTopic.ButtonClick += new EventHandler(onClick);
                        tsbAddChildTopic.ButtonClick += new EventHandler(onClick);
                        tsbAddSiblingTopic.Tag = tsbAddChildTopic.Tag = file;

                        itemImage = miAddEmptySibling.Image;
                        miAddEmptySibling.Image = miAddEmptyChild.Image = null;
                    }

                    miTemplate = new ToolStripMenuItem(name, null, onClick);
                    miTemplate.Image = itemImage;
                    miTemplate.Tag = file;
                    sbStatusBarText.SetStatusBarText(miTemplate, "Add new '" +
                        name + "' topic");
                    miStandardSibling.DropDownItems.Add(miTemplate);

                    miTemplate = new ToolStripMenuItem(name, null, onClick);
                    miTemplate.Image = itemImage;
                    miTemplate.Tag = file;
                    sbStatusBarText.SetStatusBarText(miTemplate, "Add new '" +
                        name + "' topic");
                    miStandardChild.DropDownItems.Add(miTemplate);
                }

            // Look for custom templates in the local application data folder
            name = Path.Combine(Environment.GetFolderPath(
                Environment.SpecialFolder.LocalApplicationData),
                Constants.ConceptualTemplates);

            if(!Directory.Exists(name))
                miCustomSibling.Enabled = miCustomChild.Enabled = false;
            else
            {
                files = Directory.GetFiles(name, "*.aml");

                if(files.Length == 0)
                    miCustomSibling.Enabled = miCustomChild.Enabled = false;
                else
                    foreach(string file in files)
                    {
                        name = Path.GetFileNameWithoutExtension(file);
                        itemImage = null;

                        miTemplate = new ToolStripMenuItem(name, null, onClick);
                        miTemplate.Image = itemImage;
                        miTemplate.Tag = file;
                        sbStatusBarText.SetStatusBarText(miTemplate,
                            "Add new '" + name + "' topic");
                        miCustomSibling.DropDownItems.Add(miTemplate);

                        miTemplate = new ToolStripMenuItem(name, null, onClick);
                        miTemplate.Image = itemImage;
                        miTemplate.Tag = file;
                        sbStatusBarText.SetStatusBarText(miTemplate,
                            "Add new '" + name + "' topic");
                        miCustomChild.DropDownItems.Add(miTemplate);
                    }
            }

            topics = new TopicCollection(fileItem);
            topics.Load();
            topics.ListChanged += new ListChangedEventHandler(topics_ListChanged);

            this.Text = Path.GetFileName(fileItem.FullPath);
            this.ToolTipText = fileItem.FullPath;
            this.LoadTopics(null);
        }