[Back]

// DotNetNukeŽ - http://www.dotnetnuke.com
// Copyright (c) 2002-2009
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using System.IO;

namespace AdefWebserver.Modules.SimpleSurvey
{
    public partial class View : PortalModuleBase, IActionable
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                lnkAdminSurveyResults.Visible = (PortalSecurity.IsInRole("Administrators"));
                        
                if (UserId == -1)
                {
                    pnlLoggedIn.Visible = true;
                    pnlQuestion.Visible = false;
                }
                else
                {
                    if (!Page.IsPostBack)
                    {
                        DisplaySurvey();
                        DisplaySurveyValues();
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

        #region DisplaySurvey
        private void DisplaySurvey()
        {
            // Add elements to the DCP panel

            // Create Table
            Table objTable = new Table();
            // Add the Table to DCP panel
            DCP.Controls.Add(objTable);
            objTable.ID = "ResultsTable";

            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            var SurveyQuestions = from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                  where SurveyDataItems.ModuleID == ModuleId
                                  where SurveyDataItems.Visible == true
                                  orderby SurveyDataItems.SortOrder
                                  select SurveyDataItems;

            foreach (var SurveyQuestion in SurveyQuestions)
            {
                TableRow objTableRow = new TableRow();
                TableCell QuestionCell = new TableCell();
                TableCell AnswerCell = new TableCell();
                objTableRow.Cells.Add(QuestionCell);
                objTableRow.Cells.Add(AnswerCell);
                objTable.Rows.Add(objTableRow);

                // Display Question
                string strRequired = (SurveyQuestion.Required == true) ? "<font color='#cc0000'>*</font>" : "";
                string strMoney = (SurveyQuestion.Type == "Money") ? "$" : "";
                Label objLabel = new Label();
                QuestionCell.Controls.Add(objLabel);
                QuestionCell.Style.Add(HtmlTextWriterStyle.TextAlign, "right");
                objLabel.Text = String.Format("{0}{1}:{2}", strRequired, SurveyQuestion.DataName, strMoney);

                // Display Answer Form Element
                AnswerFormElement(AnswerCell, SurveyQuestion.Type, SurveyQuestion.SurveyDataItemID.ToString());

                // Create ID's for controls so they will be persisted in ViewState
                objTableRow.ID = String.Format("{0}", SurveyQuestion.SurveyDataItemID.ToString());
                QuestionCell.ID = String.Format("{0}_QuestionCell", SurveyQuestion.SurveyDataItemID.ToString());
                AnswerCell.ID = String.Format("{0}_AnswerCell", SurveyQuestion.SurveyDataItemID.ToString());
                objLabel.ID = String.Format("{0}_QuestionLabel", SurveyQuestion.SurveyDataItemID.ToString());
            }   
            
            ltValidation.Text = "<br /><i>(Items marked <font color='#cc0000'>*</font> are required)</i><br />";
        }
        #endregion

        #region DisplaySurveyValues
        private void DisplaySurveyValues()
        {
            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            // Get all current Answers
            var CurrentDataAnswers = from SurveyDataAnswers in SimpleSurveyDataContext.SurveyDataAnswers
                                     from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                     where SurveyDataAnswers.SurveyDataItemID == SurveyDataItems.SurveyDataItemID
                                     where SurveyDataItems.ModuleID == ModuleId
                                     where SurveyDataAnswers.UserID == UserId
                                     select SurveyDataAnswers;

            // Add answers to Form
            foreach (var DataAnswer in CurrentDataAnswers)
            {
                ControlCollection colTableCollection = DCP.Controls[0].Controls;
                List<SurveyItem> colSurveyItems = new List<SurveyItem>();

                Control objControl = DCP.FindControl(String.Format("{0}_Answer", DataAnswer.SurveyDataItemID.ToString()));
                string tmpItemType = objControl.GetType().FullName;

                switch (tmpItemType)
                {
                    case "System.Web.UI.WebControls.TextBox":
                        TextBox tempTextBox = ((TextBox)(objControl));
                        tempTextBox.Text = DataAnswer.Value;
                        break;
                    case "System.Web.UI.WebControls.DropDownList":
                        DropDownList tempDropDownList = ((DropDownList)(objControl));
                        try
                        {
                            tempDropDownList.SelectedValue = DataAnswer.Value;
                        }
                        catch
                        {
                            // If the option has been deleted an error will be thrown
                            // supress the error because the option can be re-added
                        }
                        break;
                    case "System.Web.UI.WebControls.RadioButtonList":
                        RadioButtonList tempRadioButtonList = ((RadioButtonList)(objControl));
                        try
                        {
                            tempRadioButtonList.SelectedValue = DataAnswer.Value;
                        }
                        catch
                        {
                            // If the option has been deleted an error will be thrown
                            // supress the error because the option can be re-added
                        }
                        break;
                    case "System.Web.UI.WebControls.CheckBoxList":
                        CheckBoxList tempCheckBoxList = ((CheckBoxList)(objControl));
                        try
                        {
                            tempCheckBoxList.Items.FindByValue(DataAnswer.Value).Selected = true;
                        }
                        catch
                        {
                            // If the option has been deleted an error will be thrown
                            // supress the error because the option can be re-added
                        }
                        break;
                    case "System.Web.UI.WebControls.FileUpload":
                        if (DataAnswer.Value.Trim().Length > 5)
                        {
                            FileUpload tempFileUpload = ((FileUpload)(objControl));
                            HyperLink tempHyperLink = new HyperLink();
                            tempHyperLink.Text = " [Current Image]";
                            tempHyperLink.NavigateUrl = string.Format(@"uploads/{0}", DataAnswer.Value);
                            tempHyperLink.Target = "_new";
                            tempFileUpload.Parent.Controls.Add(tempHyperLink);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion

        #region AnswerFormElement
        private void AnswerFormElement(TableCell QuestionCell, string SurveyQuestionType, string strSurveyDataItemID)
        {
            switch (SurveyQuestionType)
            {
                case "Text":
                    TextBox objLargeTextBox = new TextBox();
                    QuestionCell.Controls.Add(objLargeTextBox);
                    objLargeTextBox.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objLargeTextBox.TextMode = TextBoxMode.MultiLine;
                    objLargeTextBox.Columns = 25;
                    objLargeTextBox.Rows = 2;
                    objLargeTextBox.MaxLength = 200;
                    break;
                case "Dropdown":
                    DropDownList objDropDownList = new DropDownList();
                    QuestionCell.Controls.Add(objDropDownList);
                    objDropDownList.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objDropDownList.Items.AddRange(AddListItems(Convert.ToInt32(strSurveyDataItemID)));
                    break;
                case "Radio Buttons":
                    RadioButtonList objRadioButtonList = new RadioButtonList();
                    QuestionCell.Controls.Add(objRadioButtonList);
                    objRadioButtonList.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objRadioButtonList.Items.AddRange(AddListItems(Convert.ToInt32(strSurveyDataItemID)));
                    break;
                case "Check Boxes":
                    CheckBoxList objCheckBoxList = new CheckBoxList();
                    QuestionCell.Controls.Add(objCheckBoxList);
                    objCheckBoxList.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objCheckBoxList.Items.AddRange(AddListItems(Convert.ToInt32(strSurveyDataItemID)));
                    break;
                case "Integer":
                    TextBox objIntegerTextBox = new TextBox();
                    QuestionCell.Controls.Add(objIntegerTextBox);
                    objIntegerTextBox.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objIntegerTextBox.Columns = 4;
                    break;
                case "Double":
                    TextBox objDoubleTextBox = new TextBox();
                    QuestionCell.Controls.Add(objDoubleTextBox);
                    objDoubleTextBox.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objDoubleTextBox.Columns = 4;
                    break;
                case "Money":
                    TextBox objMoneyTextBox = new TextBox();
                    QuestionCell.Controls.Add(objMoneyTextBox);
                    objMoneyTextBox.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objMoneyTextBox.Columns = 4;
                    break;
                case "Email":
                    TextBox objEmailTextBox = new TextBox();
                    QuestionCell.Controls.Add(objEmailTextBox);
                    objEmailTextBox.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objEmailTextBox.Columns = 35;
                    break;
                case "Date":
                    TextBox objDateTextBox = new TextBox();
                    QuestionCell.Controls.Add(objDateTextBox);
                    objDateTextBox.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objDateTextBox.Columns = 10;
                    break;
                case "Website":
                    TextBox objWebsiteTextBox = new TextBox();
                    QuestionCell.Controls.Add(objWebsiteTextBox);
                    objWebsiteTextBox.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    objWebsiteTextBox.Columns = 35;
                    break;
                case "Image":
                    FileUpload objUploadTextBox = new FileUpload();
                    QuestionCell.Controls.Add(objUploadTextBox);
                    objUploadTextBox.ID = String.Format("{0}_Answer", strSurveyDataItemID);
                    break;
            }
        }
        #endregion

        #region AddListItems
        private ListItem[] AddListItems(int intSurveyDataItemID)
        {
            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            var Survey_Choices = from SurveyChoices in SimpleSurveyDataContext.SurveyChoices
                                 where SurveyChoices.SurveyDataItemID == intSurveyDataItemID
                                 select SurveyChoices;

            List<ListItem> colListItems = new List<ListItem>();

            foreach (var SurveyChoice in Survey_Choices)
            {
                ListItem objListItem = new ListItem();
                objListItem.Text = SurveyChoice.choice;
                objListItem.Value = SurveyChoice.choice;

                colListItems.Add(objListItem);
            }

            return colListItems.ToArray();
        }
        #endregion

        #region btnSubmit_Click
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            List<string> colValidationList = new List<string>();
            ltValidation.Text = "";
            // Get all the values from the form            
            List<SurveyItem> colSurveyFormValues = GetFormValues();
            // Get all the Survey Items from the database
            List<SurveyItem> colSurveyItems = GetSurveyItems();

            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            List<SurveyItem> colCompleteSurveyItems = (from SurveyFormValues in colSurveyFormValues
                                                       from SurveyItems in colSurveyItems
                                                       where SurveyFormValues.SurveyDataItemID == SurveyItems.SurveyDataItemID
                                                       select new SurveyItem
                                                       {
                                                           ItemName = SurveyItems.ItemName,
                                                           ItemTypeName = SurveyFormValues.ItemTypeName,
                                                           // If an Item is a FileUpload - Store the current value
                                                           // THe upload process will update the new value 
                                                           ItemValue =
                                                               (SurveyFormValues.ItemTypeName == "FileUpload") ?
                                                               ((SimpleSurveyDataContext.SurveyDataAnswers.
                                                                  Where(x => x.UserID == UserId & x.SurveyDataItemID == SurveyFormValues.SurveyDataItemID).FirstOrDefault() != null)
                                                                  ? SimpleSurveyDataContext.SurveyDataAnswers.Where(x => x.UserID == UserId 
                                                                  & x.SurveyDataItemID == SurveyFormValues.SurveyDataItemID).FirstOrDefault().Value : "")
                                                               : SurveyFormValues.ItemValue,
                                                           Required = SurveyItems.Required,
                                                           SurveyDataItemID = SurveyFormValues.SurveyDataItemID
                                                       }).ToList();

            // Validate Required Fields
            colValidationList = ValidateRequiredFields(colCompleteSurveyItems);
            if (colValidationList.Count > 0)
            {
                DisplayValidationErrors(colValidationList);
                return;
            }

            // Validate Field Types
            colValidationList = ValidateFieldValues(colCompleteSurveyItems);
            if (colValidationList.Count > 0)
            {
                DisplayValidationErrors(colValidationList);
                return;
            }

            // Upload any images
            bool boolUploadComplete = UploadImages(colCompleteSurveyItems);
            if (!boolUploadComplete)
            {
                colValidationList.Add("There was an error uploading a image file.");
                colValidationList.Add("Only .jpg/.jpeg/.gif allowed.");
                DisplayValidationErrors(colValidationList);
                return;
            }

            // Save data
            SaveSurveyItems(colCompleteSurveyItems);
            DisplaySurveyValues();
        }
        #endregion

        #region SaveSurveyItems
        private void SaveSurveyItems(List<SurveyItem> colCompleteSurveyItems)
        {
            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            // Get all current items
            var CurrentDataAnswers = from SurveyDataAnswers in SimpleSurveyDataContext.SurveyDataAnswers
                                     from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                     where SurveyDataAnswers.SurveyDataItemID == SurveyDataItems.SurveyDataItemID
                                     where SurveyDataItems.ModuleID == ModuleId
                                     where SurveyDataAnswers.UserID == UserId
                                     select SurveyDataAnswers;

            // Delete all current Items
            SimpleSurveyDataContext.SurveyDataAnswers.DeleteAllOnSubmit(CurrentDataAnswers);
            SimpleSurveyDataContext.SubmitChanges();

            // Add all new items
            foreach (var SurveyItem in colCompleteSurveyItems)
            {
                if (SurveyItem.ItemTypeName != "CheckBoxList")
                {
                    SurveyDataAnswer objSurveyDataAnswer = new SurveyDataAnswer();
                    objSurveyDataAnswer.UserID = UserId;
                    objSurveyDataAnswer.SurveyDataItemID = SurveyItem.SurveyDataItemID;
                    objSurveyDataAnswer.Value = SurveyItem.ItemValue;

                    SimpleSurveyDataContext.SurveyDataAnswers.InsertOnSubmit(objSurveyDataAnswer);
                    SimpleSurveyDataContext.SubmitChanges();
                }
                else
                {
                    // For Check boxes, multiple rows are saved
                    char[] delimiterChars = { ',' };
                    string[] SurveyValues = SurveyItem.ItemValue.Split(delimiterChars);

                    foreach (string SurveyValue in SurveyValues)
                    {
                        SurveyDataAnswer objSurveyDataAnswer = new SurveyDataAnswer();
                        objSurveyDataAnswer.UserID = UserId;
                        objSurveyDataAnswer.SurveyDataItemID = SurveyItem.SurveyDataItemID;
                        objSurveyDataAnswer.Value = SurveyValue;

                        SimpleSurveyDataContext.SurveyDataAnswers.InsertOnSubmit(objSurveyDataAnswer);
                        SimpleSurveyDataContext.SubmitChanges();
                    }
                }
            }
        }
        #endregion

        #region UploadImages
        private bool UploadImages(List<SurveyItem> colCompleteSurveyItems)
        {
            bool UploadComplete = true;
            foreach (var objSurveyItem in colCompleteSurveyItems)
            {
                if ((objSurveyItem.ItemTypeName == "FileUpload") & (UploadComplete == true))
                {
                    ControlCollection colTableCollection = DCP.Controls[0].Controls;
                    List<SurveyItem> colSurveyItems = new List<SurveyItem>();

                    Control objControl = DCP.FindControl(String.Format("{0}_Answer", objSurveyItem.SurveyDataItemID.ToString()));
                    string tmpItemType = objControl.GetType().FullName;

                    FileUpload tempFileUpload = ((FileUpload)(objControl));

                    if (tempFileUpload.HasFile)
                    {
                        // Only upload image files
                        if ((
                            Path.GetExtension(tempFileUpload.FileName).ToLower() == ".jpg" ||
                            Path.GetExtension(tempFileUpload.FileName).ToLower() == ".jpeg" ||
                            Path.GetExtension(tempFileUpload.FileName).ToLower() == ".gif"
                            ))
                        {
                            string path = MapPath(@"~\DesktopModules\SimpleSurvey\uploads\");
                            EnsureDirectory(new System.IO.DirectoryInfo(path));

                            // Delete the previous image
                            try
                            {
                                File.Delete(path + objSurveyItem.ItemValue);
                            }
                            catch
                            {
                                // The image may not be there because it was deleted 
                            }

                            // Add the new image
                            objSurveyItem.ItemValue = Convert.ToString(ModuleId) + "_" + UniqueString() + Path.GetExtension(tempFileUpload.FileName).ToLower();
                            path = path + objSurveyItem.ItemValue;
                            tempFileUpload.SaveAs(path);
                        }
                        else
                        {
                            UploadComplete = false;
                            break;
                        }
                    }
                }
            }

            return UploadComplete;
        }
        #endregion

        #region ValidateRequiredFields
        private List<string> ValidateRequiredFields(List<SurveyItem> colCompleteSurveyItems)
        {
            List<string> colValidationList = new List<string>();
            string strValidation = "";
            foreach (var objSurveyItem in colCompleteSurveyItems)
            {
                if ((objSurveyItem.ItemTypeName != "FileUpload"))
                {
                    // Check non-FileUpload 
                    if ((objSurveyItem.Required) & (objSurveyItem.ItemValue.Trim().Length == 0))
                    {
                        strValidation = String.Format("Item {0} is required.", objSurveyItem.ItemName);
                        colValidationList.Add(strValidation);
                    }
                }
                else
                {
                    // Check FileUpload
                    if ((objSurveyItem.Required) & (objSurveyItem.ItemValue == ""))
                    {
                        ControlCollection colTableCollection = DCP.Controls[0].Controls;
                        Control objControl = DCP.FindControl(String.Format("{0}_Answer", objSurveyItem.SurveyDataItemID.ToString()));
                        FileUpload tempFileUpload = ((FileUpload)(objControl));

                        if (!tempFileUpload.HasFile)
                        {
                            strValidation = String.Format("Item {0} is required.", objSurveyItem.ItemName);
                            colValidationList.Add(strValidation);
                        }
                    }
                }
            }
            return colValidationList;
        }
        #endregion

        #region ValidateFieldValues
        private List<string> ValidateFieldValues(List<SurveyItem> colCompleteSurveyItems)
        {
            List<string> colValidationList = new List<string>();
            string strValidation = "";
            foreach (var objSurveyItem in colCompleteSurveyItems)
            {
                switch (objSurveyItem.ItemName)
                {
                    case "Integer":
                        try
                        {
                            if (objSurveyItem.ItemValue.Trim().Length > 0)
                            {
                                Convert.ToInt32(objSurveyItem.ItemValue.Trim());
                            }
                        }
                        catch
                        {
                            strValidation = String.Format("Item {0} must be an integer.", objSurveyItem.ItemName);
                            colValidationList.Add(strValidation);
                        }
                        break;
                    case "Double":
                    case "Money":
                        try
                        {
                            if (objSurveyItem.ItemValue.Trim().Length > 0)
                            {
                                Convert.ToDouble(objSurveyItem.ItemValue.Trim());
                            }
                        }
                        catch
                        {
                            strValidation = String.Format("Item {0} must be a double.", objSurveyItem.ItemName);
                            colValidationList.Add(strValidation);
                        }
                        break;
                    case "Date":
                        try
                        {
                            if (objSurveyItem.ItemValue.Trim().Length > 0)
                            {
                                Convert.ToDateTime(objSurveyItem.ItemValue.Trim());
                            }
                        }
                        catch
                        {
                            strValidation = String.Format("Item {0} must be a Date.", objSurveyItem.ItemName);
                            colValidationList.Add(strValidation);
                        }
                        break;
                    case "Email":
                        if (objSurveyItem.ItemValue.Trim().Length > 0)
                        {
                            if (!
                                (objSurveyItem.ItemValue.Contains("@") &
                                objSurveyItem.ItemValue.Contains("."))
                                )
                            {
                                strValidation = String.Format("Item {0} must be a email address.", objSurveyItem.ItemName);
                                colValidationList.Add(strValidation);
                            }
                        }
                        break;
                    case "Website":
                        if (objSurveyItem.ItemValue.Trim().Length > 0)
                        {
                            if (!
                                (objSurveyItem.ItemValue.Contains("http") &
                                objSurveyItem.ItemValue.Contains("."))
                                )
                            {
                                strValidation = String.Format(@"Item {0} must be a website address (include http://).", objSurveyItem.ItemName);
                                colValidationList.Add(strValidation);
                            }
                        }
                        break;
                }
            }

            return colValidationList;
        }
        #endregion

        #region GetSurveyItems
        private List<SurveyItem> GetSurveyItems()
        {
            List<SurveyItem> colSurveyItems = new List<SurveyItem>();
            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            var SurveyQuestions = from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                                  where SurveyDataItems.ModuleID == ModuleId
                                  where SurveyDataItems.Visible == true
                                  orderby SurveyDataItems.SortOrder
                                  select SurveyDataItems;

            foreach (var SurveyQuestion in SurveyQuestions)
            {
                SurveyItem objSurveyItem = new SurveyItem();
                objSurveyItem.ItemName = SurveyQuestion.DataName;
                objSurveyItem.ItemTypeName = SurveyQuestion.Type;
                objSurveyItem.Required = (SurveyQuestion.Required.HasValue) ? Convert.ToBoolean(SurveyQuestion.Required) : false;
                objSurveyItem.SurveyDataItemID = SurveyQuestion.SurveyDataItemID;

                colSurveyItems.Add(objSurveyItem);
            }

            return colSurveyItems;
        }
        #endregion

        #region GetFormValues
        private List<SurveyItem> GetFormValues()
        {
            ControlCollection colTableCollection = DCP.Controls[0].Controls;
            List<SurveyItem> colSurveyItems = new List<SurveyItem>();

            foreach (TableRow TableRowItem in colTableCollection)
            {
                SurveyItem objSurveyItem = new SurveyItem();
                TableCell objTableCell = (TableCell)TableRowItem.Controls[1];
                Control Item = (Control)objTableCell.Controls[0];
                string tmpItemType = Item.GetType().FullName;

                switch (tmpItemType)
                {
                    case "System.Web.UI.WebControls.TextBox":
                        TextBox tempTextBox = ((TextBox)(Item));
                        objSurveyItem.ItemTypeName = "TextBox";
                        objSurveyItem.SurveyDataItemID = GetItemID(tempTextBox.ID);
                        objSurveyItem.ItemName = tempTextBox.ID;
                        objSurveyItem.ItemValue = tempTextBox.Text;
                        break;
                    case "System.Web.UI.WebControls.DropDownList":
                        DropDownList tempDropDownList = ((DropDownList)(Item));
                        objSurveyItem.ItemTypeName = "DropDownList";
                        objSurveyItem.SurveyDataItemID = GetItemID(tempDropDownList.ID);
                        objSurveyItem.ItemName = tempDropDownList.ID;
                        objSurveyItem.ItemValue = tempDropDownList.SelectedValue;
                        break;
                    case "System.Web.UI.WebControls.CheckBoxList":
                        CheckBoxList tempCheckBoxList = ((CheckBoxList)(Item));
                        objSurveyItem.ItemTypeName = "CheckBoxList";
                        objSurveyItem.SurveyDataItemID = GetItemID(tempCheckBoxList.ID);
                        objSurveyItem.ItemName = tempCheckBoxList.ID;
                        string strSelectedItem = "";
                        ListItemCollection objListItemCollection = tempCheckBoxList.Items;
                        foreach (ListItem objListItem in objListItemCollection)
                        {
                            if (objListItem.Selected)
                            {
                                strSelectedItem = (strSelectedItem
                                    + (objListItem.Value.Replace(",", "") + ","));
                            }
                        }
                        if ((strSelectedItem != ""))
                        {
                            strSelectedItem = strSelectedItem.Substring(0, (strSelectedItem.Length - 1));
                        }
                        objSurveyItem.ItemValue = strSelectedItem;
                        break;
                    case "System.Web.UI.WebControls.RadioButtonList":
                        RadioButtonList tempRadioButtonList = ((RadioButtonList)(Item));
                        objSurveyItem.ItemTypeName = "RadioButtonList";
                        objSurveyItem.SurveyDataItemID = GetItemID(tempRadioButtonList.ID);
                        objSurveyItem.ItemName = tempRadioButtonList.ID;
                        objSurveyItem.ItemValue = tempRadioButtonList.SelectedValue;
                        break;
                    case "System.Web.UI.WebControls.FileUpload":
                        FileUpload tempFileUpload = ((FileUpload)(Item));
                        objSurveyItem.ItemTypeName = "FileUpload";
                        objSurveyItem.SurveyDataItemID = GetItemID(tempFileUpload.ID);
                        objSurveyItem.ItemName = tempFileUpload.ID;
                        objSurveyItem.ItemValue = tempFileUpload.FileName;
                        break;
                    default:
                        objSurveyItem.SurveyDataItemID = -1;
                        break;
                }
                // Add the SurveyItem to the Collection
                colSurveyItems.Add(objSurveyItem);
            }
            return colSurveyItems;
        }
        #endregion

        #region GetItemID
        private int GetItemID(string strID)
        {
            int intSurveyDataItemID = 0;
            int intUnderscorePosition = strID.IndexOf("_");
            intSurveyDataItemID = Convert.ToInt32(strID.Substring(0, intUnderscorePosition));
            return intSurveyDataItemID;
        }
        #endregion

        #region DisplayValidationErrors
        private void DisplayValidationErrors(List<string> colValidationList)
        {
            string strValidation = "<font color='#cc0000'>";
            foreach (string objValiationItem in colValidationList)
            {
                strValidation = strValidation + String.Format("* {0}<br />", objValiationItem);
            }
            strValidation = strValidation + "</font>";
            ltValidation.Text = strValidation;
        }
        #endregion

        #region UniqueString
        public string UniqueString()
        {
            //  Create a unique file name  
            DateTime myDate = DateTime.Now;
            string myTimeString = myDate.ToLongTimeString().Replace(":", "u");
            myTimeString = myTimeString.Replace(" AM", "11");
            myTimeString = myTimeString.Replace(" PM", "99");
            myTimeString = (myTimeString + Session.SessionID);
            return myTimeString;
        }
        #endregion

        #region EnsureDirectory
        public static void EnsureDirectory(System.IO.DirectoryInfo oDirInfo)
        {
            if (oDirInfo.Parent != null)
                EnsureDirectory(oDirInfo.Parent);
            if (!oDirInfo.Exists)
            {
                oDirInfo.Create();
            }
        }
        #endregion

        #region IActionable Members
        public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(GetNextActionID(), "Edit Survey", ModuleActionType.AddContent, "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }
        #endregion

        #region lnkResults_Click
        protected void lnkResults_Click(object sender, EventArgs e)
        {
            lnkBack.Visible = true;
            lnkResults.Visible = false;
            pnlResults.Visible = true;
            pnlLoggedIn.Visible = false;
            pnlQuestion.Visible = false;

            DisplaySurveyResults();
        }
        #endregion

        #region lnkBack_Click
        protected void lnkBack_Click(object sender, EventArgs e)
        {
            pnlResults.Visible = false;
            lnkBack.Visible = false;
            lnkResults.Visible = true;

            if (UserId == -1)
            {
                pnlLoggedIn.Visible = true;
                pnlQuestion.Visible = false;
            }
            else
            {
                pnlLoggedIn.Visible = false;
                pnlQuestion.Visible = true;
            }
        }
        #endregion

        #region DisplaySurveyResults
        private void DisplaySurveyResults()
        {
            SimpleSurveyDataContext SimpleSurveyDataContext = new SimpleSurveyDataContext();

            var results = from SurveyDataItems in SimpleSurveyDataContext.SurveyDataItems
                          from SurveyDataAnswers in SimpleSurveyDataContext.SurveyDataAnswers
                          where SurveyDataItems.SurveyDataItemID == SurveyDataAnswers.SurveyDataItemID
                          where SurveyDataItems.ModuleID == ModuleId
                          where SurveyDataItems.Visible == true
                          where (SurveyDataItems.Type == "Dropdown" || SurveyDataItems.Type == "Radio Buttons" || SurveyDataItems.Type == "Check Boxes")
                          group SurveyDataItems by SurveyDataItems.SurveyDataItemID into Questions
                          select new
                          {
                              Question = SimpleSurveyDataContext.SurveyDataItems.Where(x => x.SurveyDataItemID == Convert.ToInt32(Questions.Key)).FirstOrDefault().DataName,
                              Options = from SurveyDataAnswers in SimpleSurveyDataContext.SurveyDataAnswers
                                        where SurveyDataAnswers.SurveyDataItemID == Questions.Key
                                        where SurveyDataAnswers.Value != ""
                                        group SurveyDataAnswers by SurveyDataAnswers.Value into SurveyOptions
                                        select new
                                        {
                                            Option = SurveyOptions.Key,
                                            Count = SurveyOptions.Count().ToString()
                                        },
                              Count = Questions.Count().ToString()
                          };

            lvResults.DataSource = results;
            lvResults.DataBind();
        } 
        #endregion

        #region lnkAdminSurveyResults_Click
        protected void lnkAdminSurveyResults_Click(object sender, EventArgs e)
        {
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(PortalSettings.ActiveTab.TabID, "AdminResults", "mid=" + ModuleId.ToString()));
        } 
        #endregion
}
}