public async Task <IActionResult> Edit(int id, TopicType topicType)
        {
            if (id != topicType.TopicTypeId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(topicType);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TopicTypeExists(topicType.TopicTypeId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(topicType));
        }
        static void SendMessage(TopicType topic)
        {
            // Create a transaction because we are using a transactional queue.
            using (var trn = new MessageQueueTransaction())
            {
                try
                {
                    // Create queue object
                    using (var queue = QueueHelper.GetQueueReference(@".\private$\mbp.message"))
                    {
                        queue.Formatter = new XmlMessageFormatter();

                        // push message onto queue (inside of a transaction)
                        trn.Begin();
                        queue.Send(String.Format("{0} message", topic), topic.ToString(), trn);
                        trn.Commit();

                        Console.WriteLine("===============================");
                        Console.WriteLine("{0} message queued", topic);
                        Console.WriteLine("===============================");
                        Console.WriteLine();
                    }
                }
                catch
                {
                    trn.Abort(); // rollback the transaction
                }
            }
        }
Example #3
0
        public string InsertTopicType(TopicType TopicType)
        {
            string result = "";

            result = topicTypeBLL.Add(TopicType).ToString();
            return(result);
        }
Example #4
0
        private static string GetTopicTitle(TopicType type, string name)
        {
            switch (type)
            {
            case TopicType.Namespace:
                return(String.Format("{0} Namespace", name ?? "Empty"));

            case TopicType.Schema:
                return(String.Format("{0} Schema", name));

            case TopicType.Element:
                return(String.Format("{0} Element", name));

            case TopicType.Attribute:
                return(String.Format("{0} Attribute", name));

            case TopicType.AttributeGroup:
                return(String.Format("{0} Attribute Group", name));

            case TopicType.Group:
                return(String.Format("{0} Group", name));

            case TopicType.SimpleType:
                return(String.Format("{0} Simple Type", name));

            case TopicType.ComplexType:
                return(String.Format("{0} Complex Type", name));

            default:
                throw ExceptionBuilder.UnhandledCaseLabel(type);
            }
        }
Example #5
0
        public TopicApp(TopicAppTimelineDb timelineDb, TopicType topicType)
        {
            _timelineDb = timelineDb;
            _topicType  = topicType;

            timelineDb.SubscribeApp(this);
        }
Example #6
0
        private string GetTopicTocTitle(TopicType type, string name)
        {
            IDictionary <string, string> nsRenaming =
                _schemaSetManager.Context.Configuration.NamespaceRenaming;

            switch (type)
            {
            case TopicType.Namespace:
                if (nsRenaming != null)
                {
                    string nsName = null;
                    if (String.IsNullOrEmpty(name))
                    {
                        if (nsRenaming.ContainsKey("(Empty)"))
                        {
                            nsName = nsRenaming["(Empty)"];
                        }
                        else if (nsRenaming.ContainsKey("Empty"))
                        {
                            nsName = nsRenaming["Empty"];
                        }
                    }
                    else if (nsRenaming.ContainsKey(name))
                    {
                        nsName = nsRenaming[name];
                    }

                    if (!String.IsNullOrEmpty(nsName))
                    {
                        return(nsName);
                    }
                }

                return(String.Format("{0} Namespace", name ?? "(Empty)"));

            case TopicType.Schema:
                return(String.Format("{0} Schema", name));

            case TopicType.Element:
                return(String.Format("{0} Element", name));

            case TopicType.Attribute:
                return(String.Format("{0} Attribute", name));

            case TopicType.AttributeGroup:
                return(String.Format("{0} Attribute Group", name));

            case TopicType.Group:
                return(String.Format("{0} Group", name));

            case TopicType.SimpleType:
                return(String.Format("{0} Simple Type", name));

            case TopicType.ComplexType:
                return(String.Format("{0} Complex Type", name));

            default:
                throw ExceptionBuilder.UnhandledCaseLabel(type);
            }
        }
Example #7
0
        private static TopicType GetOverviewTopicType(TopicType topicType)
        {
            switch (topicType)
            {
            case TopicType.Schema:
                return(TopicType.SchemasSection);

            case TopicType.Element:
                return(TopicType.ElementsSection);

            case TopicType.Attribute:
                return(TopicType.AttributesSection);

            case TopicType.AttributeGroup:
                return(TopicType.AttributeGroupsSection);

            case TopicType.Group:
                return(TopicType.GroupsSection);

            case TopicType.SimpleType:
                return(TopicType.SimpleTypesSection);

            case TopicType.ComplexType:
                return(TopicType.ComplexTypesSection);

            default:
                throw ExceptionBuilder.UnhandledCaseLabel(topicType);
            }
        }
Example #8
0
        private static string GetOverviewTopicTitle(TopicType topicType)
        {
            switch (topicType)
            {
            case TopicType.RootSchemasSection:
                return("Root Schemas");

            case TopicType.RootElementsSection:
                return("Root Elements");

            case TopicType.SchemasSection:
                return("Schemas");

            case TopicType.ElementsSection:
                return("Elements");

            case TopicType.AttributesSection:
                return("Attributes");

            case TopicType.AttributeGroupsSection:
                return("Attribute Groups");

            case TopicType.GroupsSection:
                return("Groups");

            case TopicType.SimpleTypesSection:
                return("Simple Types");

            case TopicType.ComplexTypesSection:
                return("Complex Types");

            default:
                throw ExceptionBuilder.UnhandledCaseLabel(topicType);
            }
        }
Example #9
0
        public async Task <IActionResult> IndexAjax(string search, TopicType topicType, int page = 1, int size = 5)
        {
            int fromIndex = (page - 1) * size;

            int toIndex = fromIndex + size - 1;
            List <TopicModel> topics = null;
            int topicsCount          = 0;

            if (User.IsInRole(UserRoles.Admin.ToString()))
            {
                topics = await _testManager.GetTopicsAsync(search, fromIndex, toIndex, null, topicType)
                         .ProjectTo <TopicModel>(_mapper.ConfigurationProvider).ToListAsync();

                topicsCount = await _testManager.GetTopicsCountAsync(search, null, topicType);
            }
            else if (User.IsInRole(UserRoles.User.ToString()))
            {
                int userId = await _userManager.GetUserIdAsync(User.Identity.Name);

                topics = await _testManager.GetUserTopicsAsync(userId, search, fromIndex, toIndex, false, topicType)
                         .ProjectTo <TopicModel>(_mapper.ConfigurationProvider).ToListAsync();

                topicsCount = await _testManager.GetTopicsCountAsync(search, false, topicType);
            }

            ViewData["TopicType"]   = topicType;
            ViewData["Page"]        = page;
            ViewData["Search"]      = search == null ? string.Empty : search;
            ViewData["Size"]        = size;
            ViewData["TopicsCount"] = topicsCount;

            return(PartialView("_Topics", topics));
        }
Example #10
0
        private static int GetTopicTypeSortOrderKey(TopicType topicType)
        {
            switch (topicType)
            {
            case TopicType.Schema:
                return(0);

            case TopicType.Element:
                return(1);

            case TopicType.Attribute:
                return(2);

            case TopicType.AttributeGroup:
                return(3);

            case TopicType.Group:
                return(4);

            case TopicType.SimpleType:
                return(5);

            case TopicType.ComplexType:
                return(6);

            default:
                throw ExceptionBuilder.UnhandledCaseLabel(topicType);
            }
        }
        private bool ProcessCommand(Message message, TopicType topic)
        {
            // get the subscribers
            var           subscriptions = new SubscriptionManager();
            List <string> subscribers   = subscriptions.GetSubscribers(topic);

            // loop through the subscribers and send the message
            using (var trn = new MessageQueueTransaction())
            {
                foreach (var subscriberQueue in subscribers)
                {
                    try
                    {
                        // Create queue object
                        using (var queue = QueueHelper.GetQueueReference(subscriberQueue))
                        {
                            queue.Formatter = new XmlMessageFormatter();

                            // push message onto queue (inside of a transaction)
                            trn.Begin();
                            queue.Send((string)message.Body, topic.ToString(), trn);
                            trn.Commit();

                            Console.WriteLine("{0} message queued on {1}", topic, subscriberQueue);
                        }
                    }
                    catch
                    {
                        trn.Abort(); // rollback the transaction
                        return(false);
                    }
                }
            }
            return(true); // successfully sent the message on to subscribers
        }
Example #12
0
        /// <summary>
        /// Method for creating a new topic.
        /// </summary>
        /// <param name="forum">The parent forum of the topic.</param>
        /// <param name="subject">The subject of the topic.</param>
        /// <param name="message">The content/message of the topic.</param>
        /// <param name="type">The type of the topic </param>
        /// <param name="customPropties"></param>
        /// <returns>The newly created topic.</returns>
        public Topic Create(Forum forum, String subject, String message, TopicType type, IDictionary <String, Object> customPropties = null)
        {
            if (forum == null)
            {
                throw new ArgumentNullException("forum");
            }
            if (String.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentNullException("subject");
            }
            if (String.IsNullOrWhiteSpace(message))
            {
                throw new ArgumentNullException("message");
            }
            forum = this.forumRepo.Read(f => f.Id == forum.Id);
            if (forum == null)
            {
                throw new ArgumentException("forum does not exist");
            }

            this.logger.WriteFormat("Create called on TopicService, subject: {0}, forum id: {1}", subject, forum.Id);
            AccessFlag flag = this.permService.GetAccessFlag(this.userProvider.CurrentUser, forum);

            if ((flag & AccessFlag.Create) != AccessFlag.Create)
            {
                this.logger.WriteFormat("User does not have permissions to create a new topic in forum {1}, subject: {0}", subject, forum.Id);
                throw new PermissionException("topic, create");
            }
            if (type != TopicType.Regular && (flag & AccessFlag.Priority) != AccessFlag.Priority)
            {
                this.logger.WriteFormat("User does not have permissions to set topic type on new topic in forum {1}, subject: {0}", subject, forum.Id);
                throw new PermissionException("topic, type");
            }

            Topic t = new Topic {
                Author   = this.userProvider.CurrentUser,
                AuthorId = this.userProvider.CurrentUser.Id,
                Changed  = DateTime.UtcNow,
                Created  = DateTime.UtcNow,
                Editor   = this.userProvider.CurrentUser,
                EditorId = this.userProvider.CurrentUser.Id,
                Forum    = forum,
                ForumId  = forum.Id,
                Message  = message,
                State    = TopicState.None,
                Subject  = subject,
                Type     = type
            };

            t.SetCustomProperties(customPropties);

            this.topicRepo.Create(t);
            this.logger.WriteFormat("Topic created in TopicService, Id: {0}", t.Id);
            this.eventPublisher.Publish <TopicCreated>(new TopicCreated {
                Topic = t
            });
            this.logger.WriteFormat("Create events in TopicService fired, Id: {0}", t.Id);

            return(t);
        }
Example #13
0
        private static string GetOverviewTopicLinkUri(string namespaceUri, TopicType type)
        {
            switch (type)
            {
            case TopicType.RootSchemasSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##RootSchemas", namespaceUri));

            case TopicType.RootElementsSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##RootElements", namespaceUri));

            case TopicType.SchemasSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##Schemas", namespaceUri));

            case TopicType.ElementsSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##Elements", namespaceUri));

            case TopicType.AttributesSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##Attributes", namespaceUri));

            case TopicType.AttributeGroupsSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##AttributeGroups", namespaceUri));

            case TopicType.GroupsSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##Groups", namespaceUri));

            case TopicType.SimpleTypesSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##SimpleTypes", namespaceUri));

            case TopicType.ComplexTypesSection:
                return(string.Format(CultureInfo.InvariantCulture, "{0}##ComplexTypes", namespaceUri));

            default:
                throw ExceptionBuilder.UnhandledCaseLabel(type);
            }
        }
Example #14
0
        private Topic AddTopic(TopicType topicType, string objNamespace,
                               XmlSchemaObject obj, string name)
        {
            objNamespace = (objNamespace == String.Empty)
                            ? null
                            : objNamespace;

            if (_topicStack.Count == 0)
            {
                var root = new List <Topic>();
                _topicStack.Push(root);
            }

            var topic = new Topic
            {
                Title        = GetTopicTitle(topicType, name),
                TocTitle     = GetTopicTocTitle(topicType, name),
                LinkTitle    = GetTopicLinkTitle(topicType, name),
                LinkUri      = GetTopicLinkUri(topicType, objNamespace, obj),
                LinkIdUri    = GetTopicLinkIdUri(topicType, obj),
                TopicType    = topicType,
                Namespace    = objNamespace,
                SchemaObject = obj
            };

            if (obj != null)
            {
                _topicDictionary.Add(obj, topic);
            }

            _topicStack.Peek().Add(topic);

            return(topic);
        }
Example #15
0
        public async Task EventBus_Should_Invoke_Event_Handlers(TopicType topicType, string prefix)
        {
            // Topic name
            var topicName = topicType == TopicType.Explicit ? "my-topic" : null;

            // Create handlers
            var state = new FakeState {
                Data = "A"
            };
            var fakeHandler1 = new FakeEventHandler1(state);
            var fakeHandler2 = new FakeEventHandler2(state);

            // Create message broker
            var messageBroker = new FakeMessageBroker();

            messageBroker.Subscribe(fakeHandler1, topicName, prefix);
            messageBroker.Subscribe(fakeHandler2, topicName, prefix);

            // Create service bus
            var eventBus = new FakeEventBus(messageBroker);

            eventBus.Subscribe(fakeHandler1, topicName, prefix);
            eventBus.Subscribe(fakeHandler2, topicName, prefix);

            // Publish to service bus
            var @event = new FakeIntegrationEvent("B");
            await eventBus.PublishAsync(@event, topicName, prefix);

            // Assert
            Assert.Equal(@event.CreationDate, state.Date);
            Assert.Equal("B", state.Data);
        }
Example #16
0
        public void AddNewRec_Click(object sender, EventArgs e)
        {
            if (!this.CheckValue(this.typename.Text, this.displayorder.Text, this.description.Text))
            {
                return;
            }

            var entity = TopicType.FindByName(this.typename.Text);

            if (entity != null)
            {
                base.RegisterStartupScript("", "<script>alert('数据库中已存在相同的主题分类名称');window.location.href='forum_topictypesgrid.aspx';</script>");
                return;
            }

            //TopicTypes.CreateTopicTypes(this.typename.Text, int.Parse(this.displayorder.Text), this.description.Text);
            entity              = new TopicType();
            entity.Name         = typename.Text;
            entity.DisplayOrder = Int32.Parse(displayorder.Text);
            entity.Description  = description.Text;
            entity.Save();

            AdminVisitLog.InsertLog(this.userid, this.username, this.usergroupid, this.grouptitle, this.ip, "添加主题分类", "添加主题分类,名称为:" + this.typename.Text);
            //XCache.Remove("/Forum/TopicTypes");
            base.RegisterStartupScript("", "<script>window.location.href='forum_topictypesgrid.aspx';</script>");
        }
Example #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string typename        = Request["typename"];
            string typeorder       = Request["typeorder"];
            string typedescription = Request["typedescription"];

            //if (TopicType.Exist(typename))
            //{
            //    this.result = false;
            //    return;
            //}
            //TopicTypes.CreateTopicTypes(typename, int.Parse(typeorder), typedescription);
            //this.maxId = TopicTypes.GetMaxTopicTypesId();
            //DNTCache.Current.RemoveObject("/Forum/TopicTypes");

            var entity = TopicType.FindByName(typename);

            if (entity != null)
            {
                this.result = false;
                return;
            }

            entity              = new TopicType();
            entity.Name         = typename;
            entity.DisplayOrder = Int32.Parse(typeorder);
            entity.Description  = typedescription;
            entity.Save();

            maxId = entity.ID;
        }
Example #18
0
 public Topic(TopicType t, List<Subject> subjects)
 {
     Name = t;
     Subjects = subjects;
     comfortThreshold = 0;
     considerationThreshold = 0;
     curiosityThreshold = 0;
 }
Example #19
0
	public Topic(string id, string title, TopicType type)
	{
		ID = id;
		Title = title;
		Type = type;

		Conditions = new List<DialogueCondition>();
	}
Example #20
0
    public Topic(string id, string title, TopicType type)
    {
        ID    = id;
        Title = title;
        Type  = type;

        Conditions = new Stack <ConditionToken>();
    }
Example #21
0
 public List <string> GetSubscribers(TopicType topic)
 {
     if (SubscribersList.ContainsKey(topic))
     {
         return(SubscribersList[topic]);
     }
     return(null);
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="topicType"></param>
 /// <param name="id"></param>
 /// <param name="mediaTitle">Anime or manga title</param>
 /// <param name="messageId">Null for start, -1 for last post, else scroll to message</param>
 /// <param name="page"></param>
 public ForumsTopicNavigationArgs(TopicType topicType, string id, int?messageId, int page)
 {
     Page      = ForumsPageIndex.PageTopic;
     TopicType = topicType;
     TopicId   = id;
     MessageId = messageId;
     TopicPage = page;
 }
 public ForumsNewTopicNavigationArgs(TopicType topicType, string title, int mediaId)
 {
     Page      = ForumsPageIndex.PageNewTopic;
     ForumType = ForumType.Normal;
     TopicType = topicType;
     Title     = title;
     Id        = mediaId;
 }
Example #24
0
 public Topic(TopicType t)
 {
     Name = t;
     Subjects = new List<Subject>();
     comfortThreshold = 0;
     considerationThreshold = 0;
     curiosityThreshold = 0;
 }
Example #25
0
        public Comment(string username, string body, TopicType type)
        {
            Username = username;
            Body = body;
            TopicType = type;

            // Added create/retrieve code later
        }
Example #26
0
 public Topic(TopicType t, float comfort, float consideration, float curious)
 {
     Name = t;
     Subjects = new List<Subject>();
     comfortThreshold = comfort;
     considerationThreshold = consideration;
     curiosityThreshold = curious;
 }
Example #27
0
        public static string TopicName(string entityId, EntityType entity, TopicType topic)
        {
            string result = (entity == EntityType.Registry) ? "$registries/" : "$devices/";

            result += entityId;
            result += (topic == TopicType.Events) ? "/events" : "/commands";
            return(result);
        }
Example #28
0
        public Topic(string title, string comment, TopicType type)
        {
            Title = title;
            Comment = comment;
            TopicType = type;

            // New or get the comment code here
        }
        public async Task <IActionResult> GetEventsByTopic(TopicType topic, int?page, int?count)
        {
            LogRequestInformation(topic.ToString());

            var result = await _douService.GetEventsByTopic(topic, page, count);

            LogResponseInformation(result);
            return(Ok(result));
        }
Example #30
0
 public Topic()
 {
     //TopicType
     Name = TopicType.Player;
     Subjects = new List<Subject>();
     comfortThreshold = 0;
     considerationThreshold = 0;
     curiosityThreshold = 0;
 }
Example #31
0
        private static string GetTopicLinkTitle(TopicType type, string name)
        {
            if (type == TopicType.Namespace)
            {
                return(name ?? "Empty");
            }

            return(name);
        }
Example #32
0
 public ResearchCompleted(ResearchType research, TopicType? topic)
 {
     this.topic = topic;
     AddControl(new Border(30, 48, 224, 140, ColorScheme.Green, Backgrounds.Research, 0));
     AddControl(new Label(88, Label.Center, "Research Completed", Font.Large, ColorScheme.Green));
     AddControl(new Label(105, Label.Center, research.Metadata().Name, Font.Large, ColorScheme.White));
     AddControl(new Button(146, 64, 80, 14, "OK", ColorScheme.Green, Font.Normal, EndModal));
     AddControl(new Button(146, 176, 80, 14, "VIEW REPORTS", ColorScheme.Green, Font.Normal, OnViewReports));
 }
Example #33
0
 public static Topic Create(TopicType type, string id, string title, string sourcePath, CultureInfo language, string projectFolder)
 {
     switch(type)
     {
         case TopicType.Feature: { return new FeatureTopic() { Id = id, Type = type, Title = title, SourcePath = sourcePath, Language = language, ProjectFolder = projectFolder }; }
         case TopicType.FeatureSet: { return new FeatureSetTopic() { Id = id, Type = type, Title = title, SourcePath = sourcePath, Language = language, ProjectFolder = projectFolder }; }
         default: return null;
     }
 }
Example #34
0
        private static string FormatValue(TopicType type, string value)
        {
            if (type == TopicType.String)
                value = "\"" + value + "\"";
            else if (type == TopicType.Number)
                value += "f";

            return value;
        }
        /// <summary>
        /// 遞等式計算通用處理
        /// </summary>
        /// <param name="type">題型</param>
        /// <param name="expressFormat">計算表達式</param>
        /// <param name="getArguments">參數處理邏輯</param>
        /// <param name="formulas">計算式作成</param>
        private void CleverStartegy(TopicType type, string expressFormat, Func <int[]> getArguments, IList <RecursionEquationFormula> formulas)
        {
            // 當前反推判定次數(一次推算內次數累加)
            int defeated = 0;

            RecursionEquationFormula RecursionEquation = new RecursionEquationFormula
            {
                Type           = type,
                ConfixFormulas = new List <Formula>(),
                Answer         = new List <int>()
            };

            while (1 == 1)
            {
                // 如果大於三次則認為此題無法作成繼續下一題
                if (defeated == INVERSE_NUMBER)
                {
                    RecursionEquation = null;
                    break;
                }

                int[] factors = getArguments();
                if (factors == null)
                {
                    defeated++;
                    continue;
                }

                StringBuilder express = new StringBuilder();
                var           answer  = factors[3];
                express.AppendFormat(CultureInfo.CurrentCulture, expressFormat, factors[0], factors[1], factors[2]);

                // 計算式推導
                var calc = new ExpressArithmeticUtil();
                if (!calc.IsResult(express.ToString(), out int result))
                {
                    defeated++;
                    continue;
                }
                if (result != answer)
                {
                    defeated++;
                    continue;
                }
                // 加入推導出計算式集合
                calc.Formulas.ToList().ForEach(f => RecursionEquation.ConfixFormulas.Add(f));
                RecursionEquation.Answer.Add(answer);
                defeated = 0;

                break;
            }

            if (RecursionEquation != null)
            {
                formulas.Add(RecursionEquation);
            }
        }
Example #36
0
 /// <summary>
 /// Creates a new instance of the <see cref="TopicData"/> class.
 /// </summary>
 /// <param name="type">Topic type.</param>
 /// <param name="fileName">Topic name.</param>
 /// <param name="relativePath">Relative path to the topic file.</param>
 public TopicData(TopicType type, string fileName, string relativePath)
 {
     FileName = fileName;
     Type = type;
     RelativePath = relativePath;
     #if WEAK_RESULT
     parserResult = new WeakReference<TopicParserResult>(null, true);
     #endif
 }
Example #37
0
        private void DeleteForumTypes(string idlist)
        {
            //TopicTypes.DeleteForumTopicTypes(idlist);
            var list = TopicType.FindAllByIDs(idlist.SplitAsInt());

            if (list.Count > 0)
            {
                list.Delete();
            }
        }
Example #38
0
 public static Topic CreateDomainTopic(string name, int passingPoints, TopicType topicType, bool islocked = true)
 {
     return(new Topic
     {
         Name = name,
         PassingPoints = passingPoints,
         TopicType = topicType,
         IsLocked = islocked,
     });
 }
Example #39
0
        private string GetTopicType()
        {
            string text       = this.forumInfo.TopicTypes + "";
            int    num        = 0;
            var    topicTypes = TopicType.FindAllWithCache().ToDataTable();

            while (!(String.IsNullOrEmpty(DNTRequest.GetFormString("type" + num))))
            {
                string type1 = DNTRequest.GetFormString("oldtopictype" + num);
                string type2 = DNTRequest.GetFormString("type" + num);
                if (type2 != "-1")
                {
                    if (String.IsNullOrEmpty(type1))
                    {
                        int  displayOrder = this.GetDisplayOrder(type2.Split(',')[1], topicTypes);
                        var  list         = new List <String>(text.Split("|"));
                        bool flag         = false;
                        for (int j = 0; j < list.Count; j++)
                        {
                            int displayOrder2 = this.GetDisplayOrder(list[j].Split(',')[1], topicTypes);
                            if (displayOrder2 > displayOrder)
                            {
                                list.Insert(j, type2);
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            list.Add(type2);
                        }

                        text = "";
                        foreach (var item in list)
                        {
                            text = text + item + "|";
                        }
                    }
                    else
                    {
                        text = text.Replace(type1, type2);
                    }
                }
                else
                {
                    if (type1 != "")
                    {
                        text = text.Replace(type1, "");
                    }
                }
                //IL_215:
                num++;
            }
            return(text);
        }
        /// <summary>
        /// Query Topic
        /// </summary>
        /// <param name="type">Type</param>
        /// <param name="index">Index</param>
        /// <param name="userid">User Id</param>
        /// <param name="mobiletoken">Mobile Token</param>
        /// <returns></returns>
        public async Task <List <DiscoverResult> > QueryTopic(TopicType type, int index, string userid, string mobiletoken)
        {
            WebContentProvider web = WebContentProvider.GetInstance();
            string             url = string.Format(Config.Discover, index);

            if (type != TopicType.None)
            {
                url += "&category_id=" + (int)type;
            }
            return(await web.HttpGetRequest <List <DiscoverResult> >(url, web.GetHeaders(userid, mobiletoken)));
        }
Example #41
0
 public IMessageConsumer CreateConsumer(TopicType topicType, string strTopicName)
 {
     if (topicType.Equals(TopicType.Topic))
     {
         return(session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(strTopicName)));
     }
     else
     {
         return(session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(strTopicName)));
     }
 }
Example #42
0
		public TopicView(TopicCategory? category, TopicType topic)
		{
			this.category = category;
			this.topic = topic;
			var metadata = topic.Metadata();
			if (metadata.Background != null)
				AddControl(new Background(metadata.Background, metadata.BackgroundPalette));
			AddTopicControls((dynamic)topic.Metadata().Subject);
			AddControl(new Button(5, 5, 30, 14, "OK", metadata.Scheme, Font.Normal, OnOk));
			AddControl(new Button(5, 40, 30, 14, "<<", metadata.Scheme, Font.Normal, OnPrevious));
			AddControl(new Button(5, 75, 30, 14, ">>", metadata.Scheme, Font.Normal, OnNext));
		}
Example #43
0
		/// <summary>
		/// Method for creating a new topic.
		/// </summary>
		/// <param name="forum">The parent forum of the topic.</param>
		/// <param name="subject">The subject of the topic.</param>
		/// <param name="message">The content/message of the topic.</param>
		/// <param name="type">The type of the topic </param>
		/// <param name="customPropties"></param>
		/// <returns>The newly created topic.</returns>
		public Topic Create(Forum forum, String subject, String message, TopicType type, IDictionary<String, Object> customPropties = null) {
			if (forum == null) {
				throw new ArgumentNullException("forum");
			}
			if (String.IsNullOrWhiteSpace(subject)) {
				throw new ArgumentNullException("subject");
			}
			if (String.IsNullOrWhiteSpace(message)) {
				throw new ArgumentNullException("message");
			}
			forum = this.forumRepo.Read(f => f.Id == forum.Id);
			if (forum == null) {
				throw new ArgumentException("forum does not exist");
			}

			this.logger.WriteFormat("Create called on TopicService, subject: {0}, forum id: {1}", subject, forum.Id);
			AccessFlag flag = this.permService.GetAccessFlag(this.userProvider.CurrentUser, forum);
			if ((flag & AccessFlag.Create) != AccessFlag.Create) {
				this.logger.WriteFormat("User does not have permissions to create a new topic in forum {1}, subject: {0}", subject, forum.Id);
				throw new PermissionException("topic, create");
			}
			if (type != TopicType.Regular && (flag & AccessFlag.Priority) != AccessFlag.Priority) {
				this.logger.WriteFormat("User does not have permissions to set topic type on new topic in forum {1}, subject: {0}", subject, forum.Id);
				throw new PermissionException("topic, type");
			}

			Topic t = new Topic {
				Author = this.userProvider.CurrentUser,
				AuthorId = this.userProvider.CurrentUser.Id,
				Changed = DateTime.UtcNow,
				Created = DateTime.UtcNow,
				Editor = this.userProvider.CurrentUser,
				EditorId = this.userProvider.CurrentUser.Id,
				Forum = forum,
				ForumId = forum.Id,
				Message = message,
				State = TopicState.None,
				Subject = subject,
				Type = type
			};
			t.SetCustomProperties(customPropties);

			this.topicRepo.Create(t);
			this.logger.WriteFormat("Topic created in TopicService, Id: {0}", t.Id);
			this.eventPublisher.Publish<TopicCreated>(new TopicCreated {
				Topic = t
			});
			this.logger.WriteFormat("Create events in TopicService fired, Id: {0}", t.Id);

			return t;
		}
 /// <summary>
 /// Query topic notes
 /// </summary>
 /// <param name="type">Topic Type</param>
 /// <param name="startid">Start Id</param>
 /// <returns></returns>
 public async Task<List<RecommendationResult>> QueryDiscover(TopicType type, int startid)
 {
     WebContentProvider web = WebContentProvider.GetInstance();
     string url = Config.Recommendations;
     if (type != TopicType.None)
     {
         url += "&collection_category_id=" + (int)type;
     }
     if (startid != 0)
     {
         url += "&max_recommended_at=" + startid;
     }
     return await web.HttpGetRequest<List<RecommendationResult>>(url, web.GetHeaders(null, null));
 }
Example #45
0
 public void SetQuestionText(MySqlUtils sqlUtils, 
     string title, string questionText, string paramTableName,
     string paramColNames, string queryBody, TopicType topicType)
 {
     m_sqlUtils = sqlUtils;
     m_queryBody = queryBody;
     Text = title;
     m_topicType = topicType;
     DataSet ds = new DataSet();
     sqlUtils.ExecuteQuery(string.Format("SELECT {0} FROM {1}", paramColNames, paramTableName), ds);
     m_paramNames = paramColNames.Split(new char[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
     m_tableName = paramTableName;
     int curPosition = 0;
     while (curPosition < questionText.Length)
     {
         int startParamIndex = questionText.IndexOf('{', curPosition);
         if (startParamIndex < 0) // if there is no more paraeters in the string
         {
             string labelText = questionText.Substring(curPosition);
             _flowLayoutPanelQueryText.Controls.Add(new Label() { Text = labelText, AutoSize = true,
                 Font = m_labelInfo.Font, ForeColor = m_labelInfo.ForeColor,
                 Margin = m_labelInfo.Margins, BackColor = Color.Transparent });
             break;
         }
         if (startParamIndex > curPosition) // if there is a need in Label
         {
             string labelText = questionText.Substring(curPosition, startParamIndex - curPosition);
             _flowLayoutPanelQueryText.Controls.Add(new Label() { Text = labelText, AutoSize = true,
                 Font = m_labelInfo.Font, ForeColor = m_labelInfo.ForeColor,
                 Margin = m_labelInfo.Margins, BackColor = Color.Transparent });
         }
         int endParamIndex = questionText.IndexOf('}', startParamIndex);
         curPosition = endParamIndex + 1;
         int curParamInd = int.Parse(questionText.Substring(startParamIndex + 1, endParamIndex - startParamIndex - 1));
         BBBNOVA.BNComboBox cb = new BBBNOVA.BNComboBox()
         {
             Size = m_comboBoxInfo.Size,
             Font = m_comboBoxInfo.Font,
             ForeColor = Color.White,
             BackColor = Color.Black,
             DataSource = ds.Tables[0],
             DisplayMember = m_paramNames[curParamInd],
             Margin = m_comboBoxInfo.Margins,
             DropDownWidth = 300
         };
         cb.SelectedValueChanged += new EventHandler(comboBox_SelectedValueChanged);
         m_cbList.Add(cb);
         _flowLayoutPanelQueryText.Controls.Add(cb);
     }
 }
Example #46
0
 /// <summary>
 /// Applies majority on facts and normalizes their score
 /// </summary>
 public static void CalculateFactScores(MySqlUtils sqlUtils, string category, TopicType topicType)
 {
     string factScoreUpdate1 = string.Format(
         "UPDATE {0} sf, {3} t1 SET sf.Score = IFNULL((SELECT SUM(us.Belief) FROM {1} us, {2} im " +
         "WHERE sf.ItemID=im.ItemID AND im.UserId=us.UserId AND sf.Category='{4}'), 0) " +
         "WHERE sf.TopicID=t1.TopicId AND t1.TopicType={5}",
         TableConstants.ScoredFacts, TableConstants.UserScores,
         TableConstants.ItemsMentions, TableConstants.Topics,
         category, (int)topicType);
     string factScoreUpdate2 = string.Format(
         "UPDATE {0} sf, (SELECT SUM(sf1.Score) AS TopicScore, sf1.TopicId " +
         "FROM {0} sf1, {1} t WHERE sf1.Category = '{2}' AND sf1.TopicId=t.TopicId AND t.TopicType={3} " +
         "GROUP BY sf1.TopicId) cs " +
         "SET sf.Score = sf.Score / cs.TopicScore " +
         "WHERE sf.TopicId = cs.TopicId AND sf.Category='{2}' AND cs.TopicScore <> 0",
         TableConstants.ScoredFacts, TableConstants.Topics, category, (int)topicType);
     sqlUtils.ExecuteNonQuery(factScoreUpdate1);
     sqlUtils.ExecuteNonQuery(factScoreUpdate2);
 }
 private static void NotfiyResearchCompleted(ResearchType research, TopicType? topic)
 {
     GameState.Current.Notifications.Enqueue(() => new ResearchCompleted(research, topic).DoModal(GameState.Current.ActiveScreen));
 }
Example #48
0
        public static void PrepareDb(MySqlUtils sqlUtils, string category, TopicType topicType)
        {
            ///////////////////////////////////////////////
            // reinitiate the Users Scores table
            // for each user from table of Users create
            // posititve and negative rows

            sqlUtils.ExecuteNonQuery(string.Format(
                "CREATE TABLE IF NOT EXISTS {0} ( " +
                "UserID int(11) unsigned NOT NULL PRIMARY KEY, " +
                "Belief double NOT NULL, " +
                "Version int(11) NULL, " +
                "NumOfFacts int(11) NOT NULL " +
                // ", FOREIGN KEY usUserID_fkey (UserID) REFERENCES Users (UserID) ON DELETE CASCADE" +
                ") ENGINE = MyISAM",
                TableConstants.UserScores));

            // new users creation in the userscores table
            sqlUtils.ExecuteNonQuery(string.Format(
                "INSERT INTO {0} (UserId, Belief, Version, NumOfFacts) " +
                "(SELECT u.UserID as UserId, {2} as Belief, 1 as Version, " +
                "0 as NumOfFacts FROM {1} u " +
                "WHERE u.UserID NOT IN (SELECT us.UserId FROM {0} us))",
                TableConstants.UserScores, TableConstants.Users, BeliefInitialValue,
                TableConstants.ItemsMentions));

            // update users number of facts
            sqlUtils.ExecuteNonQuery(string.Format(
                "UPDATE {0} us,  (SELECT im.UserID, COUNT(*) as NumOfItems FROM {1} im GROUP BY im.UserID) s " +
                "SET us.NumOfFacts = s.NumOfItems, Version=1 " +
                "WHERE s.UserID=us.UserID",
                TableConstants.UserScores, TableConstants.ItemsMentions));

            ////////////////////////////////////////////////////
            // creation and initiallization of scored facts table
            sqlUtils.ExecuteNonQuery(string.Format(
                "CREATE TABLE IF NOT EXISTS {0} ( " +
                "ItemID INT(11) unsigned NOT NULL, " +
                "TopicID INT(11) unsigned NOT NULL, " +
                "Factor int(11) NOT NULL, " +
                "Score DOUBLE NOT NULL, " +
                "Category varchar(70) COLLATE utf8_bin NOT NULL, " +
                "Correctness TINYINT(1) NULL, " +
                //"FactName varchar(100) COLLATE utf8_bin NULL, " +
                //"FactValue varchar(500) COLLATE utf8_bin NOT NULL, " +

                "PRIMARY KEY(ItemID), " +
                //"FOREIGN KEY sfItemID_fkey (ItemID) REFERENCES Items (ItemID) ON DELETE CASCADE, " +
                "FOREIGN KEY sfItemID_fkey (ItemID) REFERENCES Items (id) ON DELETE CASCADE, " +
                "FOREIGN KEY sfTopicID_fkey (TopicID) REFERENCES Topics (TopicID) ON DELETE CASCADE " +
                ") ENGINE = MyISAM",
                TableConstants.ScoredFacts));

            // insert into ScoredFacts new facts
            sqlUtils.ExecuteNonQuery(String.Format(
                "INSERT INTO {0} (ItemId, TopicId, Category, Factor, Score) " +
                "SELECT i.ItemId, i.TopicId, '{3}' AS Category, 0 AS Factor, 0 AS Score " +
                "FROM {1} t, {2} i WHERE t.TopicId=i.TopicId AND t.Category = '{3}' AND t.TopicType={4} " +
                "AND i.ItemId NOT IN (SELECT ItemID FROM {0})",
                TableConstants.ScoredFacts, TableConstants.Topics, TableConstants.Items,
                category, (int)topicType));

            // update all facts Factor
            sqlUtils.ExecuteNonQuery(String.Format(
                "UPDATE {0} sf, (SELECT im.ItemId, COUNT(im.ID) as Factor FROM {1} im, {2} t " +
                "WHERE t.TopicId=im.TopicId AND t.TopicType={3} GROUP BY im.ItemId) s " +
                "SET sf.Factor = s.Factor WHERE sf.ItemId = s.ItemId",
                TableConstants.ScoredFacts, TableConstants.ItemsMentions,
                TableConstants.Topics, (int)topicType));
        }
Example #49
0
 public ForumTopicWrapperFull AddTopic(int threadid, string subject, string content, TopicType topicType)
 {
     var id = ForumDataProvider.CreateTopic(TenantId, threadid, subject, topicType);
     ForumDataProvider.CreatePost(TenantId, id, 0, subject, content, true,
                                  PostTextFormatter.BBCode);
     return GetTopicPosts(id);
 }
        public static int CreateTopic(int tenantID, int threadID, string title, TopicType type)
        {
            int topicID;
            using (var tr = DbManager.Connection.BeginTransaction(IsolationLevel.ReadUncommitted))
            {
                topicID = DbManager.ExecuteScalar<int>(new SqlInsert("forum_topic")
                                                    .InColumnValue("id", 0)
                                                    .InColumnValue("TenantID", tenantID)
                                                    .InColumnValue("thread_id", threadID)
                                                    .InColumnValue("title", title)
                                                    .InColumnValue("type", (int)type)
                                                    .InColumnValue("create_date", DateTime.UtcNow)
                                                    .InColumnValue("is_approved", 1)
                                                    .InColumnValue("poster_id", SecurityContext.CurrentAccount.ID)
                                                    .InColumnValue("sticky", 0)
                                                    .InColumnValue("closed", 0)
                                                    .Identity(0, 0, true));

                DbManager.Connection.CreateCommand(@"update forum_thread 
                                                        set topic_count = (select count(id) from forum_topic where TenantID= @tid and thread_id = @threadID),
                                                        recent_topic_id = @topicID
                                                      where id = @threadID and TenantID = @tid")
                                     .AddParameter("tid", tenantID)
                                     .AddParameter("topicID", topicID)
                                     .AddParameter("threadID", threadID)
                                     .ExecuteNonQuery();

                tr.Commit();
            }

            return topicID;
        }
Example #51
0
        private static string GetTopicLinkIdUri(TopicType type, XmlSchemaObject obj)
        {
            if (type == TopicType.Namespace ||
                type == TopicType.Schema)
            {
                return null;
            }

            var annotated = (XmlSchemaAnnotated)obj;
            if (string.IsNullOrEmpty(annotated.Id))
                return null;

            var targetNamespace = obj.GetSchema().TargetNamespace;
            var schemaName = obj.GetSchemaName();
            return string.Format("{0}#{1}#{2}", targetNamespace, schemaName, annotated.Id);
        }
Example #52
0
        private static string GetTopicLinkTitle(TopicType type, string name)
        {
            if (type == TopicType.Namespace)
                return name ?? "Empty";

            return name;
        }
Example #53
0
 // String to create the table in the database
 public static string CreateTableSQL(TopicType type)
 {
     return string.Format("CREATE TABLE {0} ({1} INTEGER PRIMARY KEY AUTOINCREMENT, {2} DATETIME, {3} ntext, {4} ntext);",
         type == TopicType.Freezer ? _tableNameFreezer : _tableNameFridge, _idFieldName, _dateTimeFieldName, _titleFieldName, _commentFieldName);
 }
 private void AddTopic(Handlers.AddTopicHandler handler, string path, TopicType topicType)
 {
     topicPathsPendingAddition.Add(path);
     topicControl.AddTopic(path, topicType, handler);
 }
Example #55
0
 private static string GetTopicTitle(TopicType type, string name)
 {
     switch (type)
     {
         case TopicType.Namespace:
             return String.Format("{0} Namespace", name ?? "Empty");
         case TopicType.Schema:
             return String.Format("{0} Schema", name);
         case TopicType.Element:
             return String.Format("{0} Element", name);
         case TopicType.Attribute:
             return String.Format("{0} Attribute", name);
         case TopicType.AttributeGroup:
             return String.Format("{0} Attribute Group", name);
         case TopicType.Group:
             return String.Format("{0} Group", name);
         case TopicType.SimpleType:
             return String.Format("{0} Simple Type", name);
         case TopicType.ComplexType:
             return String.Format("{0} Complex Type", name);
         default:
             throw ExceptionBuilder.UnhandledCaseLabel(type);
     }
 }
Example #56
0
        private Topic AddTopic(TopicType topicType, string objNamespace, XmlSchemaObject obj, string name)
        {
            objNamespace = (objNamespace == string.Empty)
                            ? null
                            : objNamespace;

            if (_topicStack.Count == 0)
            {
                var root = new List<Topic>();
                _topicStack.Push(root);
            }

            var topic = new Topic
                        {
                            Title = GetTopicTitle(topicType, name),
                            LinkTitle = GetTopicLinkTitle(topicType, name),
                            LinkUri = GetTopicLinkUri(topicType, objNamespace, obj),
                            LinkIdUri = GetTopicLinkIdUri(topicType, obj),
                            TopicType = topicType,
                            Namespace = objNamespace,
                            SchemaObject = obj
                        };

            if (obj != null)
                _topicDictionary.Add(obj, topic);

            _topicStack.Peek().Add(topic);

            return topic;
        }
Example #57
0
        private void PushTopic(TopicType topicType, string objNamespace, XmlSchemaObject obj, string name)
        {
            Topic topic;
            if (topicType != TopicType.Namespace)
            {
                topic = AddTopic(topicType, objNamespace, obj, name);
            }
            else
            {
                var namespaceKey = objNamespace ?? string.Empty;
                if (!_namespaceTopics.TryGetValue(namespaceKey, out topic))
                {
                    topic = AddTopic(topicType, objNamespace, obj, name);
                    _namespaceTopics.Add(namespaceKey, topic);
                }
            }

            _topicStack.Push(topic.Children);
            _topicUriStack.Push(topic.LinkUri);
        }
Example #58
0
        private string GetTopicLinkUri(TopicType type, string objNamespace, XmlSchemaObject obj)
        {
            if (type == TopicType.Namespace)
                return objNamespace ?? string.Empty;

            var isGlobal = obj.Parent is XmlSchema;
            var parent = _topicUriStack.Peek();

            switch (type)
            {
                case TopicType.Schema:
                    return parent + "#" + obj.GetSchemaName();
                case TopicType.Element:
                    return isGlobal
                            ? parent + "#E/" + ((XmlSchemaElement)obj).QualifiedName.Name
                            : parent + "/" + ((XmlSchemaElement)obj).QualifiedName.Name;
                case TopicType.Attribute:
                    return isGlobal
                            ? parent + "#A/" + ((XmlSchemaAttribute)obj).QualifiedName.Name
                            : parent + "/@" + ((XmlSchemaAttribute)obj).QualifiedName.Name;
                case TopicType.AttributeGroup:
                    return parent + "#AG/" + ((XmlSchemaAttributeGroup)obj).QualifiedName.Name;
                case TopicType.Group:
                    return parent + "#G/" + ((XmlSchemaGroup)obj).QualifiedName.Name;
                case TopicType.SimpleType:
                case TopicType.ComplexType:
                    return parent + "#T/" + ((XmlSchemaType)obj).QualifiedName.Name;
                default:
                    throw ExceptionBuilder.UnhandledCaseLabel(type);
            }
        }
 /// <summary>
 /// Query Topic
 /// </summary>
 /// <param name="type">Type</param>
 /// <param name="index">Index</param>
 /// <param name="userid">User Id</param>
 /// <param name="mobiletoken">Mobile Token</param>
 /// <returns></returns>
 public async Task<List<DiscoverResult>> QueryTopic(TopicType type, int index, string userid, string mobiletoken)
 {
     WebContentProvider web = WebContentProvider.GetInstance();
     string url = string.Format(Config.Discover, index);
     if (type != TopicType.None)
     {
         url += "&category_id=" + (int)type;
     }
     return await web.HttpGetRequest<List<DiscoverResult>>(url, web.GetHeaders(userid, mobiletoken));
 }
Example #60
0
 private void OnSelectTopic(TopicType topic)
 {
     GameState.Current.SetScreen(new TopicView(category, topic));
 }