public void FillGrid()
        {
            SurveyData data = new Surveys().GetAllSurveysByTitle(txtSearchField.Text, SelectedFolderId, ((PageBase)Page).NSurveyUser.Identity.UserId);
            gridSurveys.DataSource = null;

            //commented out??
            if (!string.IsNullOrEmpty(SurveyListOrder))
            {
                data.Surveys.DefaultView.Sort = SurveyListOrder;
                gridSurveys.DataSource = data.Surveys.DefaultView;
            } else
                gridSurveys.DataSource = data.Surveys.OrderByDescending(x => x.Activated).ThenBy(x => x.Title);
 
            gridSurveys.DataBind();
   
        }
		private void Page_Load(object sender, System.EventArgs e)
		{
			SetupSecurity();
			MessageLabel.Visible = false;
			_messageConditionId = 
				Information.IsNumeric(Request["messageconditionid"]) ? int.Parse(Request["messageconditionid"]) : -1;
			_isScored = new Surveys().IsSurveyScored(SurveyId);

			LocalizePage();
            UITabList.SetConditionalEndMessageTabs((MsterPageTabs)Page.Master, UITabList.ConditionalEndMessageTabs.EndMessages);

			if (_messageConditionId == -1)
			{
				SwitchToCreationMode();
			}
			else
			{
				SwitchToEditionMode();
			}

            //CKEditor settings:
            //ThankYouCKEditor.config.toolbar = "Simple";
            //ThankYouCKEditor.config.uiColor = "#DDDDDD";
            ConditionCKeditor.config.enterMode = CKEditor.NET.EnterMode.BR;
            ConditionCKeditor.config.skin = "moonocolor";

            ConditionCKeditor.config.toolbar = new object[]
			{
				new object[] { "Source", "-", "NewPage", "Preview", "-", "Templates" },
				new object[] { "Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "-", "Print", "SpellChecker", "Scayt" },
				new object[] { "Undo", "Redo", "-", "Find", "Replace", "-", "SelectAll", "RemoveFormat" },
				new object[] { "Form", "Checkbox", "Radio", "TextField", "Textarea", "Select", "Button", "ImageButton", "HiddenField" },
				"/",
				new object[] { "Bold", "Italic", "Underline", "Strike", "-", "Subscript", "Superscript" },
				new object[] { "NumberedList", "BulletedList", "-", "Outdent", "Indent", "Blockquote", "CreateDiv" },
				new object[] { "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock" },
				new object[] { "BidiLtr", "BidiRtl" },
				new object[] { "Link", "Unlink", "Anchor" },
				new object[] { "Image", "Flash", "Table", "HorizontalRule", "Smiley", "SpecialChar", "PageBreak", "Iframe" },
				"/",
				new object[] { "Styles", "Format", "Font", "FontSize" },
				new object[] { "TextColor", "BGColor" },
				new object[] { "Maximize", "ShowBlocks", "-", "About" }
			};


		}
 private int GetIdFromUrl()
 {
     if (Request.PathInfo.Length == 0)
     {
         MessageLabel.Text = ResourceManager.GetString("InvalidSurveyUrl");
         MessageLabel.Visible = true;
         return -1;
     }
     string friendlyName = Request.PathInfo.Substring(1);
     int id = new Surveys().GetSurveyIdFromFriendlyName(friendlyName);
     if (id <= 0)
     {
         MessageLabel.Text = ResourceManager.GetString("InvalidSurveyUrl");
         MessageLabel.Visible = true;
         return -1;
     }
     return id;
 }
 private int GetIdFromQueryStr()
 {
     Guid guid;
     if (Guid.TryParse(Request[Votations.NSurvey.Constants.Constants.QRYSTRGuid], out guid))
     {
         int id = new Surveys().GetSurveyIdFromGuid(guid);
         if (id <= 0)
         {
             MessageLabel.Text = ResourceManager.GetString("InvalidSurveyGuid");
             MessageLabel.Visible = true; return -1;
         }
         else return id;
     }
     else
     {
         MessageLabel.Text = ResourceManager.GetString("InvalidSurveyGuid");
         MessageLabel.Visible = true; return -1;
     }
 }
        private void Page_Load(object sender, System.EventArgs e)
        {
            UITabList.SetCampaignTabs((MsterPageTabs)Page.Master, UITabList.CampaignTabs.Web);
            MessageLabel.Visible = false;
            SetupSecurity();
            LocalizePage();
            ShowFriendlyUrl();
            if (!Page.IsPostBack)
            {

                // Header.SurveyId = SurveyId;
                ((Wap)Master.Master).HeaderControl.SurveyId = SurveyId;
                var survey = new Surveys().GetSurveyById(SurveyId, null).Surveys[0];
                Guid guid = survey.SurveyGuid;
                if (!survey.IsFriendlyNameNull())
                    txtFriendly.Text = survey.FriendlyName;
                CodeHyperLink.NavigateUrl = GetUrl("?surveyid=" + guid.ToString());
                CodeMobileHyperLink.NavigateUrl = GetMobileUrl("?surveyid=" + guid.ToString());

                CodeHyperLink.Text = CodeHyperLink.NavigateUrl;
                CodeMobileHyperLink.Text = CodeMobileHyperLink.NavigateUrl;
            }
            SetupTextArea();
        }
        private string ExportCSVStyleTwo()
        {
            DateTime startDate;
            DateTime endDate;
            if (rdAllDates.Checked)
            {
                startDate = new DateTime(2004, 1, 1);
                endDate = DateTime.Today;
            }
            else
            {
                startDate = (StartDateTextBox.Text == null && !Information.IsDate(StartDateTextBox.Text)) ?
                     new DateTime(2004, 1, 1) : DateTime.Parse(StartDateTextBox.Text);
                endDate = (EndDateTextBox.Text == null && !Information.IsDate(EndDateTextBox.Text)) ?
                     new DateTime(2010, 1, 1) : DateTime.Parse(EndDateTextBox.Text);
            }

            System.Text.StringBuilder csvData = new System.Text.StringBuilder();
            bool scored = new Surveys().IsSurveyScored(SurveyId);

            // Get an instance of the voter DAL using the DALFactory
            CSVExportData csvExportData = new Voters().GetCSVExport(SurveyId, startDate, endDate);


            string textDelimiter = TextDelimiterTextBox.Text,
                fieldDelimiter = FieldDelimiterTextBox.Text;

            csvData.Append(textDelimiter + "VoterID" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "Section" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "Start date" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "End date" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "IP" + textDelimiter);
            if (scored)
            {
                csvData.Append(fieldDelimiter + textDelimiter + "Score" + textDelimiter);
            }
            csvData.Append(fieldDelimiter + textDelimiter + "Email" + textDelimiter);
            csvData.Append(fieldDelimiter + textDelimiter + "UserName" + textDelimiter);

            // Build CSV header
            foreach (CSVExportData.ExportAnswersRow headerColumn in csvExportData.ExportAnswers.Rows)
            {

                headerColumn.ColumnHeader = System.Text.RegularExpressions.Regex.Replace(GetHeader(headerColumn), "<[^>]*>", " ");
                csvData.Append(fieldDelimiter + textDelimiter + headerColumn.ColumnHeader.Replace("[[", "").Replace("]]", "").Replace("!", "").Replace(textDelimiter, textDelimiter + textDelimiter) + textDelimiter);
            }

            WebSecurityAddInCollection securityAddIns = WebSecurityAddInFactory.CreateWebSecurityAddInCollection(new SecurityAddIns().GetWebSecurityAddIns(SurveyId), ViewState, null);
            NameValueCollection addInVoterData;

            if (csvExportData.Voters.Rows.Count > 0)
            {

                // Get security addins data if any available and get key name
                // to add to the export header
                for (int i = 0; i < securityAddIns.Count; i++)
                {
                    addInVoterData = securityAddIns[i].GetAddInVoterData(csvExportData.Voters[0].VoterID);
                    if (addInVoterData != null)
                    {
                        for (int j = 0; j < addInVoterData.Count; j++)
                        {
                            csvData.Append(string.Format("{0}{1}{2}{1}",
                                fieldDelimiter, textDelimiter, addInVoterData.GetKey(j).Replace(textDelimiter, textDelimiter + textDelimiter)));
                        }
                    }
                }
            }

            foreach (CSVExportData.VotersRow voter in csvExportData.Voters.Rows)
            {

                for (int voterSections = 0; voterSections <= GetVoterMaxSections(voter.VoterID, csvExportData); voterSections++)
                {
                    csvData.Append(System.Environment.NewLine);
                    csvData.Append(textDelimiter + voter.VoterID + textDelimiter);
                    csvData.Append(fieldDelimiter + textDelimiter + voterSections + textDelimiter);
                    csvData.Append(fieldDelimiter + textDelimiter + voter.StartDate + textDelimiter);
                    csvData.Append(fieldDelimiter + textDelimiter + voter.VoteDate + textDelimiter);
                    csvData.Append(fieldDelimiter + textDelimiter + voter.IPSource + textDelimiter);
                    if (scored)
                    {
                        csvData.Append(fieldDelimiter + textDelimiter + voter.Score + textDelimiter);
                    }
                    csvData.Append(fieldDelimiter + textDelimiter + voter.Email + textDelimiter);
                    csvData.Append(fieldDelimiter + textDelimiter + voter.UserName + textDelimiter);

                    // reparse all answers to see which answer was answered or not by the voter
                    foreach (CSVExportData.ExportAnswersRow headerColumn in csvExportData.ExportAnswers.Rows)
                    {
                        // Check if the voter has answered
                        CSVExportData.VoterAnswersRow[] answer = (CSVExportData.VoterAnswersRow[])csvExportData.VoterAnswers.Select(string.Format("VoterID={0} AND AnswerID = {1} AND SectionNumber={2}",
                            voter.VoterID, headerColumn.AnswerId, voterSections));
                        if (answer.Length > 0)
                        {
                            int i = answer[0].AnswerTypeId;

                            if (answer[0].IsAnswerTextNull())
                            {
                                csvData.Append(fieldDelimiter + textDelimiter + 1 + textDelimiter);
                            }
                            else
                            {
                                switch (CarriageReturnDropDownList.SelectedValue)
                                {
                                    case "1":
                                        {
                                            csvData.Append(fieldDelimiter + textDelimiter + GetDetail(answer[0], (AnswerTypeEnum)headerColumn.AnswerTypeId).Replace(textDelimiter, textDelimiter + textDelimiter).Replace(Environment.NewLine, ((char)10).ToString()) + textDelimiter);
                                            break;
                                        }
                                    case "2":
                                        {
                                            csvData.Append(fieldDelimiter + textDelimiter + GetDetail(answer[0], (AnswerTypeEnum)headerColumn.AnswerTypeId).Replace(textDelimiter, textDelimiter + textDelimiter).Replace(Environment.NewLine, CRCharTextbox.Text) + textDelimiter);
                                            break;
                                        }
                                    default:
                                        {
                                            csvData.Append(fieldDelimiter + textDelimiter + GetDetail(answer[0], (AnswerTypeEnum)headerColumn.AnswerTypeId).Replace(textDelimiter, textDelimiter + textDelimiter) + textDelimiter);
                                            break;
                                        }

                                }
                            }
                        }
                        else
                        {
                            csvData.Append(fieldDelimiter + textDelimiter + textDelimiter);
                        }
                    }

                    // Get security addins data if any available
                    for (int i = 0; i < securityAddIns.Count; i++)
                    {
                        addInVoterData = securityAddIns[i].GetAddInVoterData(voter.VoterID);
                        if (addInVoterData != null)
                        {
                            for (int j = 0; j < addInVoterData.Count; j++)
                            {
                                if (addInVoterData[j] != null)
                                {
                                    switch (CarriageReturnDropDownList.SelectedValue)
                                    {
                                        case "1":
                                            {
                                                csvData.Append(string.Format("{0}{1}{2}{1}",
                                                    fieldDelimiter, textDelimiter, addInVoterData[j].Replace(textDelimiter, textDelimiter + textDelimiter).Replace(Environment.NewLine, ((char)10).ToString())));
                                                break;
                                            }
                                        case "2":
                                            {
                                                csvData.Append(string.Format("{0}{1}{2}{1}",
                                                    fieldDelimiter, textDelimiter, addInVoterData[j].Replace(textDelimiter, textDelimiter + textDelimiter).Replace(Environment.NewLine, CRCharTextbox.Text)));
                                                break;
                                            }
                                        default:
                                            {
                                                csvData.Append(string.Format("{0}{1}{2}{1}",
                                                    fieldDelimiter, textDelimiter, addInVoterData[j].Replace(textDelimiter, textDelimiter + textDelimiter)));
                                                break;
                                            }

                                    }
                                }
                                else
                                {
                                    csvData.Append(fieldDelimiter + textDelimiter + textDelimiter);
                                }
                            }
                        }
                    }
                }
            }

            return csvData.ToString();
        }
        /// <summary>
        /// Must create and return the control 
        /// that will show the administration interface
        /// If none is available returns null
        /// </summary>
        public Control GetAdministrationInterface(Style controlStyle)
        {
            Table table = new Table();
            table.ControlStyle.CopyFrom(controlStyle); //CSS questionBuilder
            table.Width = Unit.Percentage(100);

            int maxEntries = 0;
            int entryCount = 0;
            string maxReachedMessage = ResourceManager.GetString("QuotaReachedMessage", this.LanguageCode);
 
            SurveyEntryQuotaData quotaSettings = new Surveys().GetQuotaSettings(this.SurveyId);
            if (quotaSettings.SurveyEntryQuotas.Rows.Count > 0)
            {
                maxEntries = quotaSettings.SurveyEntryQuotas[0].MaxEntries;
                entryCount = quotaSettings.SurveyEntryQuotas[0].EntryCount;
                maxReachedMessage = quotaSettings.SurveyEntryQuotas[0].MaxReachedMessage;
            }

            this._entryCount.Text = entryCount.ToString();


            table.Rows.Add(this.BuildRow(this._entryCount, ResourceManager.GetString("EntriesNumberLabel", this.LanguageCode), controlStyle));
            this._maxEntryTextBox = new TextBox();
            this._maxEntryTextBox.Text = maxEntries.ToString();
            this._maxEntryTextBox.Width = Unit.Pixel(40);

            table.Rows.Add(this.BuildRow(this._maxEntryTextBox, ResourceManager.GetString("MaxQuotaEntriesLabel", this.LanguageCode), controlStyle));

            table.Rows.Add(this.BuildRow(null, ResourceManager.GetString("QuotaReachedLabel", this.LanguageCode), controlStyle));

            //ckeditor row:
            this._maxReachedMessage = new CKEditor.NET.CKEditorControl();
            this._maxReachedMessage.BasePath = "~/Scripts/ckeditor";
            this._maxReachedMessage.config.enterMode = CKEditor.NET.EnterMode.BR;
            this._maxReachedMessage.Width = Unit.Percentage(100);
            this._maxReachedMessage.config.skin = "moonocolor";
            this._maxReachedMessage.Text = maxReachedMessage;

            table.Rows.Add(this.BuildRow(this._maxReachedMessage, null, controlStyle));
            
            PlaceHolder child = new PlaceHolder();

            Button button = new Button();
            button.Text = ResourceManager.GetString("ApplyChangesButton", this.LanguageCode);
            button.CssClass = "btn btn-primary btn-xs bw";
            button.Click += new EventHandler(this.OnUpdateClick);
            child.Controls.Add(button);

            Button button2 = new Button();
            button2.Text = ResourceManager.GetString("ResetQuotaEntriesButton", this.LanguageCode);
            button2.CssClass = "btn btn-primary btn-xs bw";
            button2.Click += new EventHandler(this.OnResetClick);
            child.Controls.Add(button2);

            table.Rows.Add(this.BuildRow(child, null, controlStyle));

            return table;
        }
        // OLD Freetextbox code:
        //private void ApplyPrivacyButton_Click(object sender, System.EventArgs e)
        //{
        //    SurveyData surveyData = new Surveys().GetSurveyById(SurveyId, LanguagesDropdownlist.SelectedValue);
        //    surveyData.Surveys[0].RedirectionURL = RedirectionURLTextBox.Text;
        //    surveyData.Surveys[0].ThankYouMessage = ThankYouFreeTextBox.Text.Length > 3900 ?
        //        ThankYouFreeTextBox.Text.Substring(0, 3900) : ThankYouFreeTextBox.Text;

        //    // Update the DB
        //    new Survey().UpdateSurvey(surveyData, LanguagesDropdownlist.SelectedValue);

        //    ((PageBase)Page).ShowNormalMessage(MessageLabel, ((PageBase)Page).GetPageResource("SurveyUpdatedMessage"));
        //    MessageLabel.Visible = true;
        //}

        //New section for CKeditor - 2013/06/18:
        private void ApplyPrivacyButton_Click(object sender, System.EventArgs e)
        {
            SurveyData surveyData = new Surveys().GetSurveyById(SurveyId, LanguagesDropdownlist.SelectedValue);
            surveyData.Surveys[0].RedirectionURL = RedirectionURLTextBox.Text;
            surveyData.Surveys[0].ThankYouMessage = ThankYouCKEditor.Text.Length > 3900 ?
                ThankYouCKEditor.Text.Substring(0, 3900) : ThankYouCKEditor.Text;

            // Update the DB
            new Survey().UpdateSurvey(surveyData, LanguagesDropdownlist.SelectedValue);

            ((PageBase)Page).ShowNormalMessage(MessageLabel, ((PageBase)Page).GetPageResource("SurveyUpdatedMessage"));
            MessageLabel.Visible = true;
        }
        /// <summary>
        /// Builds the Question list table with
        /// the edit options
        /// </summary>
        private void BuildQuestionList()
        {
            _questionsData = new Questions().GetQuestions(SurveyId, LanguagesDropdownlist.SelectedValue);
            int currentPage = 1,
                previousDisplayOrder = 0,
                totalPages = new Surveys().GetPagesNumber(SurveyId);

            Table questionsContainer = new Table();
            questionsContainer.Width = Unit.Percentage(100);
            Table questionTable = new Table();
            // moved to css file
            // questionTable.CellSpacing = 2;
            // questionTable.CellPadding = 4;
            questionTable.CssClass = "questionBuilder";

            TableRow pageBreakRow = BuildRow(null);

            // always add first page 
            questionTable.Rows.Add(pageBreakRow);

            foreach (QuestionData.QuestionsRow question in _questionsData.Questions.Rows)
            {
                while (question.PageNumber > currentPage)
                {
                    var lastq = _questionsData.Questions
                        .AsEnumerable().Where(x => x.PageNumber < currentPage)
                        .OrderByDescending(x => x.DisplayOrder).FirstOrDefault();
                    int displayOrder = lastq == null ? 0 : lastq.DisplayOrder + 1;
                    pageBreakRow.Cells[0].Controls.Add(BuildPageBreakOptionsRow(currentPage, totalPages, displayOrder));

                    currentPage++;
                    questionsContainer.Rows.Add(BuildRow(questionTable));
                    QuestionListPlaceHolder.Controls.Add(questionsContainer);

                    // Creates a new page
                    questionsContainer = new Table();
                    questionsContainer.Width = Unit.Percentage(100);
                    questionTable = new Table();
                    // moved to css file:
                    // questionTable.CellSpacing = 2;
                    // questionTable.CellPadding = 4;
                    questionTable.CssClass = "questionBuilder";

                    pageBreakRow = BuildRow(null);
                    questionTable.Rows.Add(pageBreakRow);
                }

                if (question.PageNumber == currentPage)
                {
                    AddQuestionWebControl(questionTable, question);
                    previousDisplayOrder = question.DisplayOrder;
                }
            }

            pageBreakRow.Cells[0].Controls.Add(BuildPageBreakOptionsRow(currentPage, totalPages, previousDisplayOrder));

            questionsContainer.Rows.Add(BuildRow(questionTable));
            QuestionListPlaceHolder.Controls.Add(questionsContainer);
        }
        /// <summary>
        /// Get the current DB stats and fill 
        /// the label with them
        /// </summary>
        private void BindData()
        {
            isScored = new Surveys().IsSurveyScored(SurveyId);

            TimeSpan timeTaken;
            _voterAnswers = new Voters().GetVoterAnswers(_voterId);

            if (!_voterAnswers.Voters[0].IsVoteDateNull() && !_voterAnswers.Voters[0].IsStartDateNull())
            {
                timeTaken = _voterAnswers.Voters[0].VoteDate - _voterAnswers.Voters[0].StartDate;
            }
            else
            {
                timeTaken = new TimeSpan(0);
            }

            VoterUIDLabel.Text = _voterId.ToString();
            IPAddressLabel.Text = _voterAnswers.Voters[0].IPSource;
            VoteDateLabel.Text = _voterAnswers.Voters[0].VoteDate.ToString();
            VoterEmail.Text = _voterAnswers.Voters[0].IsEmailNull() ? GetPageResource("AnonymousVoteInfo") : _voterAnswers.Voters[0].Email;
            VoterUserName.Text = _voterAnswers.Voters[0].IsContextUserNameNull() ?  GetPageResource("ContextUserNameDisabled") : _voterAnswers.Voters[0].ContextUserName;
            VoterLanguageValueLabel.Text = _voterAnswers.Voters[0].IsLanguageCodeNull() || _voterAnswers.Voters[0].LanguageCode.Length == 0 ?
                GetPageResource("LanguageUndefined") : _voterAnswers.Voters[0].LanguageCode;
            TimeToTakeSurveyLabel.Text = string.Format("{0} {1}, {2} secs.", timeTaken.Minutes.ToString(), GetPageResource("MinutesInfo"), timeTaken.Seconds.ToString());

            WebSecurityAddInCollection securityAddIns = WebSecurityAddInFactory.CreateWebSecurityAddInCollection(new SecurityAddIns().GetWebSecurityAddIns(SurveyId), ViewState, null);
            NameValueCollection addInVoterData;
            for (int i=0;i<securityAddIns.Count;i++)
            {
                addInVoterData = securityAddIns[i].GetAddInVoterData(_voterId);
                if (addInVoterData != null)
                {
                    // Creates a new addin voter details page
                    SecurityAddInVoterReportControl addInVoterControl =
                        (SecurityAddInVoterReportControl)LoadControl("UserControls/SecurityAddInVoterReportControl.ascx");

                    addInVoterControl.AddInDescription = securityAddIns[i].Description;
                    addInVoterControl.AddInVoterData = addInVoterData;
                    AddInVoterDataPlaceHolder.Controls.Add(addInVoterControl);
                }
            }

            _questionData = new Questions().GetQuestionHierarchy(SurveyId);
            QuestionsDataGrid.DataSource = GetParentQuestions();
            QuestionsDataGrid.DataKeyField = "QuestionId";
            QuestionsDataGrid.DataBind();
            if (isScored)
            {
                VoterScoreTotalLabel.Text = GetPageResource("VoterScoreTotalLabel") + _totalScore.ToString();
            }
        }
        /// <summary>
        /// Get conditional thanks message based
        /// on user's answers
        /// </summary>
        public string GetThanksMessage(int surveyId, VoterAnswersData surveyAnswers, bool evaluateScores)
        {
            MessageConditionData surveyMessageConditions = new Surveys().GetSurveyMessageConditions(surveyId);
            if ((surveyMessageConditions.MessageConditions.Rows.Count > 0) && (surveyAnswers.Voters.Count > 0))
            {
                DataRow[] rowArray = null;
                string thankYouMessage = null;
                int scoreTotal = evaluateScores ? this.GetScoreTotal(surveyAnswers) : 0;
                foreach (MessageConditionData.MessageConditionsRow row in surveyMessageConditions.MessageConditions.Rows)
                {
                    if ((evaluateScores && (row.MessageConditionalOperator == 3)) && (scoreTotal < row.Score))
                    {
                        thankYouMessage = row.ThankYouMessage;
                    }
                    if ((evaluateScores && (row.MessageConditionalOperator == 2)) && (scoreTotal == row.Score))
                    {
                        thankYouMessage = row.ThankYouMessage;
                    }
                    if ((evaluateScores && (row.MessageConditionalOperator == 4)) && (scoreTotal > row.Score))
                    {
                        thankYouMessage = row.ThankYouMessage;
                    }
                    if ((evaluateScores && (row.MessageConditionalOperator == 5)) && ((scoreTotal >= row.Score) && (scoreTotal <= row.ScoreMax)))
                    {
                        thankYouMessage = row.ThankYouMessage;
                    }
                    if (row.MessageConditionalOperator != 1)
                    {
                        continue;
                    }
                    int num2 = evaluateScores ? new Question().GetQuestionAnswersScore(row.QuestionId, surveyAnswers) : 0;
                    if ((evaluateScores && (row.ConditionalOperator == 3)) && (num2 == row.Score))
                    {
                        thankYouMessage = row.ThankYouMessage;
                    }
                    if ((evaluateScores && (row.ConditionalOperator == 4)) && (num2 < row.Score))
                    {
                        thankYouMessage = row.ThankYouMessage;
                    }
                    if ((evaluateScores && (row.ConditionalOperator == 5)) && (num2 > row.Score))
                    {
                        thankYouMessage = row.ThankYouMessage;
                    }
                    if ((evaluateScores && (row.ConditionalOperator == 6)) && ((num2 >= row.Score) && (num2 <= row.ScoreMax)))
                    {
                        thankYouMessage = row.ThankYouMessage;
                    }
                    if (!row.IsAnswerIdNull() && !row.IsTextFilterNull())
                    {
                        string expression = this.EscapeFilterString(row.TextFilter);
                        if ((!row.IsExpressionOperatorNull() && (row.ExpressionOperator != 2)) && Information.IsDate(expression))
                        {
                            expression = "#" + expression + "#";
                        }
                        else if ((row.ExpressionOperator != 2) && !Information.IsNumeric(expression))
                        {
                            expression = "'" + expression + "'";
                        }
                        try
                        {
                            switch (row.ExpressionOperator)
                            {
                                case 1:
                                    rowArray = surveyAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText = ", expression }));
                                    goto Label_03F9;

                                case 3:
                                    rowArray = surveyAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText > ", expression }));
                                    goto Label_03F9;

                                case 4:
                                    rowArray = surveyAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText < ", expression }));
                                    goto Label_03F9;
                            }
                            rowArray = surveyAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText like '%", expression, "%'" }));
                        }
                        catch (EvaluateException)
                        {
                        }
                    }
                    else if (!row.IsAnswerIdNull())
                    {
                        rowArray = surveyAnswers.VotersAnswers.Select("AnswerId=" + row.AnswerId);
                    }
                    else if (row.IsAnswerIdNull())
                    {
                        rowArray = surveyAnswers.VotersAnswers.Select("QuestionId=" + row.QuestionId);
                    }
                    else
                    {
                        rowArray = null;
                    }
                Label_03F9:
                    if ((((rowArray != null) && (row.ConditionalOperator == 1)) && (rowArray.Length > 0)) || ((row.ConditionalOperator == 2) && (rowArray.Length == 0)))
                    {
                        thankYouMessage = row.ThankYouMessage;
                        break;
                    }
                }
                if (thankYouMessage != null)
                {
                    return ParseThankYouMessage(thankYouMessage, scoreTotal);
                }
            }
            return null;
        }
        /// <summary>
        /// Get the current DB stats and fill 
        /// the label with them
        /// </summary>
        private void FillFields()
        {
            MultiLanguageData surveyLanguages = new MultiLanguages().GetSurveyLanguages(SurveyId);

            SurveyData surveySettings = new Surveys().GetSurveyById(SurveyId, "");
            if ((MultiLanguageMode)surveySettings.Surveys[0].MultiLanguageModeId != MultiLanguageMode.None)
            {
                MultiLanguagesPlaceHolder.Visible = true;
                MultiLanguagesCheckBox.Checked = true;
                MultiLanguagesModeDropDownList.SelectedValue = surveySettings.Surveys[0].MultiLanguageModeId.ToString();

                if (int.Parse(MultiLanguagesModeDropDownList.SelectedValue) == (int)MultiLanguageMode.Cookie ||
                    int.Parse(MultiLanguagesModeDropDownList.SelectedValue) == (int)MultiLanguageMode.QueryString ||
                    int.Parse(MultiLanguagesModeDropDownList.SelectedValue) == (int)MultiLanguageMode.Session)
                {
                    VariableNameLabel.Visible = true;
                    VariableNameTextBox.Visible = true;
                    VariableNameTextBox.Text = surveySettings.Surveys[0].MultiLanguageVariable;
                    VariableNameUpdateButton.Visible = true;
                    VariableNameInfoLabel.Visible = true;
                }
                else
                {
                    VariableNameLabel.Visible = false;
                    VariableNameTextBox.Text = string.Empty;
                    VariableNameTextBox.Visible = false;
                    VariableNameUpdateButton.Visible = false;
                    VariableNameInfoLabel.Visible = false;
                }
            }
            else
            {
                MultiLanguagesPlaceHolder.Visible = false;
                MultiLanguagesCheckBox.Checked = false;
            }

            DisabledLanguagesListBox.DataSource = new MultiLanguages().GetMultiLanguages();
            DisabledLanguagesListBox.DataMember = "MultiLanguages";
            DisabledLanguagesListBox.DataTextField = "LanguageDescription";
            DisabledLanguagesListBox.DataValueField = "LanguageCode";
            DisabledLanguagesListBox.DataBind();

            EnabledLanguagesListBox.DataSource = surveyLanguages;
            EnabledLanguagesListBox.DataMember = "MultiLanguages";
            EnabledLanguagesListBox.DataTextField = "LanguageDescription";
            EnabledLanguagesListBox.DataValueField = "LanguageCode";
            EnabledLanguagesListBox.DataBind();

            foreach (ListItem enabledItem in EnabledLanguagesListBox.Items)
            {
                ListItem disabledItem = DisabledLanguagesListBox.Items.FindByValue(enabledItem.Value);
                if (disabledItem != null)
                {
                    DisabledLanguagesListBox.Items.Remove(disabledItem);
                }
            }

            DefaultLanguageDropdownlist.Items.Clear();
            foreach (MultiLanguageData.MultiLanguagesRow language in surveyLanguages.MultiLanguages)
            {
                ListItem defaultItem = new ListItem(language.LanguageDescription, language.LanguageCode);
                if (language.DefaultLanguage)
                {
                    defaultItem.Selected = true;
                }

                DefaultLanguageDropdownlist.Items.Add(defaultItem);
            }

            ((PageBase)Page).TranslateListControl(DefaultLanguageDropdownlist);
            ((PageBase)Page).TranslateListControl(DisabledLanguagesListBox);
            ((PageBase)Page).TranslateListControl(EnabledLanguagesListBox);
        }
		/// <summary>
		///  Get the existing message condition
		///  and restore the UI
		/// </summary>
		private void BindUpdate()
		{
			MessageConditionData messageConditionData = new Surveys().GetSurveyMessageCondition(_messageConditionId);
			if (messageConditionData.MessageConditions.Rows.Count > 0)
			{
				MessageConditionData.MessageConditionsRow messageCondition = 
					(MessageConditionData.MessageConditionsRow)messageConditionData.MessageConditions[0];
			
				if (MessageConditionDropdownlist.Items.FindByValue(messageCondition.MessageConditionalOperator.ToString()) != null)
				{
					MessageConditionDropdownlist.SelectedValue = messageCondition.MessageConditionalOperator.ToString();
				}

                ConditionCKeditor.Text = messageCondition.ThankYouMessage;

				// Check if condition is based on the survey's score or on its questions answers
				if (_isScored && (messageCondition.MessageConditionalOperator == (int)MessageConditionalOperator.ScoredLess ||
					messageCondition.MessageConditionalOperator == (int)MessageConditionalOperator.ScoreEquals ||
					messageCondition.MessageConditionalOperator == (int)MessageConditionalOperator.ScoreGreater))
				{
					ScoreTextbox.Text = messageCondition.Score.ToString();
					HideFields(true, true, false, false, true, false, true);
				}
				else if (_isScored && messageCondition.MessageConditionalOperator == (int)MessageConditionalOperator.ScoreRange)
				{
					ScoreTextbox.Text = messageCondition.Score.ToString();
					ScoreMaxTextbox.Text = messageCondition.ScoreMax.ToString();
					HideFields(true, true, false, false, false, false, true);
				}
				// User selected a condition from a question's answer
				else if (messageCondition.MessageConditionalOperator == (int)MessageConditionalOperator.QuestionAnswer)
				{
					QuestionFilterDropdownlist.SelectedValue = messageCondition.QuestionId.ToString();

					if (_isScored && (messageCondition.ConditionalOperator == (int)ConditionalOperator.ScoredLess ||
						messageCondition.ConditionalOperator == (int)ConditionalOperator.ScoreEquals ||
						messageCondition.ConditionalOperator == (int)ConditionalOperator.ScoreGreater))
					{
						ScoreTextbox.Text = messageCondition.Score.ToString();
						HideFields(false, true, false, false, true, false, false);
					}
					else if (_isScored && messageCondition.ConditionalOperator == (int)ConditionalOperator.ScoreRange)
					{
						ScoreTextbox.Text = messageCondition.Score.ToString();
						ScoreMaxTextbox.Text = messageCondition.ScoreMax.ToString();
						HideFields(false, true, false, false, false,false, false);
					}
					else
					{
						BindAnswerDropDownList();

						// Is the question's answer a field type
						if (!messageCondition.IsAnswerIdNull() && 
							AnswerFilterDropdownlist.Items.FindByValue((-messageCondition.AnswerId).ToString()) != null)
						{
							AnswerFilterDropdownlist.SelectedValue = (-messageCondition.AnswerId).ToString();
							HideFields(false,false, false, true, true, false, false);
							
							// Set text filter and show it
							TextFilterTextbox.Text = messageCondition.TextFilter;
							TextFilterTextbox.Visible = true;
							FilterTextLabel.Visible = true;
							ExpressionLogicDropdownlist.SelectedValue = messageCondition.ExpressionOperator.ToString();
							ExpressionLogicDropdownlist.Visible = true;
							TextEvaluationConditionLabel.Visible = true;

						}
						else
						{
							AnswerFilterDropdownlist.SelectedValue = messageCondition.IsAnswerIdNull() ?
								"0" : messageCondition.AnswerId.ToString();
							HideFields(false,false, false, true, true, false, false);
						}
					}

					LogicDropDownList.SelectedValue = messageCondition.ConditionalOperator.ToString();
				}
			}

		}
 private void ShowSurveyDDL()
 {
     var surveys=new Surveys().GetAssignedSurveysList(((PageBase)Page).NSurveyUser.Identity.UserId);
  
     if (surveys.Surveys.Count == 1) { InitiateSurvey(surveys.Surveys[0].SurveyId); return; }
     if (surveys.Surveys.Count == 0) { int s = ((PageBase)Page).SurveyId; return; }
     ddlSurveys.Items.Clear();
     ddlSurveys.Items.Add(new ListItem(GetPageResource("DDLSelectValue"), "-1"));
     ddlSurveys.AppendDataBoundItems = true;
     ddlSurveys.DataSource = surveys.Surveys;
     ddlSurveys.DataTextField = "Title";
     ddlSurveys.DataValueField = "SurveyId";
     ddlSurveys.DataBind();
     ddlSurveys.Visible = true;
     ChooseSurveyLabel.Visible = true;
 }
		void BuildQuestionList()
		{
			QuestionData _questionsData = new Questions().GetAnswerableQuestionWithoutChilds(SurveyId);
			int currentPage = 1,
				previousDisplayOrder = 0,
				totalPages = new Surveys().GetPagesNumber(SurveyId);
			
			Table questionsContainer = new Table();
			questionsContainer.Width = Unit.Percentage(100);
			Table questionTable = new Table();
			questionTable.CellSpacing = 2;
			questionTable.CellPadding = 4;
			questionTable.CssClass = "questionBuilder";
				
			questionTable.Rows.Add(BuildPageBreakOptionsRow(currentPage, totalPages,previousDisplayOrder));
			foreach (QuestionData.QuestionsRow question in _questionsData.Questions.Rows)
			{
				while (question.PageNumber > currentPage)
				{
					currentPage++;

					questionsContainer.Rows.Add(BuildRow(questionTable));
					EditAnswersPlaceHolder.Controls.Add(questionsContainer);

					// Creates a new page
					questionsContainer = new Table();
					questionsContainer.Width = Unit.Percentage(100);
					questionTable = new Table();
					questionTable.CellSpacing = 2;
					questionTable.CellPadding = 4;
					questionTable.CssClass = "questionBuilder";
					questionTable.Rows.Add(BuildPageBreakOptionsRow(currentPage, totalPages,previousDisplayOrder));
				}

				if (question.PageNumber == currentPage)
				{
					AddQuestionWebControl(questionTable, question);
					previousDisplayOrder = question.DisplayOrder;
				}
			}

			questionsContainer.Rows.Add(BuildRow(questionTable));
			EditAnswersPlaceHolder.Controls.Add(questionsContainer);
		}
        /// <summary>
        /// Bind the fields
        /// </summary>
        private void FillFields()
        {
            string surveyLink;
            string firstNamelastname = GetPageResource("FromNameTextBox");
            var survey = new Surveys().GetSurveyById(SurveyId, null).Surveys[0];

            if (Request.ServerVariables["SERVER_PORT"] != null && Request.ServerVariables["SERVER_PORT"] != "80")
            {
                if (HttpContext.Current.Request.ApplicationPath != "/")
                {
                    surveyLink = string.Format("http://{0}:{1}{2}/surveymobile.aspx?surveyid={3}&uid=[--invitationid-]",
                        Request.ServerVariables["SERVER_NAME"], Request.ServerVariables["SERVER_PORT"], HttpContext.Current.Request.ApplicationPath, survey.SurveyGuid);
                }
                else
                {
                    surveyLink = string.Format("http://{0}:{1}/surveymobile.aspx?surveyid={2}&uid=[--invitationid-]",
                        Request.ServerVariables["SERVER_NAME"], Request.ServerVariables["SERVER_PORT"], survey.SurveyGuid);
                }
            }
            else
            {
                if (HttpContext.Current.Request.ApplicationPath != "/")
                {
                    surveyLink = string.Format("http://{0}{1}/surveymobile.aspx?surveyid={2}&uid=[--invitationid-]",
                        Request.ServerVariables["SERVER_NAME"], HttpContext.Current.Request.ApplicationPath, survey.SurveyGuid);
                }
                else
                {
                    surveyLink = string.Format("http://{0}/surveymobile.aspx?surveyid={1}&uid=[--invitationid-]",
                        Request.ServerVariables["SERVER_NAME"], survey.SurveyGuid);
                }
            }

            if (NSurveyUser.Identity is NSurveyFormIdentity)
            {
                firstNamelastname =
                    ((NSurveyFormIdentity)NSurveyUser.Identity).FirstName + " " + ((NSurveyFormIdentity)NSurveyUser.Identity).LastName;
                
            }

            MailingCKEditor.Text =
                string.Format(GetPageResource("InvitationMessageTextBox"), survey.Title, surveyLink, firstNamelastname);
        }
        private string ExportCSVStyleOne()
        {
            try
            {
                DateTime startDate;
                DateTime endDate;
                if (rdAllDates.Checked)
                {
                    startDate = new DateTime(2004, 1, 1);
                    endDate = DateTime.Today;
                }
                else
                {
                    startDate = DateTime.Parse(StartDateTextBox.Text);
                    endDate =  DateTime.Parse(EndDateTextBox.Text);
                }

                System.Text.StringBuilder csvData = new System.Text.StringBuilder();
                bool scored = new Surveys().IsSurveyScored(SurveyId);

                // Get an instance of the voter DAL using the DALFactory
                CSVExportData csvExportData = new Voters().GetCSVExport(SurveyId, startDate, endDate);


                string textDelimiter = TextDelimiterTextBox.Text,
                    fieldDelimiter = FieldDelimiterTextBox.Text;
                csvData.Append(textDelimiter + "VoterID" + textDelimiter);
                csvData.Append(Delimit("Section"));
                csvData.Append(Delimit("Start date"));
                csvData.Append(Delimit("End date"));
                csvData.Append(Delimit("IP"));
                if (scored)
                {
                    csvData.Append(Delimit("Score"));
                }
                csvData.Append(Delimit("Email"));
                csvData.Append(Delimit("UserName"));

                // Build CSV header
                //
                //Whenever question Changes we need to detect
                int questionIdPrev = -1;
                foreach (CSVExportData.ExportAnswersRow headerColumn in csvExportData.ExportAnswers.Rows)
                {
                    QuestionSelectionMode selectionMode;
                    if (headerColumn.QuestionId != questionIdPrev) // Detect Question Change to emit Question Text alone for Certain conditions
                    {
                        selectionMode = (QuestionSelectionMode)headerColumn.SelectionModeId;
                        questionIdPrev = headerColumn.QuestionId;
                        if (csvExportData.ExportAnswers.FirstOrDefault(x => x.QuestionId == questionIdPrev &&
                           ((AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionTextType)) != null)
                            csvData.Append(StripCharactesAndDelimit(GetQuestionOnlyHeader(headerColumn)));

                        // New requirement for Others we need a seperate column
                        var firstRec = csvExportData.ExportAnswers.FirstOrDefault(x => x.QuestionId == questionIdPrev &&
                           ((AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionOtherType));
                        if (firstRec != null)
                            csvData.Append(StripCharactesAndDelimit(GetHeader(firstRec)));
                    }
                    if ((AnswerTypeEnum)headerColumn.AnswerTypeId != AnswerTypeEnum.SelectionTextType && //Selection Types go Under Question Header
                       (AnswerTypeEnum)headerColumn.AnswerTypeId != AnswerTypeEnum.SelectionOtherType)
                        csvData.Append(StripCharactesAndDelimit(GetHeader(headerColumn)));
                }

                WebSecurityAddInCollection securityAddIns = WebSecurityAddInFactory.CreateWebSecurityAddInCollection(new SecurityAddIns().GetWebSecurityAddIns(SurveyId), ViewState, null);
                NameValueCollection addInVoterData;

                if (csvExportData.Voters.Rows.Count > 0)
                {

                    // Get security addins data if any available and get key name
                    // to add to the export header
                    for (int i = 0; i < securityAddIns.Count; i++)
                    {
                        addInVoterData = securityAddIns[i].GetAddInVoterData(csvExportData.Voters[0].VoterID);
                        if (addInVoterData != null)
                        {
                            for (int j = 0; j < addInVoterData.Count; j++)
                                csvData.Append(Delimit(ReplaceDelimitersInText(addInVoterData.GetKey(j), textDelimiter)));
                        }
                    }
                }

                foreach (CSVExportData.VotersRow voter in csvExportData.Voters.Rows)
                {

                    for (int voterSections = 0; voterSections <= GetVoterMaxSections(voter.VoterID, csvExportData); voterSections++)
                    {
                        csvData.Append(System.Environment.NewLine);

                        csvData.Append(textDelimiter + voter.VoterID + textDelimiter);
                        csvData.Append(fieldDelimiter + textDelimiter + voterSections + textDelimiter);
                        csvData.Append(fieldDelimiter + textDelimiter + voter.StartDate + textDelimiter);
                        csvData.Append(fieldDelimiter + textDelimiter + voter.VoteDate + textDelimiter);
                        csvData.Append(fieldDelimiter + textDelimiter + voter.IPSource + textDelimiter);
                        if (scored)
                        {
                            csvData.Append(fieldDelimiter + textDelimiter + voter.Score + textDelimiter);
                        }
                        csvData.Append(fieldDelimiter + textDelimiter + voter.Email + textDelimiter);
                        csvData.Append(fieldDelimiter + textDelimiter + voter.UserName + textDelimiter);


                        // For every new question concatenate with # all Select type Answers and emit as first row
                        // Thereafter look only at non select type answers
                        //Do the above only if the Voter has answered the question
                        //
                        questionIdPrev = -1;

                        foreach (CSVExportData.ExportAnswersRow headerColumn in csvExportData.ExportAnswers.Rows)
                        {
                            if (headerColumn.QuestionId != questionIdPrev) // Detect Question Change to emit Question Text alone for Certain conditions
                            {
                                questionIdPrev = headerColumn.QuestionId;
                                //if this question has any answers of type Select then we need to emit the Question Text
                                // Once that is done skip all Select type questions as they have only one answer and it goes under Question heading

                                string concatenatedOthers = string.Empty;
                                if (csvExportData.ExportAnswers.FirstOrDefault(x => x.QuestionId == questionIdPrev && (AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionOtherType) != null)
                                {
                                    csvExportData.VoterAnswers
                                        .Where(x => x.VoterID == voter.VoterID &&
                                               x.QuestionId == questionIdPrev &&
                                               x.SectionNumber == voterSections &&
                                               (AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionOtherType)
                                       .ToList().ForEach(y => concatenatedOthers += GetDetail(y, AnswerTypeEnum.SelectionOtherType) +
                                           (MultiSeparatorTextBox.Text == string.Empty ? "#" : MultiSeparatorTextBox.Text));
                                    // csvData.Append(ReplaceCRAndDelimitAnswers(concatenatedOthers.TrimEnd('#')));
                                }

                                string concatenatedAnswers = string.Empty;
                                if (csvExportData.ExportAnswers.FirstOrDefault(x => x.QuestionId == questionIdPrev &&
                                   (AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionTextType) != null)
                                {
                                    csvExportData.VoterAnswers
                                        .Where(x => x.VoterID == voter.VoterID &&
                                               x.QuestionId == questionIdPrev &&
                                               x.SectionNumber == voterSections &&
                                               (AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionTextType)
                                       .ToList().ForEach(y => concatenatedAnswers += GetDetail(y, AnswerTypeEnum.SelectionTextType) +
                                       (MultiSeparatorTextBox.Text == string.Empty ? "#" : MultiSeparatorTextBox.Text));



                                }

                                //Another change.If the there is Other types get the heading of the orher and add it.
                                // if ((headerColumn.SelectionModeId == 1 || headerColumn.SelectionModeId == 2) && !string.IsNullOrEmpty(concatenatedOthers))//radiobutton selection

                                if (!string.IsNullOrEmpty(concatenatedOthers))//radiobutton selection
                                {
                                    var dat = csvExportData.ExportAnswers.Where(x => x.QuestionId == questionIdPrev &&
                                                   (AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionOtherType).FirstOrDefault();
                                    if (dat != null)
                                    {
                                        concatenatedAnswers += GetAnswerOnlyHeader(dat);
                                    }

                                }
                                if (csvExportData.ExportAnswers.FirstOrDefault(x => x.QuestionId == questionIdPrev &&
                                  (AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionTextType) != null)
                                {
                                    csvData.Append(ReplaceCRAndDelimitAnswers(concatenatedAnswers.TrimEnd((MultiSeparatorTextBox.Text == string.Empty ? '#' : MultiSeparatorTextBox.Text[0]))));
                                }
                                if (csvExportData.ExportAnswers.FirstOrDefault(x => x.QuestionId == questionIdPrev && (AnswerTypeEnum)x.AnswerTypeId == AnswerTypeEnum.SelectionOtherType) != null)
                                {
                                    csvData.Append(ReplaceCRAndDelimitAnswers(concatenatedOthers.TrimEnd(MultiSeparatorTextBox.Text == string.Empty ? '#' : MultiSeparatorTextBox.Text[0])));
                                }

                            }

                            if (((AnswerTypeEnum)headerColumn.AnswerTypeId != AnswerTypeEnum.SelectionTextType &&
                                   (AnswerTypeEnum)headerColumn.AnswerTypeId != AnswerTypeEnum.SelectionOtherType))
                            {
                                // Check if the voter has answered
                                CSVExportData.VoterAnswersRow[] answer = (CSVExportData.VoterAnswersRow[])csvExportData.VoterAnswers.Select(string.Format("VoterID={0} AND AnswerID = {1} AND SectionNumber={2}",
                                    voter.VoterID, headerColumn.AnswerId, voterSections));
                                if (answer.Length > 0) csvData.Append(ReplaceCRAndDelimitAnswers(GetDetail(answer[0], (AnswerTypeEnum)headerColumn.AnswerTypeId)));
                                else csvData.Append(Delimit(string.Empty));
                            }
                        }

                        // Get security addins data if any available
                        for (int i = 0; i < securityAddIns.Count; i++)
                        {
                            addInVoterData = securityAddIns[i].GetAddInVoterData(voter.VoterID);
                            if (addInVoterData != null)
                            {
                                for (int j = 0; j < addInVoterData.Count; j++)
                                {
                                    if (addInVoterData[j] != null) csvData.Append(ReplaceCRAndDelimitAnswers(addInVoterData[j]));
                                    else csvData.Append(fieldDelimiter + textDelimiter + textDelimiter);

                                }
                            }
                        }
                    }
                }

                return csvData.ToString();
            }
            catch (Exception ex)
            {
                ShowErrorMessage(MessageLabel, ex.Message);
                return string.Empty;
            }
        }
        private void ExportSurveyButton_Click(object sender, System.EventArgs e)
        {
            NSurveyForm surveyForm = null;


            Response.Charset = "utf-8";
            Response.ContentType = "application/octet-stream";

            Response.ContentType = "text/xml";
            Response.AddHeader("Content-Disposition", "attachment; filename=\"SurveyExport" + SurveyId + ".xml\"");

            surveyForm = new Surveys().GetFormForExport(SurveyId);
            surveyForm.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);

            Response.End();
        }
        /// <summary>
        /// Get next page depending depending on the
        /// branching rules
        /// </summary>
        public int GetNextPage(int surveyId, int pageNumber, VoterAnswersData voterAnswers, bool evaluateScores)
        {
            BranchingRuleData surveyPageBranchingRules = new Surveys().GetSurveyPageBranchingRules(surveyId, pageNumber);
            if (surveyPageBranchingRules.BranchingRules.Rows.Count <= 0)
            {
                pageNumber++;
                return pageNumber;
            }
            int num = pageNumber + 1;
            DataRow[] rowArray = null;
            foreach (BranchingRuleData.BranchingRulesRow row in surveyPageBranchingRules.BranchingRules.Rows)
            {
                int num2 = evaluateScores ? new Question().GetQuestionAnswersScore(row.QuestionId, voterAnswers) : 0;
                if ((evaluateScores && (row.ConditionalOperator == 3)) && (num2 == row.Score))
                {
                    return row.TargetPageNumber;
                }
                if ((evaluateScores && (row.ConditionalOperator == 4)) && (num2 < row.Score))
                {
                    return row.TargetPageNumber;
                }
                if ((evaluateScores && (row.ConditionalOperator == 5)) && (num2 > row.Score))
                {
                    return row.TargetPageNumber;
                }
                if ((evaluateScores && (row.ConditionalOperator == 6)) && ((num2 >= row.Score) && (num2 <= row.ScoreMax)))
                {
                    return row.TargetPageNumber;
                }
                if (!row.IsAnswerIdNull() && !row.IsTextFilterNull())
                {
                    string expression = this.EscapeFilterString(row.TextFilter);
                    if ((!row.IsExpressionOperatorNull() && (row.ExpressionOperator != 2)) && Information.IsDate(expression))
                    {
                        expression = "#" + expression + "#";
                    }
                    else if ((row.ExpressionOperator != 2) && !Information.IsNumeric(expression))
                    {
                        expression = "'" + expression + "'";
                    }
                    try
                    {
                        switch (row.ExpressionOperator)
                        {
                            case 1:
                                rowArray = voterAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText = ", expression }));
                                goto Label_0319;

                            case 3:
                                rowArray = voterAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText > ", expression }));
                                goto Label_0319;

                            case 4:
                                rowArray = voterAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText < ", expression }));
                                goto Label_0319;
                        }
                        rowArray = voterAnswers.VotersAnswers.Select(string.Concat(new object[] { "AnswerId = ", row.AnswerId, " AND AnswerText like '%", expression, "%'" }));
                    }
                    catch (EvaluateException)
                    {
                    }
                }
                else if (!row.IsAnswerIdNull())
                {
                    rowArray = voterAnswers.VotersAnswers.Select("AnswerId=" + row.AnswerId);
                }
                else if (row.IsAnswerIdNull())
                {
                    rowArray = voterAnswers.VotersAnswers.Select("QuestionId=" + row.QuestionId);
                }
                else
                {
                    rowArray = null;
                }
            Label_0319:
                if ((((rowArray != null) && (row.ConditionalOperator == 1)) && (rowArray.Length > 0)) || ((row.ConditionalOperator == 2) && (rowArray.Length == 0)))
                {
                    return row.TargetPageNumber;
                }
            }
            return num;
        }
        private void ShowFriendlyUrl()
        {
            var survey = new Surveys().GetSurveyById(SurveyId, null).Surveys[0];

            if (!survey.IsFriendlyNameNull())
            {
                friendlyUrlLink.Visible = true;
                friendlyUrlLink.Text = GetUrl("/" + survey.FriendlyName);
                friendlyUrlLink.NavigateUrl = GetUrl("/" + survey.FriendlyName);

                friendlyMobileUrlLink.Visible = true;
                friendlyMobileUrlLink.Text = GetMobileUrl("/" + survey.FriendlyName);
                friendlyMobileUrlLink.NavigateUrl = GetMobileUrl("/" + survey.FriendlyName);


            }
            else
            {
                friendlyUrlLink.Visible = false;
                friendlyMobileUrlLink.Visible = false;
            }
        }
        /// <summary>
        /// Get the current DB data and fill 
        /// the fields with them
        /// </summary>
        private void BindFields()
        {


            DateFormatLabel.Text = (DateTime.Now).ToShortDateString();

            // Retrieve the survey data
            SurveyData surveyData = new Surveys().GetSurveyById(SurveyId, "");
            SurveyData.SurveysRow survey = surveyData.Surveys[0];

            // Assigns the retrieved data to the correct fields
            TitleTextBox.Text = survey.Title;
            ActiveCheckBox.Checked = survey.Activated;
            ArchiveCheckBox.Checked = survey.Archive;
            ScoredCheckbox.Checked = survey.Scored;
            QuestionNumberingCheckbox.Checked = survey.QuestionNumberingDisabled;
            OpeningDateTextBox.Text = survey.IsOpenDateNull() ? null : survey.OpenDate.ToShortDateString();
            CloseDateTextbox.Text = survey.IsCloseDateNull() ? null : survey.CloseDate.ToShortDateString();
            EnableNavigationCheckbox.Checked = survey.NavigationEnabled;
            EmailFromTextbox.Text = survey.EmailFrom;
            EmailToTextBox.Text = survey.EmailTo;
            EmailSubjectTextbox.Text = survey.EmailSubject;
            ViewState["ThanksMessage"] = survey.ThankYouMessage;
            DefaultSurveyCheckBox.Checked = survey.DefaultSurvey;

            EntryNotificationDropdownlist.DataSource = new Surveys().GetSurveyNotificationModes();
            EntryNotificationDropdownlist.DataTextField = "description";
            EntryNotificationDropdownlist.DataValueField = "NotificationModeId";

            EntryNotificationDropdownlist.DataBind();
            ((PageBase)Page).TranslateListControl(EntryNotificationDropdownlist);
            EntryNotificationDropdownlist.SelectedValue = survey.NotificationModeID.ToString();

            if ((NotificationMode)survey.NotificationModeID !=
                NotificationMode.None)
            {
                NotificationPlaceHolder.Visible = true;
            }
            else
            {
                NotificationPlaceHolder.Visible = false;
            }

            ProgressDisplayDropDownList.DataSource = new Surveys().GetSurveyProgressModes();
            ProgressDisplayDropDownList.DataTextField = "description";
            ProgressDisplayDropDownList.DataValueField = "ProgressDisplayModeId";
            ProgressDisplayDropDownList.DataBind();
            ((PageBase)Page).TranslateListControl(ProgressDisplayDropDownList);
            ProgressDisplayDropDownList.SelectedValue = survey.ProgressDisplayModeID.ToString();

            ResumeModeDropdownlist.DataSource = new Surveys().GetSurveyResumeModes();
            ResumeModeDropdownlist.DataTextField = "description";
            ResumeModeDropdownlist.DataValueField = "ResumeModeId";
            ResumeModeDropdownlist.DataBind();
            ((PageBase)Page).TranslateListControl(ResumeModeDropdownlist);
            ResumeModeDropdownlist.SelectedValue = survey.ResumeModeID.ToString();
        }
		private void InitPageOptions()
		{
			PageOptionData pageOptions = new Surveys().GetSurveyPageOptions(SurveyId, PageNumber);
			if (pageOptions.PageOptions.Rows.Count > 0)
			{
				_enableRandomize = pageOptions.PageOptions[0].IsRandomizeQuestionsNull() ? false : pageOptions.PageOptions[0].RandomizeQuestions;
				_enableSubmit = pageOptions.PageOptions[0].IsEnableSubmitButtonNull() ? false : pageOptions.PageOptions[0].EnableSubmitButton;
			}
		}
        private void ImportXMLButton_Click(object sender, System.EventArgs e)
        {
            if (ImportFile.PostedFile != null)
            {
                NSurveyForm importedSurveys = new NSurveyForm();
                try
                {

                    importedSurveys.ReadXml(ImportFile.PostedFile.InputStream);
                    if (importedSurveys.Survey.Rows.Count > 0)
                    {
                        // Prevents SQL injection from custom hand written datasources Sql answer types in the import Xml 
                        if (!GlobalConfig.SqlBasedAnswerTypesAllowed || !(((PageBase)Page).NSurveyUser.Identity.IsAdmin || ((PageBase)Page).CheckRight(NSurveyRights.SqlAnswerTypesEdition, false)))
                        {
                            foreach (NSurveyForm.AnswerTypeRow answerType in importedSurveys.AnswerType)
                            {
                                answerType.DataSource = null;
                            }
                        }

                        new Survey().ImportSurveys(importedSurveys, ((PageBase)Page).NSurveyUser.Identity.UserId, ((PageBase)Page).SelectedFolderId ?? -1);
                        Surveys srv = new Surveys();
                        srv.SetFolderId(((PageBase)Page).SelectedFolderId, importedSurveys.Survey[0].SurveyID);

                        AssignSurveyToUser(importedSurveys.Survey[0].SurveyID);
                        SurveyId = importedSurveys.Survey[0].SurveyID;
                        UINavigator.NavigateToSurveyBuilder(importedSurveys.Survey[0].SurveyID, 4);
                        ((PageBase)Page).ShowNormalMessage(MessageLabel, ((PageBase)Page).GetPageResource("SurveyImported"));
                    }

                    else ((PageBase)Page).ShowErrorMessage(MessageLabel, ((PageBase)Page).GetPageResource("SurveyNotImported"));


                    MessageLabel.Visible = true;
                }
                catch (Exception ex)
                {
                    if (ex.Message == "DUPLICATEFOLDER")
                        ((PageBase)Page).ShowErrorMessage(MessageLabel, ((PageBase)Page).GetPageResource("SurveyImportDuplicate") );
                    else
                        ((PageBase)Page).ShowErrorMessage(MessageLabel, ((PageBase)Page).GetPageResource("Exception") + "  " + ex.Message);
                    MessageLabel.Visible = true;
                }
            }
        }
        /// <summary>
        /// Builds the HTML to show the survey box
        /// </summary>
        protected virtual void BuildSurveyBox(bool enableQuestionDefaults)
        {
            QuestionData data;
            this._questions = new QuestionItemCollection();
            this._questionContainer = Votations.NSurvey.BE.Votations.NSurvey.Constants.Commons.GetCentPercentTable();//JJ;
            this._questionContainer.Rows.Add(this.BuildRow("", null));
            this._questionContainer.Rows[0].EnableViewState = false;
            this._questionContainer.Rows.Add(this.BuildRow("", null));
            this._questionContainer.Rows[1].EnableViewState = false;
            this._questionContainer.Width = Unit.Percentage(100.0);
            // moved to css
            //            this._questionContainer.CellSpacing = 0;
            //            this._questionContainer.CellPadding = 3;



            Votations.NSurvey.SQLServerDAL.SurveyLayout u = new Votations.NSurvey.SQLServerDAL.SurveyLayout();
            var _userSettings = u.SurveyLayoutGet(this.SurveyId, this.LanguageCode);


            if (!(_userSettings == null || _userSettings.SurveyLayout.Count == 0))
            {
                this.Controls.Add(BuildCustomHeaderOrFooter(HttpUtility.HtmlDecode(_userSettings.SurveyLayout[0].SurveyHeaderText)));
            }
            this._questionContainer.ControlStyle.Font.CopyFrom(base.ControlStyle.Font);
            this.Controls.Add(this._questionContainer);
            PageOptionData surveyPageOptions = new Surveys().GetSurveyPageOptions(this.SurveyId, this.CurrentPageIndex);
            if (surveyPageOptions.PageOptions.Rows.Count > 0)
            {
                this._enableSubmitButton = surveyPageOptions.PageOptions[0].EnableSubmitButton;
                this._randomQuestions = surveyPageOptions.PageOptions[0].RandomizeQuestions;
            }
            if (this._randomQuestions)
            {
                data = new Questions().GetRandomPagedQuestions(this.SurveyId, this.CurrentPageIndex, this.GetRandomSeedForQuestion(), this.LanguageCode);
            }
            else
            {
                data = new Questions().GetPagedQuestions(this.SurveyId, this.CurrentPageIndex, this.LanguageCode);
            }
            foreach (QuestionData.QuestionsRow row2 in data.Questions.Rows)
            {
                if (!new Question().SkipQuestion(row2.QuestionId, this.VoterAnswers, this._isScored))
                {
                    TableRow row = new TableRow();
                    TableCell cell = new TableCell();
                    row.Cells.Add(cell);

                    this._questionContainer.Rows.Add(row);
                    this.InsertQuestion(row2, cell, enableQuestionDefaults);
                }
                else
                {
                    this.CleanVoterQuestionAnswers(QuestionItemFactory.Create(row2, null, this.UniqueID, this.GetRandomSeedForQuestion(), (VoterAnswersData.VotersAnswersDataTable)this.VoterAnswers.VotersAnswers.Copy(), enableQuestionDefaults));
                }
            }
            if (this._enableNavigation && this._previousQuestionNumbering)
            {
                this.ReverseQuestionsNumbers();
            }
            if ((this.CurrentPageIndex < this.TotalPageNumber) && !this._enableSubmitButton)
            {
                this._questionContainer.Rows.Add(this.BuildNextPageButtonRow());
            }
            else
            {
                this._questionContainer.Rows.Add(this.BuildSubmitButtonRow());
            }

            if (!(_userSettings == null || _userSettings.SurveyLayout.Count == 0))
            {
                this.Controls.Add(BuildCustomHeaderOrFooter(HttpUtility.HtmlDecode(_userSettings.SurveyLayout[0].SurveyFooterText)));
            }
            this.ViewState["SubmitButtonUID"] = this._submitButton.UniqueID;
        }
		// Bind data to page controls
		public void BindDropDown()
		{
			SurveyData surveys;
			if (((PageBase)Page).NSurveyUser.Identity.IsAdmin ||
				((PageBase)Page).NSurveyUser.Identity.HasAllSurveyAccess)
			{
				surveys = new Surveys().GetAllSurveysList();
			}
			else
			{
				surveys = new Surveys().GetAssignedSurveysList(((PageBase)Page).NSurveyUser.Identity.UserId);
			}
			
			SurveyDropDownList.DataSource = surveys;
			SurveyDropDownList.DataMember = "surveys";
			SurveyDropDownList.DataTextField = "title";
			SurveyDropDownList.DataValueField = "surveyid";
			SurveyDropDownList.DataBind();
			if ( SurveyDropDownList.Items.FindByValue(SurveyId.ToString()) != null)
			{
				SurveyDropDownList.SelectedValue = SurveyId.ToString();
			}
		}
 /// <summary>
 /// Retrieve all survey data from the db
 /// </summary>
 protected virtual void GetSurveyData()
 {
     SurveyData surveyById = new Surveys().GetSurveyById(this.SurveyId, this.LanguageCode);
     this._surveyRow = surveyById.Surveys[0];
     this._surveyTitle = this._surveyRow.Title;
     this._redirectionURL = this._surveyRow.RedirectionURL;
     this._unAuthentifiedUserAction = (UnAuthentifiedUserAction)this._surveyRow.UnAuthentifiedUserActionID;
     this._enableNavigation = this._surveyRow.NavigationEnabled;
     this._progressMode = (ProgressDisplayMode)this._surveyRow.ProgressDisplayModeID;
     this._notificationMode = (NotificationMode)this._surveyRow.NotificationModeID;
     this._resumeMode = (ResumeMode)this._surveyRow.ResumeModeID;
     this._emailFrom = this._surveyRow.EmailFrom;
     this._emailTo = this._surveyRow.EmailTo;
     this._emailSubject = this._surveyRow.EmailSubject;
     this._isScored = this._surveyRow.Scored;
     this._showQuestionNumbers = !this._surveyRow.QuestionNumberingDisabled;
     this._multiLanguageMode = (MultiLanguageMode)this._surveyRow.MultiLanguageModeId;
     this._languageVariable = this._surveyRow.MultiLanguageVariable;
     this.TotalPageNumber = this._surveyRow.TotalPageNumber;
     if ((this._surveyRow.ThankYouMessage != null) && (this._surveyRow.ThankYouMessage.Length != 0))
     {
         this._thankYouMessage = this._surveyRow.ThankYouMessage;
     }
     else
     {
         this._thankYouMessage = ResourceManager.GetString("ThankYouMessage", this.LanguageCode);
     }
 }
 /// <summary>
 /// Must create and return the control 
 /// that will show the logon interface.
 /// If none is available returns null
 /// </summary>
 public Control GetLoginInterface(Style controlStyle)
 {
     SurveyEntryQuotaData quotaSettings = new Surveys().GetQuotaSettings(this.SurveyId);
     if (quotaSettings.SurveyEntryQuotas.Rows.Count > 0)
     {
         return new LiteralControl(GetErrorMessage(quotaSettings.SurveyEntryQuotas[0].MaxReachedMessage));
     }
     return new LiteralControl( GetErrorMessage( ResourceManager.GetString("QuotaReachedMessage", this.LanguageCode)));
 }
 /// <summary>
 /// Check if the current survey
 /// has enough quota left to allow a new entry
 /// </summary>
 public bool IsAuthenticated()
 {
     SurveyEntryQuotaData quotaSettings = new Surveys().GetQuotaSettings(this.SurveyId);
     return ((quotaSettings.SurveyEntryQuotas.Rows.Count > 0) && (quotaSettings.SurveyEntryQuotas[0].EntryCount < quotaSettings.SurveyEntryQuotas[0].MaxEntries));
 }
        public static object TreeViewMoveItem(string ParentFolderId, string ItemId)
        {
            try
            {

                int id = int.Parse(ItemId.Substring(1));
                int? pid = (string.IsNullOrEmpty(ParentFolderId)) ? (int?)null : int.Parse(ParentFolderId.Substring(1));

                // skip move to a list
                if (ParentFolderId.StartsWith("s"))
                    return new { Status = false, Message = "TREECANNOTMOVE" };

                if (ItemId.StartsWith("f"))
                {
                    FolderData fd = new Folders().GetFolderById(id);
                    FolderData.TreeNodesRow tn = (FolderData.TreeNodesRow)fd.TreeNodes.Rows[0];

                    if ((tn.ParentFolderId != null) && pid.HasValue)
                        new Folders().MoveFolder(pid, id);
                    else
                        return new { Status = false, Message = "TREECANNOTMOVE" };
                }
                else if (ItemId.StartsWith("s"))
                {
                    Surveys srv = new Surveys();

                    int sid;
                    if (int.TryParse(ItemId.Substring(1), out sid))
                    {
                        srv.SetFolderId(pid, sid);
                    }
                }
                return new { Status = true, Message = string.Empty };
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                if (ex.Message == "DUPLICATEFOLDER")   return new { Status = false, Message = ex.Message };
                throw;
            }
       
        }
		/// <summary>
		/// Get the current DB data and fill 
		/// the fields with them
		/// </summary>
		private void BindFields()
		{

			// Retrieve the survey data
			SurveyData surveyData = new Surveys().GetSurveyById(SurveyId, LanguagesDropdownlist.SelectedValue);
			SurveyData.SurveysRow survey = surveyData.Surveys[0];

			RedirectionURLTextBox.Text = survey.RedirectionURL;
			//ThankYouFreeTextBox.Text = survey.ThankYouMessage;
            ThankYouCKEditor.Text = survey.ThankYouMessage;

			SurveyMessageConditons.BindData();
		}