Exemplo n.º 1
0
        public override AnswerItem Reply(MessageItem mItem)
        {
            var answerItem = new AnswerItem();
            var text       = mItem.TextOnly;

            long.TryParse(text, out var selectedFolder);
            if (selectedFolder == 0)
            {
                var folders = _repository.GetTemplateFolders();
                answerItem.Message = "Available pre-installed word folders:";
                var buttonRows = folders.Select(a => new[]
                {
                    new InlineKeyboardButton
                    {
                        Text         = a.Name + " (" + a.WordsCount + ")",
                        CallbackData = a.Id.ToString()
                    }
                });

                answerItem.Markup = new InlineKeyboardMarkup(buttonRows);
            }
            else
            {
                _repository.SetTemplateFolder(mItem.ChatId, new [] { selectedFolder });
                answerItem.Message = "The folder has been added";
            }
            return(answerItem);
        }
        private void SetExtendedProperties()
        {
            AnswerData answers = new Answers().GetAnswerById(AnswerId, null);

            ExtendedPropertiesPlaceholder.Controls.Clear();

            if (((AnswerTypeMode)answers.Answers[0].TypeMode & AnswerTypeMode.ExtendedType) > 0)
            {
                ExtendedPlaceholder.Visible           = true;
                ExtendedPropertiesPlaceholder.Visible = true;
                AnswerItem answerItem =
                    AnswerItemFactory.Create(answers.Answers[0], null, null, AnswerSelectionMode.None, null,
                                             ControlRenderMode.Edit, null, UniqueID, true, null, true);

                ExtendedAnswerItem extendedItem = answerItem as ExtendedAnswerItem;

                if (extendedItem != null)
                {
                    extendedItem.RestoreProperties();
                    ExtendedPropertiesPlaceholder.Controls.Add(extendedItem.GeneratePropertiesUI());
                }
            }
            else
            {
                ExtendedPropertiesPlaceholder.Controls.Clear();
                ExtendedPropertiesPlaceholder.Visible = false;
                ExtendedPlaceholder.Visible           = false;
            }
        }
Exemplo n.º 3
0
 // 查询调查问题答案信息
 public static int getAnswerList(out List <AnswerItem> list, Dictionary <String, String[]> conditions)
 {
     list = null;
     try
     {
         using (SqlConnection conn = ConnectDb())
         {
             SqlParameter[] pms;
             String         sql = String.Format(sql_GetAnswerList, getAnswerItemFilter(conditions, out pms));
             SqlCommand     cmd = new SqlCommand(sql, conn);
             if (pms != null)
             {
                 cmd.Parameters.AddRange(pms);
             }
             SqlDataReader dr = cmd.ExecuteReader();
             list = new List <AnswerItem>();
             while (dr.Read())
             {
                 AnswerItem item = new AnswerItem();
                 item.ID       = Int32.Parse(dr["ID"].ToString());
                 item.Sequence = Int32.Parse(dr["Sequence"].ToString());
                 item.Answer   = dr["Answer"].ToString();
                 item.Valid    = (bool)dr["Valid"];
                 list.Add(item);
             }
             dr.Close();
             dr.Dispose();
         }
     }
     catch (Exception ex)
     {
         throw new Exception(String.Format("查询调查问题答案信息时出错:{0}", ex.Message));
     }
     return(OK);
 }
Exemplo n.º 4
0
 public override AnswerItem ProcessAnswer(AnswerItem previousAnswerItem, MessageItem mItem)
 {
     return(new AnswerItem
     {
         Message = "This command doesn't support such options"
     });
 }
Exemplo n.º 5
0
 /// <summary>
 /// This resets all variables that may be currently displaying a warning
 /// </summary>
 protected void ClearCurrentWarnings()
 {
     LastDropped            = null;
     ActiveMaxItemWarning   = false;
     PlacingItemBackWarning = false;
     HasWonGame             = false;
 }
Exemplo n.º 6
0
        public override AnswerItem Reply(MessageItem mItem)
        {
            IReplyMarkup markup = null;

            string message;

            if (string.IsNullOrEmpty(mItem.TextOnly))
            {
                message =
                    "Type a chinese word to remove it from the dictionary. All word's score information will be removed too!";
            }
            else if (NoAnswer == mItem.TextOnly.ToLowerInvariant())
            {
                message = "Delete has been cancelled";
            }
            else if (mItem.TextOnly.ToLowerInvariant().StartsWith(YesAnswer))
            {
                try
                {
                    var wordText = mItem.TextOnly.Replace(YesAnswer, string.Empty);
                    var word     = _repository.GetWord(wordText, mItem.ChatId);

                    if (word == null)
                    {
                        message = $"Word {wordText} is not found";
                    }
                    else
                    {
                        _repository.DeleteWord(word.Id);
                        message = $"Word {word.OriginalWord} has been removed";
                    }
                }
                catch (Exception e)
                {
                    message = e.Message;
                }
            }
            else
            {
                message = $"Do you really want to remove '{mItem.TextOnly}'?";

                markup = new InlineKeyboardMarkup(new[]
                {
                    new InlineKeyboardButton {
                        Text = "✅Yes", CallbackData = $"yes{mItem.TextOnly}"
                    },
                    new InlineKeyboardButton {
                        Text = "❌No", CallbackData = "no"
                    }
                });
            }

            var answer = new AnswerItem
            {
                Message = message,
                Markup  = markup
            };

            return(answer);
        }
Exemplo n.º 7
0
        public string GetLastAnswerSheet(string pRequest)
        {
            var rd     = new APIResponse <GetLastAnswerSheetRD>();
            var rdData = new GetLastAnswerSheetRD();

            List <AnswerItem> list = new List <AnswerItem>();
            AnswerItem        item = new AnswerItem()
            {
                QuestionId = "1",
                Answer     = "A"
            };

            list.Add(item);
            item = new AnswerItem()
            {
                QuestionId = "2",
                Answer     = "B"
            };
            list.Add(item);
            rdData.AnswerList = list;
            rdData.Score      = 90;
            rdData.TestStatus = 1;

            rd.Data       = rdData;
            rd.ResultCode = 0;
            return(rd.ToJSON());
        }
Exemplo n.º 8
0
 public void SubmitAnswer(Question.Result answer)
 {
     correct = answer == currentQuestion.result;
     answerTimes++;
     if (correct)
     {
         if (energy < 5)
         {
             energy++;
         }
     }
     else
     {
         if (energy > 0)
         {
             energy--;
         }
     }
     if (answerTimes == 1 && correct && energy >= 5)
     {
         combo++;
     }
     if (!correct)
     {
         combo = 0;
     }
     if (IsCurrentCompleted)
     {
         var answerItem = new AnswerItem();
         answerItem.question  = currentQuestion;
         answerItem.completed = correct && answerTimes == 1;
         completedList.Add(answerItem);
     }
 }
Exemplo n.º 9
0
 public PostedAnswerData(AnswerItem item, int answerId, int sectionNumber, string fieldText, AnswerTypeMode typeMode)
 {
     this.Item           = item;
     this.AnswerId       = answerId;
     this.FieldText      = fieldText;
     this.TypeMode       = typeMode;
     this._sectionNumber = sectionNumber;
 }
Exemplo n.º 10
0
 public override AnswerItem ProcessNext(AnswerItem previousAnswerItem, LearnUnit lUnit)
 {
     return(new AnswerItem
     {
         Message = lUnit.WordStatistic ?? GetCommandIconUnicode(),
         Picture = lUnit.Picture,
         Markup = GetLearnMarkup(lUnit.IdWord.GetValueOrDefault())
     });
 }
        public ActionResult <AnswerItem> GetAnswer()
        {
            var answer = new AnswerItem
            {
                Factor1 = _answer[0].ToString(),
                Factor2 = _answer[1].ToString()
            };

            return(answer);
        }
Exemplo n.º 12
0
 // 查询签到用户调查问题回答信息
 public static int getUserAnswerList(out List <AnswerItem> list, int user_id)
 {
     list = null;
     try
     {
         if (listQuestions == null)
         {
             DbSelect.getQuestionList(out listQuestions, null);
         }
         using (SqlConnection conn = ConnectDb())
         {
             Dictionary <String, String[]> conditions = new Dictionary <String, String[]>();
             conditions.Add("UserID", new String[] { new Operator(OperatorTypeEnum.Equal), user_id.ToString() });
             SqlParameter[] pms;
             String         sql = String.Format(sql_GetUserAnswerList, getUserAnswerItemFilter(conditions, out pms));
             SqlCommand     cmd = new SqlCommand(sql, conn);
             if (pms != null)
             {
                 cmd.Parameters.AddRange(pms);
             }
             SqlDataReader dr = cmd.ExecuteReader();
             list = new List <AnswerItem>();
             while (dr.Read())
             {
                 int          q_id   = (int)dr["QuestionID"];
                 int          ans_id = (int)dr["AnswerID"];
                 QuestionItem ques   = listQuestions.Find((QuestionItem q) =>
                 {
                     return(q.ID == q_id);
                 });
                 if (ques == null)
                 {
                     AnswerItem answer = new AnswerItem();
                     list.Add(answer);
                 }
                 else
                 {
                     AnswerItem answer = ques.Answers.Find((AnswerItem ans) =>
                     {
                         return(ans.ID == ans_id);
                     });
                     list.Add(answer);
                 }
             }
             dr.Close();
             dr.Dispose();
         }
     }
     catch (Exception ex)
     {
         throw new Exception(String.Format("查询签到用户调查问题回答信息时出错:{0}", ex.Message));
     }
     return(OK);
 }
Exemplo n.º 13
0
        public override AnswerItem Reply(MessageItem mItem)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(mItem.TextOnly))
                {
                    var user          = _repository.GetUser(mItem.ChatId);
                    var folders       = _repository.GetUserFolders(mItem.ChatId);
                    var currentFolder = folders.FirstOrDefault(a => a.Id == user.CurrentFolderId) ??
                                        folders.First(a => a.Id == 0);

                    var answerItem = new AnswerItem
                    {
                        Message = $"{_folderManageText}{Environment.NewLine}Current folder is {currentFolder.Name}. You can set a new current folder:"
                    };

                    var buttonRows = folders.Select(a => new[]
                    {
                        new InlineKeyboardButton
                        {
                            Text         = $"{a.Name} ({a.WordsCount})",
                            CallbackData = a.Id.ToString()
                        }
                    });

                    answerItem.Markup = new InlineKeyboardMarkup(buttonRows);
                    return(answerItem);
                }

                if (!long.TryParse(mItem.TextOnly, out var folderId))
                {
                    throw new InvalidOperationException("Wrong folder");
                }

                _repository.SetCurrentFolder(mItem.ChatId, folderId);
            }
            catch (Exception e)
            {
                return(new AnswerItem
                {
                    Message = e.Message
                });
            }

            return(new AnswerItem
            {
                Message = "Folder has been set"
            });
        }
Exemplo n.º 14
0
        public override AnswerItem Reply(MessageItem mItem)
        {
            var answer = new AnswerItem
            {
                Message = "👀"
            };

            if (string.IsNullOrEmpty(mItem.TextOnly))
            {
                answer.Message =
                    "Type a chinese word to view it's flash card. Use chinese characters only! Pinyin and translation are not supported!";
            }
            else
            {
                try
                {
                    var word = _repository.GetWord(mItem.Text, mItem.UserId);

                    if (word == null)
                    {
                        answer.Message = "The word is not found. But you can add it, right?";
                        return(answer);
                    }

                    var file = _repository.GetWordFlashCard(word.CardAll.Id);

                    answer.Message = string.IsNullOrEmpty(word.Usage)
                        ? word.ToScoreString()
                        : word.ToScoreString() + Environment.NewLine + word.Usage;

                    answer.Picture = new GenerateImageResult
                    {
                        Height = word.CardAll.Height, Width = word.CardAll.Width, ImageBody = file
                    };

                    word.Score.ViewCount++;
                    word.Score.LastView = _repository.GetRepositoryTime();
                    _repository.EditWord(word);
                }
                catch (Exception e)
                {
                    answer.Message = e.Message;
                    return(answer);
                }
            }

            return(answer);
        }
 /// <summary>
 /// Subscribe the answer items which require it to the correct
 /// answer publisher controls defined as defined by the Subscriber collection
 /// </summary>
 public static void ActivateAnswerConnections(AnswerConnectionsCollection answerConnections, AnswerItemCollection answers)
 {
     foreach (AnswerConnection connection in answerConnections)
     {
         IAnswerSubscriber answerItem = GetAnswerItem(answers, connection.SubscriberId) as IAnswerSubscriber;
         if (answerItem != null)
         {
             AnswerItem item2 = GetAnswerItem(answers, connection.PublisherId);
             if ((item2 != null) && (item2 is IAnswerPublisher))
             {
                 item2.AnswerPublished        += new AnswerPublisherEventHandler(answerItem.ProcessPublishedAnswers);
                 item2.AnswerPublisherCreated += new AnswerPublisherEventHandler(answerItem.PublisherCreation);
             }
         }
     }
 }
Exemplo n.º 16
0
    public bool CheckAnswer(CoreScene.Spot spot)
    {
        CoreScene.a.canChoose = false;
        bool isRight = spot.color.color == choise.color;

        answers[currentQuestion] = new AnswerItem()
        {
            isRight = isRight,
            color   = spot.color
        };
        if (isRight)
        {
            Tween.a.MoveTo(spot.cube, CoreScene.a.lightCone.position, 3f, Easing.Ease.EaseInExpo);
        }
        Tween.a.DoAfter(3f, () => {
            AskQuestion();
        });
        return(isRight);
    }
Exemplo n.º 17
0
        protected AnswerItem SaveAnswerItem(string[] wordStrings, long userId)
        {
            var answer = new AnswerItem
            {
                Message = GetCommandIconUnicode()
            };

            if (!ValidateArray(wordStrings))
            {
                return(answer);
            }

            var maxStringLength = wordStrings.Select(a => a.Length).Max();

            if (maxStringLength > MaxImportRowLength)
            {
                answer.Message += $"String length must be less than {MaxImportRowLength}";
                return(answer);
            }

            var result = _parseProvider.ImportWords(wordStrings);

            if (result == null)
            {
                return(answer);
            }

            var uploadedResult = UploadWords(result, userId);

            if (uploadedResult.SuccessfulWords.Any())
            {
                answer.Message +=
                    $"These words have been added ({uploadedResult.SuccessfulWords.Length}): {Environment.NewLine} {string.Join(Environment.NewLine, uploadedResult.SuccessfulWords.Select(a => a.OriginalWord))}{Environment.NewLine}";
            }

            if (uploadedResult.FailedWords.Any())
            {
                answer.Message +=
                    $"These words have some parse troubles ({uploadedResult.FailedWords.Length}): {Environment.NewLine} {string.Join(Environment.NewLine, uploadedResult.FailedWords)}";
            }

            return(answer);
        }
 /// <summary>
 /// Subsribe the answer items which require it to the correct
 /// answer publisher controls
 /// </summary>
 public static void BindSubscribersToPublishers(AnswerItemCollection answers)
 {
     foreach (AnswerItem item in answers)
     {
         IAnswerSubscriber subscriber = item as IAnswerSubscriber;
         if (subscriber != null)
         {
             foreach (AnswerData.AnswersRow row in new Answers().GetSubscriptionList(item.AnswerId).Answers.Rows)
             {
                 AnswerItem answerItem = GetAnswerItem(answers, row.AnswerId);
                 if (answerItem != null)
                 {
                     answerItem.AnswerPublished        += new AnswerPublisherEventHandler(subscriber.ProcessPublishedAnswers);
                     answerItem.AnswerPublisherCreated += new AnswerPublisherEventHandler(subscriber.PublisherCreation);
                 }
             }
             continue;
         }
     }
 }
        public void CreateAnswer(string questions, long id)
        {
            try
            {
                var searchAnswerItemRes = new AnswerItemDataRepository().Search(new SearchRequest <AnswerItemData>()
                {
                    Filter = f => f.EmployeeReviewId == id
                });

                if (searchAnswerItemRes.SearchTotal > 0)
                {
                    foreach (var item in searchAnswerItemRes.Items)
                    {
                        new AnswerItemDataRepository().Delete(item.Id);
                    }
                }

                var data = questions.Split('|');

                foreach (var question in data)
                {
                    AnswerItem item = new AnswerItem()
                    {
                        EmployeeReviewId = id,
                        Question         = question,
                        EmployeeRemark   = null,
                        EmployeeScore    = 0,
                        SupervisorRemark = null,
                        SupervisorScore  = 0
                    };

                    new AnswerItemDataRepository().Insert(Mapper.Map <AnswerItemData>(item));
                }
            }
            catch (Exception e)
            {
            }
        }
Exemplo n.º 20
0
        public List <Answer> GetAnswer()
        {
            Dictionary <string, Answer> result = new Dictionary <string, Answer>();

            //找出所有 tag 值為 Question type 的控制項,
            foreach (Control ctrl in this.allQControls.Values)
            {
                Question q = ctrl.Tag as Question;
                if (q != null)
                {
                    if (!result.ContainsKey(q.GetQuestionName()))
                    {
                        result.Add(q.GetQuestionName(), new Answer());
                    }
                    Answer ans = result[q.GetQuestionName()];
                    ans.SetName(q.GetQuestionName());

                    if (ctrl is CheckBox)   //如果是 checkbox :
                    {
                        CheckBox chk = (CheckBox)ctrl;

                        if (chk.Checked)
                        {
                            //這是複選題
                            AnswerItem       theAi            = new AnswerItem();
                            string           ctrlName         = ctrl.Name;
                            QuestionListItem questionListItem = q.GetListItemByLable(ctrlName);
                            theAi.SetValueName(ctrlName);
                            if (questionListItem != null)
                            {
                                if (questionListItem.HasText)  //有 remark
                                {
                                    string remarkCtrlName = ctrlName + "_remark";
                                    if (this.allQControls.ContainsKey(remarkCtrlName))
                                    {
                                        theAi.SetValueRemark(this.allQControls[remarkCtrlName].Text);
                                    }
                                    else
                                    {
                                        theAi.SetValueRemark("");
                                    }
                                }
                            }
                            ans.AddAnswerItem(theAi);
                        } //end of (chk.Checked)
                    }
                    else if (ctrl is DataGridView)
                    {
                        DataGridView dg = (DataGridView)ctrl;
                        Dictionary <string, string> value = new Dictionary <string, string>();
                        foreach (DataGridViewRow row in dg.Rows)
                        {
                            if (!row.IsNewRow)
                            {
                                AnswerItem ai = new AnswerItem();
                                Dictionary <string, string> itemContents = new Dictionary <string, string>();
                                foreach (GridColumn gc in q.GetColumns())
                                {
                                    itemContents.Add(gc.GetName(), (row.Cells[gc.GetName()].Value == null) ? "" : row.Cells[gc.GetName()].Value.ToString());
                                }
                                ai.SetContent(itemContents);
                                ans.GetAnswerItems().Add(ai);
                            }
                        }
                    }
                    else   //視為單選題
                    {
                        if (q.GetQuestionType().ToLower() == "textboxdropdown")
                        {
                            ctrl.Text = ctrl.Text.Trim();
                            string[] strArr = ctrl.Text.Split(',');
                            foreach (string str in strArr)
                            {
                                if (!string.IsNullOrEmpty(str))
                                {
                                    XmlElement elm = new XmlDocument().CreateElement("Item");
                                    elm.SetAttribute("value", str.Trim());
                                    AnswerItem ai = new AnswerItem(elm);
                                    ans.AddAnswerItem(ai);
                                }
                            }
                        }
                        else
                        {
                            ans.SetValue(ctrl.Text);
                        }
                    }
                }
            }


            return(result.Values.ToList <Answer>());
        }
        /// <summary>
        /// Creates a new answer item instance from the db answer data
        /// </summary>
        /// <param name="answer">The data source to create the instance from</param>
        /// <param name="question">The question container</param>
        /// <param name="defaultSelectionMode">The default selection mode for the
        /// item (Radio, checkbox etc...)</param>
        /// <param name="parentControlUniqueID">
        /// Unique ID required to identify global selection groups
        /// like radiobutton groups
        /// </param>
        /// <param name="showAnswerText">
        /// Assigns the text to the answeritem control ?
        /// </param>
        /// <param name="enableDefaults">
        /// Does the answer set the user default values of fields to the answer web controls
        /// </param>
        public static AnswerItem Create(AnswerData.AnswersRow answer, QuestionItem question, Section section, AnswerSelectionMode defaultSelectionMode, Style answerStyle, ControlRenderMode renderMode, string languageCode, string parentControlUniqueID, bool showAnswerText, VoterAnswersData.VotersAnswersDataTable voterAnswersState, bool enableDefaults)
        {
            AnswerItem item = null;

            try
            {
                if (answer.TypeAssembly != null)
                {
                    item                  = (AnswerItem)Assembly.Load(answer.TypeAssembly).CreateInstance(answer.TypeNameSpace);
                    item.AnswerId         = answer.AnswerId;
                    item.ImageUrl         = answer.IsImageURLNull() ? null : answer.ImageURL;
                    item.ID               = (section == null) ? (GlobalConfig.AnswerItemName + answer.AnswerId) : string.Concat(new object[] { GlobalConfig.AnswerItemName, answer.AnswerId, GlobalConfig.AnswerSectionName, section.SectionUid });
                    item.AnswerStyle      = answerStyle;
                    item.Question         = question;
                    item.QuestionId       = answer.QuestionId;
                    item.RenderMode       = renderMode;
                    item.Text             = new PipeManager().PipeValuesInText(answer.QuestionId, answer.AnswerText, voterAnswersState, languageCode);
                    item.ShowAnswerText   = showAnswerText;
                    item.SectionContainer = section;
                    item.LanguageCode     = languageCode;
                }
            }
            catch (FileNotFoundException)
            {
                item          = new AnswerTextItem();
                item.AnswerId = -1;
                item.Text     = string.Format(ResourceManager.GetString("AnswerTypeAssemblyNotFoundMessage"), answer.TypeAssembly);
                return(item);
            }
            catch (NullReferenceException)
            {
                item          = new AnswerTextItem();
                item.AnswerId = -1;
                item.Text     = string.Format(ResourceManager.GetString("AnswerTypeNotFoundMessage"), answer.TypeNameSpace, answer.TypeAssembly);
                return(item);
            }
            catch (InvalidCastException)
            {
                item          = new AnswerTextItem();
                item.AnswerId = -1;
                item.Text     = string.Format(ResourceManager.GetString("AnswerTypeInvalidMessage"), answer.TypeNameSpace, answer.TypeAssembly);
                return(item);
            }
            if (item is IClientScriptValidator)
            {
                IClientScriptValidator validator = (IClientScriptValidator)item;
                validator.JavascriptCode         = answer.JavascriptCode;
                validator.JavascriptFunctionName = answer.JavascriptFunctionName;
                if (answer.JavascriptErrorMessage != null)
                {
                    validator.JavascriptErrorMessage = (ResourceManager.GetString(answer.JavascriptErrorMessage, languageCode) == null) ? answer.JavascriptErrorMessage : ResourceManager.GetString(answer.JavascriptErrorMessage, languageCode);
                }
                else
                {
                    validator.JavascriptErrorMessage = null;
                }
                validator.EnableValidation = true;
            }
            if (item is IMandatoryAnswer)
            {
                ((IMandatoryAnswer)item).Mandatory = answer.Mandatory;
            }
            if ((item is IRegExValidator) && (answer.RegExpression != null))
            {
                ((IRegExValidator)item).RegExpression             = answer.RegExpression;
                ((IRegExValidator)item).RegExpressionErrorMessage = answer.RegExMessage;
            }
            AnswerSelectionItem item2 = item as AnswerSelectionItem;

            if (item2 != null)
            {
                item2.UniqueGroupId = parentControlUniqueID;
                item2.AnswerId      = answer.AnswerId;
                item2.TypeMode      = (AnswerTypeMode)answer.TypeMode;
                item2.SelectionMode = defaultSelectionMode;
                bool flag = (section == null) ? IsUserSelected(answer.AnswerId, 0, voterAnswersState) : IsUserSelected(answer.AnswerId, section.SectionNumber, voterAnswersState);
                if (flag)
                {
                    item2.Selected = flag;
                }
                else
                {
                    item2.Selected = enableDefaults ? answer.Selected : false;
                }
            }
            if (item is IFieldItem)
            {
                IFieldItem item3 = (IFieldItem)item;
                item3.FieldHeight = answer.FieldHeight;
                item3.FieldWidth  = answer.FieldWidth;
                item3.FieldLength = answer.FieldLength;
            }
            else if (item is AnswerDataSourceItem)
            {
                AnswerDataSourceItem item4 = (AnswerDataSourceItem)item;
                item4.QuestionId = answer.QuestionId;
                item4.AnswerId   = answer.AnswerId;
                if (item4 is AnswerXmlItem)
                {
                    item4.DataSource = answer.XmlDatasource;
                }
                else if (answer.DataSource != null)
                {
                    item4.DataSource = ParseDefaultAnswerText(answer.QuestionId, answer.DataSource, voterAnswersState, languageCode);
                }
                item4.ImageUrl = answer.IsImageURLNull() ? null : answer.ImageURL;
            }
            string str = (section == null) ? GetUserText(answer.AnswerId, 0, voterAnswersState) : GetUserText(answer.AnswerId, section.SectionNumber, voterAnswersState);

            if (str != null)
            {
                item.DefaultText = str;
            }
            else if ((enableDefaults && !answer.IsDefaultTextNull()) && (answer.DefaultText.Length > 0))
            {
                item.DefaultText = ParseDefaultAnswerText(answer.QuestionId, answer.DefaultText, voterAnswersState, languageCode);
            }
            if (item is ExtendedAnswerItem)
            {
                ((ExtendedAnswerItem)item).RestoreProperties();
            }
            return(item);
        }
Exemplo n.º 22
0
        public override AnswerItem Reply(MessageItem mItem)
        {
            var message = new AnswerItem
            {
                Message = GetCommandIconUnicode()
            };

            try
            {
                var idUser = mItem.ChatId;

                if (string.IsNullOrEmpty(mItem.TextOnly))
                {
                    message.Message = "Type a word to edit. Use chinese characters only!";
                }
                else if (mItem.TextOnly.StartsWith(EditCmd))
                {
                    if (!long.TryParse(
                            mItem.TextOnly.Split(new[] { EditCmdSeparator }, StringSplitOptions.RemoveEmptyEntries)
                            .LastOrDefault(),
                            out long idWord))
                    {
                        message.Message += "I can not edit your word now, sorry.";
                        return(message);
                    }

                    var lastWord = _repository.GetWord(idWord);
                    //_repository.GetCurrentUserWordStatistic(idUser);

                    if (lastWord == null)
                    {
                        message.Message += "No words to edit";
                        return(message);
                    }
                    message.Message = lastWord.ToEditString();
                }
                else if (mItem.TextOnly.Length > ImportCommand.MaxImportRowLength)
                {
                    message.Message =
                        $"Too much characters. Maximum is {ImportCommand.MaxImportRowLength}";
                }
                else
                {
                    var editedText = new[] { mItem.TextOnly };

                    if (!_importCommand.ValidateArray(editedText))
                    {
                        var wordToFind = _repository.GetWord(mItem.TextOnly, idUser);

                        if (wordToFind == null)
                        {
                            message.Message += "Bad text";
                            return(message);
                        }

                        message.Message = wordToFind.ToEditString();
                        return(message);
                    }

                    var word       = _parseProvider.ImportWords(editedText);
                    var parsedWord = word.SuccessfulWords.FirstOrDefault();

                    if (parsedWord == null)
                    {
                        message.Message += word.FailedWords.FirstOrDefault();
                        return(message);
                    }

                    _importCommand.UploadFiles(parsedWord);

                    _repository.EditWord(parsedWord);
                    message.Message += "The word has been updated";
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                message.Message += ex.Message;
            }
            return(message);
        }