Пример #1
0
        public Survey Update(Survey survey)
        {
            this.surveys.Update(survey);
            this.surveys.SaveChanges();

            return survey;
        }
		private bool SaveSurvey(Survey survey, int applicantID) {
            string param = "EXEC spSaveSurvey '" + applicantID + "', ";
			param = param + "'" + survey.QuestionID + "', '" + survey.RateID + "','" + survey.Comment + "'";
            conn = new DBConn.DBConn();
            conn.execSQLCommand(param);
            return true;
		}
Пример #3
0
    public static Survey createSurvey(ImportingElement element, int id, string flag)
    {
        GRASPEntities db = new GRASPEntities();

        Survey survey = new Survey();

        survey.name = element.refListName;
        survey.owner_id = id;

        db.Survey.Add(survey);
        db.SaveChanges();

        if (flag == "select1")
        {
            foreach (string label in element.select1Labels)
            {
                int size = FormFieldExport.getSurveyList(survey.id);
                SurveyElement se = createSurveyElement(label, size);
                createSurveyAssociation(survey.id, se.id);
            }
        }
        if (flag == "survey")
        {
            foreach (string label in element.surveyValues)
            {
                int size = FormFieldExport.getSurveyList(survey.id);
                SurveyElement se = createSurveyElement(label, size);
                createSurveyAssociation(survey.id, se.id);
            }
        }

        return survey;
    }
Пример #4
0
        public List<Survey> GetSurveys()
        {
            List<Survey> lstSurveys = new List<Survey>();
            DbCommand oDbCommand = DbProviderHelper.CreateCommand("SELECTSurveys",CommandType.StoredProcedure);
            DbDataReader oDbDataReader = DbProviderHelper.ExecuteReader(oDbCommand);
            while (oDbDataReader.Read())
            {
                Survey oSurvey = new Survey();
                oSurvey.SurveyId = Convert.ToInt32(oDbDataReader["SurveyId"]);

                if(oDbDataReader["SurveyGuid"] != DBNull.Value)
                    oSurvey.SurveyGuid = (Guid) oDbDataReader["SurveyGuid"];
                oSurvey.SubmissionGuid = (Guid) oDbDataReader["SubmissionGuid"];

                if(oDbDataReader["Voter"] != DBNull.Value)
                    oSurvey.Voter = Convert.ToString(oDbDataReader["Voter"]);
                oSurvey.Vote = Convert.ToInt32(oDbDataReader["Vote"]);
                oSurvey.IPAddress = Convert.ToString(oDbDataReader["IPAddress"]);

                if(oDbDataReader["DateCreated"] != DBNull.Value)
                    oSurvey.DateCreated = Convert.ToDateTime(oDbDataReader["DateCreated"]);
                lstSurveys.Add(oSurvey);
            }
            oDbDataReader.Close();
            return lstSurveys;
        }
 public void EditSurvey(Survey surveyToEdit, Survey editingSurvey)
 {
     var rowIndexOfItemToEdit = this.SurveysPage.Map.KendoGrid.IndexOfGridRowContainingText(surveyToEdit.Name);
     this.SurveysPage.Map.AllEditEntryButtons[rowIndexOfItemToEdit].MouseClick();
     ExecutionDelayProvider.SleepFor(2000);
     Manager.Current.ActiveBrowser.RefreshDomTree();
     ExecutionDelayProvider.SleepFor(2000);
     this.SurveysPage.Map.Name.MouseClick(MouseClickType.LeftDoubleClick);
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.KeyPress(Keys.Back);
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.TypeText(editingSurvey.Name);
     this.SurveysPage.Map.ActiveFromLabel.MouseClick();
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.KeyPress(Keys.Back);
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.TypeText(editingSurvey.ActiveFrom);
     this.SurveysPage.Map.Name.MouseClick();
     ExecutionDelayProvider.SleepFor(2000);
     this.SurveysPage.Map.ActiveToLabel.MouseClick(MouseClickType.LeftDoubleClick);
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.KeyPress(Keys.Back);
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.TypeText(editingSurvey.ActiveTo);
     this.SurveysPage.Map.Name.MouseClick();
     ExecutionDelayProvider.SleepFor(2000);
     Manager.Current.ActiveBrowser.RefreshDomTree();
     this.SurveysPage.Map.UpdateItemButton.MouseClick();
     Manager.Current.ActiveBrowser.RefreshDomTree();
     ExecutionDelayProvider.SleepFor(2000);
 }
Пример #6
0
    protected void btnSubmitSurvey_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //if incident selected not "--select incident--"
            if (lbIncident.SelectedIndex > 0)
            {
                Survey survey = new Survey();

                Label1.Text = lbIncident.SelectedValue;
                survey.IncidentID = Int32.Parse(lbIncident.SelectedValue);
                survey.CustomerID = Int32.Parse(tbEnterCustID.Text);
                survey.ResponseTime = Convert.ToInt32(rbResponse.SelectedValue);

                survey.Resolution = Convert.ToInt32(rbResolution.SelectedValue);
                survey.TechEfficiency = Convert.ToInt32(rbTechEfficiency.SelectedValue);
                survey.Contact = cbContact.Checked;
                if (cbContact.Checked)
                {
                        survey.ContactBy = rbContactBy.Text;
                }
                survey.Comments = tbComments.Text;

                Session["Survey"] = survey;
                Response.Redirect("~/SurveyComplete.aspx");
            }
            //else
            //{
            //    RequiredValFieldIncidentList.
            //}
            Response.Redirect("~/SurveyComplete.aspx");
        }
    }
Пример #7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Sage.Platform.WebPortal.WebPortalPage page = Parent.Page as Sage.Platform.WebPortal.WebPortalPage;
        if (page == null)
            return;

        currentSurvey = page.PageWorkItem.Modules
            .Get<Sage.SalesLogix.Web.Modules.WorkSurveyModule>().CurrentWorkSurveyConfig;
        if (currentSurvey == null)
            return;

        SetPageValues();

        if (!Page.IsPostBack)
        {
            FillDelayOptions();

            // hide the no thanks button if the survey is required
            if (currentSurvey.IsRequired)
                rbNo.Visible = false;

            // if the title image doesn't exist, hide it so alternate text doesn't show up
            if (!File.Exists(Server.MapPath(currentSurvey.SurveyOfferPage.OfferPageImagePath)))
                imgTitle.Visible = false;

            ddlDelayDays.Attributes.Add("onchange",
                                        "document.getElementById('" + rbLater.ClientID + "').checked='checked';");
        }

        CreateSurveyScript();
    }
Пример #8
0
    public Survey getCurrentSurvey()
    {
        SqlConnection conn = new SqlConnection(ConnectionString);
        string sql = "SELECT * FROM user_survey_polls WHERE active = 1";
        SqlCommand cmd = new SqlCommand(sql, conn);
        Survey survey = null;
        try
        {
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
                survey = new Survey((int)reader["id"], (int)reader["survey_num"], (string)reader["description"], (int)reader["active"]);
            reader.Close();
            return survey;
        }
        catch
        {
            throw new Exception();
        }
        finally
        {
            conn.Close();

        }
    }
Пример #9
0
 public Vote(User user, Survey survey, Answer answer)
     : this()
 {
     this.User = user;
     this.Survey = survey;
     this.Answer = answer;
 }
Пример #10
0
 public static TestReferralSurvey BuildAdditionalFromDataBaseData(string idReferral)
 {
     using (NpgsqlConnection connection = Global.GetSqlConnection())
     {
         string findPatient = "SELECT id_survey_organ, survey_comment, id_survey_type FROM public.referral WHERE id_referral = '" + idReferral + "' ORDER BY id_referral DESC LIMIT 1";
         NpgsqlCommand person = new NpgsqlCommand(findPatient, connection);
         using (NpgsqlDataReader personFromDataBase = person.ExecuteReader())
         {
             Survey p = new Survey();
             while (personFromDataBase.Read())
             {
                 //что делать с DateSpecified и Мисами?
                 if (personFromDataBase["survey_comment"] != DBNull.Value)
                     p.Comment = Convert.ToString(personFromDataBase["survey_comment"]);
                 TestReferralSurvey pers = new TestReferralSurvey(p);
                 pers.additional = TestAdditional.BuildAdditionalFromDataBaseData(idReferral);
                 if (personFromDataBase["id_survey_organ"] != DBNull.Value)
                     pers.surveyOrgan = TestCoding.BuildCodingFromDataBaseData(Convert.ToString(personFromDataBase["id_survey_organ"]));
                 if (personFromDataBase["id_survey_type"] != DBNull.Value)
                     pers.surveyType = TestCoding.BuildCodingFromDataBaseData(Convert.ToString(personFromDataBase["id_survey_type"]));
                 return pers;
             }
         }
     }
     return null;
 }
Пример #11
0
        public Survey GetSurvey(int SurveyId)
        {
            Survey oSurvey = new Survey();
            DbCommand oDbCommand = DbProviderHelper.CreateCommand("SELECTSurvey",CommandType.StoredProcedure);
            oDbCommand.Parameters.Add(DbProviderHelper.CreateParameter("@SurveyId",DbType.Int32,SurveyId));
            DbDataReader oDbDataReader = DbProviderHelper.ExecuteReader(oDbCommand);
            while (oDbDataReader.Read())
            {
                oSurvey.SurveyId = Convert.ToInt32(oDbDataReader["SurveyId"]);

                if(oDbDataReader["SurveyGuid"] != DBNull.Value)
                    oSurvey.SurveyGuid = (Guid) oDbDataReader["SurveyGuid"];
                oSurvey.SubmissionGuid = (Guid) oDbDataReader["SubmissionGuid"];

                if(oDbDataReader["Voter"] != DBNull.Value)
                    oSurvey.Voter = Convert.ToString(oDbDataReader["Voter"]);
                oSurvey.Vote = Convert.ToInt32(oDbDataReader["Vote"]);
                oSurvey.IPAddress = Convert.ToString(oDbDataReader["IPAddress"]);

                if(oDbDataReader["DateCreated"] != DBNull.Value)
                    oSurvey.DateCreated = Convert.ToDateTime(oDbDataReader["DateCreated"]);
            }
            oDbDataReader.Close();
            return oSurvey;
        }
        public void RunGetsSurveyAnswersForIdFromStore()
        {
            var mockSurveyStore = new Mock<ISurveyStore>();
            var mockSurveyAnswerStore = new Mock<ISurveyAnswerStore>();
            var mockTenantStore = new Mock<ITenantStore>();
            var mockSurveySqlStore = new Mock<ISurveySqlStore>();
            var command = new TransferSurveysToSqlAzureCommand(mockSurveyAnswerStore.Object, mockSurveyStore.Object, mockTenantStore.Object, mockSurveySqlStore.Object);
            var message = new SurveyTransferMessage { Tenant = "tenant", SlugName = "slugName" };
            var survey = new Survey("slugName")
                             {
                                 Tenant = "tenant",
                             };
            survey.Questions.Add(new Question
                                     {
                                         Text = "What is your favorite food?",
                                         PossibleAnswers = "Coffee\nPizza\nSalad",
                                         Type = QuestionType.MultipleChoice
                                     });
            mockSurveyStore.Setup(r => r.GetSurveyByTenantAndSlugName("tenant", "slugName", true)).Returns(survey);
            mockSurveyStore.Setup(r => r.GetSurveysByTenant("tenant")).Returns(new List<Survey> { survey });
            mockSurveyAnswerStore.Setup(r => r.GetSurveyAnswerIds("tenant", "slugName")).Returns(new List<string> { "id" });
            mockSurveyAnswerStore.Setup(r => r.GetSurveyAnswer("tenant", "slugName", "id")).Returns(new SurveyAnswer());
            var tenant = new Tenant { SqlAzureConnectionString = "connectionString" };
            mockTenantStore.Setup(r => r.GetTenant("tenant")).Returns(tenant);

            command.Run(message);

            mockSurveyAnswerStore.Verify(r => r.GetSurveyAnswer(message.Tenant, "slugName", "id"));
        }
 public void DeleteSurvey(Survey survey)
 {
     var rowIndexOfItemToDelete = this.SurveysPage.Map.KendoGrid.IndexOfGridRowContainingText(survey.Name);
     this.SurveysPage.Map.AllDeleteEntryButtons[rowIndexOfItemToDelete].MouseClick();
     ExecutionDelayProvider.SleepFor(2000);
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.KeyPress(Keys.Enter);
     ExecutionDelayProvider.SleepFor(2000);
 }
 public override void Delete(Survey entity)
 {
     using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
     {
         base.Delete(entity);
         scope.Complete();
     }
 }
Пример #15
0
 public SurveyPage(Survey survey)
 {
     //BackgroundColor = Color.FromHex ("#2A2A2A");
     InitializeComponent ();
     Title = "Survey";
     if (Device.OS == TargetPlatform.Android)
         NavigationPage.SetTitleIcon(this, "opac.png");
     BindingContext = new ViewModels.SurveyViewModel (survey, BackgroundColor);
     AnswerList.ItemSelected += AnswerList_ItemSelected;
 }
Пример #16
0
 public TestReferralSurvey(Survey r)
 {
     if (r != null)
         survey = r;
     else
         survey = new Survey();
     additional = new TestAdditional(survey.Additional);
     if (survey.SurveyOrgan != null)
         surveyOrgan = new TestCoding(survey.SurveyOrgan);
     if (survey.SurveyType != null)
         surveyType = new TestCoding(survey.SurveyType);
 }
Пример #17
0
        public void DeleteSurvey(Survey survey)
        {
            this.Votes.RemoveRange(this.Votes.Where(v => v.Survey.Id == survey.Id));
            foreach (Answer a in survey.Answers)
                this.Answers.Attach(a);

            this.Answers.RemoveRange(survey.Answers);
            this.SaveChanges();
            Survey surveyDb = this.Surveys.Where(s => s.Id == survey.Id).First<Survey>();
            this.Surveys.Attach(surveyDb);
            this.Surveys.Remove(surveyDb);
            this.SaveChanges();
        }
        public void AddQuestionCopiesCachedSurveyToTempDataWhenModelIsNotValid()
        {
            using (var controller = new SurveysController(null, null, null, null, null, null))
            {
                controller.ModelState.AddModelError("error for test", "invalid model state");
                var cachedSurvey = new Survey();
                controller.TempData[SurveysController.CachedSurvey] = cachedSurvey;

                var result = controller.AddQuestion(null) as ViewResult;

                var cachedSurveyReturnedInTempData = result.TempData[SurveysController.CachedSurvey] as Survey;

                Assert.AreSame(cachedSurvey, cachedSurveyReturnedInTempData);
            }
        }
        public void AddQuestionAddsTheNewQuestionToTheCachedSurveyWhenModelIsValid()
        {
            var cachedSurvey = new Survey();
            cachedSurvey.Questions.Add(new Question());
            var question = new Question();

            using (var controller = new SurveysController(null, null, null, null, null, null))
            {
                controller.TempData[SurveysController.CachedSurvey] = cachedSurvey;
                controller.AddQuestion(question);

                var actualQuestions = (controller.TempData[SurveysController.CachedSurvey] as Survey).Questions;

                Assert.AreEqual(2, actualQuestions.Count);
                Assert.IsTrue(actualQuestions.Contains(question));
            }
        }
 public void AddSurvey(Survey survey)
 {
     this.SurveysPage.Map.AddItemButton.MouseClick();
     ExecutionDelayProvider.SleepFor(2000);
     Manager.Current.ActiveBrowser.RefreshDomTree();
     ExecutionDelayProvider.SleepFor(2000);
     this.SurveysPage.Map.Name.MouseClick();
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.TypeText(survey.Name);
     this.SurveysPage.Map.ActiveFrom.MouseClick();
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.TypeText(survey.ActiveFrom);
     this.SurveysPage.Map.Name.MouseClick();
     this.SurveysPage.Map.ActiveTo.MouseClick();
     Manager.Current.ActiveBrowser.Desktop.KeyBoard.TypeText(survey.ActiveTo);
     this.SurveysPage.Map.Name.MouseClick();
     ExecutionDelayProvider.SleepFor(2000);
     Manager.Current.ActiveBrowser.RefreshDomTree();
     this.SurveysPage.Map.UpdateItemButton.MouseClick();
 }
Пример #21
0
 public string DeleteSurvey(Survey survey)
 {
     try
     {
         if (survey == null)
         {
             throw new ArgumentNullException();
         }
         using (var db = new SurveyContext())
         {
             db.DeleteSurvey(survey);
         }
         return "0";
     }
     catch (Exception e)
     {
         return e.Message;
     }
 }
        public async Task<IHttpActionResult> PutSurvey(int id, Survey survey)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != survey.SurveyId)
            {
                return BadRequest();
            }

            var dbVersion = db.Surveys
                      .Include(x => x.Questions)
                      .Single(c => c.SurveyId == survey.SurveyId);

            //update individual properties; had trouble getting the associaed questions updating properly without doing it this way.
            dbVersion.Name = survey.Name;
            dbVersion.Description = survey.Description;
            dbVersion.CompletionMessage = survey.CompletionMessage;
            dbVersion.IsClosed = survey.IsClosed;
            dbVersion.Questions = survey.Questions;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SurveyExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
Пример #23
0
        public ActionResult Create(Survey survey)
        {
            //Not sure if this is really needed
            //ModelState.Clear();
            //survey.TransferValidationMessagesTo(ModelState);

            if (ModelState.IsValid)
            {
                _surveyRepository.EnsurePersistent(survey);

                Message = "Survey Created Successfully";

                return this.RedirectToAction(a => a.Edit(survey.Id));
            }
            else
            {
                var viewModel = SurveyViewModel.Create(Repository);
                viewModel.Survey = survey;

                return View(viewModel);
            }
        }
        public ActionResult SurveyQuestions(int id)
        {
            Survey survey = db.Surveys.Find(id);
          
            Survey template = new Survey();

            template.Id = id;
            template.Title = survey.Title;
            List<QuestionResponse> qResponses = db.QuestionResponses.Where(x => x.SurveyId == survey.Id).ToList();
          
            List<QuestionResponse> surveyQuestions = new List<QuestionResponse>();

            foreach (var item in qResponses)
            {
                surveyQuestions.Add(item);
            }

            surveyQuestions.OrderBy(x => x.Id).ToList();

            template.Responses = surveyQuestions.OrderByDescending(x => x.Id).ToList();

            return Json(template, JsonRequestBehavior.AllowGet);
        }
        public void DisplayCopiesTheSurveyQuestionTypeToTheQuestionAnswerReturnedInTheContentModel()
        {
            var survey = new Survey
            {
                Questions = new List<Question>(
                    new[]
                                     {
                                        new Question { Type = QuestionType.SimpleText },
                                     })
            };

            var mockSurveyStore = new Mock<ISurveyStore>();
            mockSurveyStore.Setup(r => r.GetSurveyByTenantAndSlugName(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
                                              .Returns(survey);

            using (var controller = new SurveysController(mockSurveyStore.Object, default(ISurveyAnswerStore)))
            {
                var result = controller.Display("tenant", string.Empty) as ViewResult;

                var model = result.ViewData.Model as TenantPageViewData<SurveyAnswer>;
                Assert.AreEqual(QuestionType.SimpleText, model.ContentModel.QuestionAnswers.First().QuestionType);
            }
        }
        public void NewWhenHttpVerbIsPostSavesCachedSurveyInTempDataWhenModelStateIsNotValid()
        {
            var cachedSurvey = new Survey();

            using (var controller = new SurveysController(new Mock<ISurveyStore>().Object, null, null, null, null, null))
            {
                controller.ModelState.AddModelError("error for test", "invalid model state");
                controller.TempData[SurveysController.CachedSurvey] = cachedSurvey;

                var result = controller.New(new Survey()) as ViewResult;

                var model = result.ViewData.Model as TenantPageViewData<Survey>;
                Assert.AreSame(cachedSurvey, controller.TempData[SurveysController.CachedSurvey]);
            }
        }
Пример #27
0
 /// <summary>
 /// Create a new <see cref="SampleDataElementNode"/>
 /// </summary>
 /// <param name="surveyTree">The owning <see cref="SurveyTree{SurveyContextType}"/> container</param>
 /// <param name="survey">The <see cref="Survey"/> this node is associated with</param>
 /// <param name="contextElement">The parent element, or null for a root expansion context</param>
 /// <param name="element">The element to create a node for</param>
 /// <returns>A fully initialized <see cref="SampleDataElementNode"/>.</returns>
 public static SampleDataElementNode Create(SurveyTree <SurveyContextType> surveyTree, Survey survey, object contextElement, object element)
 {
     return(new SampleDataElementNode(surveyTree, contextElement, element, InitializeNodeData(element, contextElement, survey), null, null, true));
 }
Пример #28
0
        public static Survey CreateSurveyFromForm(SurveyForm thisForm)
        {
            Survey survey = new Survey();

            survey.SurveyAnswers = new List <SurveyAnswer>();

            survey.SeqLNr = GetNewSeqLNr();
            survey.Dat    = DateTime.Now.Date;
            survey.Typ    = thisForm.Typ;
            int subnr = 0;

            switch (survey.Typ.ToLower())
            {
            case "hla":
                survey.TypDsc = "Hälsovårdskort";
                break;

            case "oha":
                survey.TypDsc = "Munvårdskort";
                break;
            }

            foreach (var q in thisForm.Questions)
            {
                subnr++;
                SurveyAnswer newAnswer = new SurveyAnswer();
                newAnswer.SeqLNr = survey.SeqLNr;
                newAnswer.SubNr  = subnr;

                newAnswer.Dsc     = q.Dsc;
                newAnswer.KeyWrd  = q.KeyWrd;
                newAnswer.Man     = q.Man;
                newAnswer.Multi   = q.Multi;
                newAnswer.OhaTyp  = q.OhaTyp;
                newAnswer.SelList = q.SelList;
                newAnswer.Sort    = q.Sort;
                newAnswer.SysVar  = q.SysVar;
                newAnswer.Txt     = q.Txt;

                switch (q.OhaTyp.ToLower())
                {
                case "sel":
                    newAnswer.PrmDec = q.Multi;
                    newAnswer.PrmChr = q.Dsc;
                    string[] parts = q.SelList.Split('¤');
                    if (parts.Length > 0)
                    {
                        for (int i = 0; i < parts.Length; i++)
                        {
                            newAnswer.PrmChr += "¤" + parts[i] + "|0";
                        }
                    }
                    break;

                case "int":
                    newAnswer.PrmChr = q.Dsc + "¤0";
                    break;

                case "chr":
                    newAnswer.PrmChr = q.Dsc + "¤";
                    break;

                case "top":
                    newAnswer.PrmChr = q.Dsc;
                    break;
                }

                survey.SurveyAnswers.Add(newAnswer);
            }

            return(survey);
        }
Пример #29
0
 public PhaseControlViewModel(Survey survey)
 {
     this.survey = survey;
 }
Пример #30
0
 public SurveyCellViewModel(Survey survey, Color backgroundColor)
 {
     this.survey = survey;
     RaisePropertyChanged("Survey");
     BackgroundColor = backgroundColor;
 }
Пример #31
0
        public async Task <IActionResult> CreateUpdateGrantForm(GrantFormVM data)
        {
            var a      = data;
            var userId = User.GetIdentity();

            if (!string.IsNullOrEmpty(userId))
            {
                var user = await _context.ApplicationUser.Where(x => x.Id.Equals(userId)).FirstOrDefaultAsync();

                //.Where(x => x.Id.Equals(userId)).FirstOrDefault();
                if (user != null && user.CorporateId.HasValue)
                {
                    var company = await _context.Corporates.Where(x => x.Id.Equals(user.CorporateId.Value)).FirstOrDefaultAsync();

                    if (company != null)
                    {
                        if (data.SurveyId == 0)
                        {
                            var survQuestions = new List <SurveyQuestion>();
                            foreach (var quest in data.Questions)
                            {
                                var survQuestOpts = new List <SurveyQuestionOption>();
                                if (quest.Type.ToLower() != "open")
                                {
                                    foreach (var opt in quest.Options)
                                    {
                                        survQuestOpts.Add(new SurveyQuestionOption()
                                        {
                                            Text = opt
                                        });
                                    }
                                }

                                survQuestions.Add(new SurveyQuestion()
                                {
                                    Type = quest.Type,
                                    Text = quest.Text,
                                    SurveyQuestionOptions = survQuestOpts
                                });
                            }

                            Survey newSurv = new Survey()
                            {
                                Title           = data.Title,
                                CorporateId     = company.Id,
                                CreatedOn       = DateTime.Now,
                                CreatedBy       = user.UserName,
                                Month           = DateTime.Now.Month,
                                Year            = DateTime.Now.Year,
                                SurveyQuestions = survQuestions
                            };

                            await _context.AddAsync(newSurv);

                            await _context.SaveChangesAsync();

                            return(RedirectToAction("ViewGrantForm", "Home", new { area = "Corporate", sid = newSurv.Id }));
                        }
                        else
                        {
                            var surveyQuesions = await _context.SurveyQuestions.Where(x => x.SurveyId.Equals(data.SurveyId)).ToListAsync();

                            //remove all and then add
                            foreach (var quest in surveyQuesions)
                            {
                                var questOptions = await _context.SurveyQuestionOptions.Where(x => x.SurveyQuestionId.Equals(quest.Id)).ToListAsync();

                                _context.SurveyQuestionOptions.RemoveRange(questOptions);
                            }
                            _context.SurveyQuestions.RemoveRange(surveyQuesions);
                            await _context.SaveChangesAsync();

                            foreach (var quest in data.Questions)
                            {
                                var survQuestOpts = new List <SurveyQuestionOption>();

                                if (quest.Type.ToLower() != "open")
                                {
                                    foreach (var opt in quest.Options)
                                    {
                                        survQuestOpts.Add(new SurveyQuestionOption()
                                        {
                                            Text = opt
                                        });
                                    }
                                }
                                await _context.SurveyQuestions.AddAsync(new SurveyQuestion()
                                {
                                    Type = quest.Type,
                                    Text = quest.Text,
                                    SurveyQuestionOptions = survQuestOpts,
                                    SurveyId = data.SurveyId,
                                });
                            }
                            await _context.SaveChangesAsync();

                            return(RedirectToAction("ViewGrantForm", "Home", new { area = "Corporate", sid = data.SurveyId }));
                        }
                    }
                }
            }
            return(View());
        }
Пример #32
0
        public IActionResult UserSurveyReports(string surveyGuid)
        {
            SurveyMetrics metric        = new SurveyMetrics(_dBContext, _mapper);
            string        userguid      = Request.Headers[Constants.UserToken];
            string        decyrptstring = Security.Decrypt(userguid);

            if (string.IsNullOrEmpty(decyrptstring))
            {
                return(BadRequest(Messages.UnauthorizedUserError));
            }

            User user = _dBContext.User.Where(x => x.UserGuid == decyrptstring).FirstOrDefault();

            if (user == null)
            {
                return(BadRequest(Messages.UserNotFoundError));
            }

            Survey survey = _dBContext.Survey.Where(x => x.CreatedBy == user.Userid && x.SurveyGuid == surveyGuid).FirstOrDefault();

            if (survey == null)
            {
                return(BadRequest(Messages.SurveyNotFoundError));
            }

            List <SurveyQuestions> surveyQuestions = _dBContext.SurveyQuestions.Where(x => x.StatusId != (int)EnumStatus.Deleted && x.SurveyId == survey.Surveyid).ToList();

            List <QuestionType> questionType = _dBContext.QuestionType.ToList();

            SurveyMetricViewModel          surveyMetric    = new SurveyMetricViewModel();
            List <QuestionMetricViewModel> questionMetrics = new List <QuestionMetricViewModel>();

            foreach (var item in surveyQuestions)
            {
                QuestionMetricViewModel questionMetric = new QuestionMetricViewModel();
                var type = questionType.Where(x => x.TypeId == item.TypeId).Select(x => x.TypeCode).FirstOrDefault();
                switch (type)
                {
                case "radiobuttons":
                    questionMetric = metric.forCountAndAverage(item.SurveyQuestionId);
                    break;

                case "multiple":
                    questionMetric = metric.forCountAndAverage(item.SurveyQuestionId);
                    break;

                case "imageradiobuttons":
                    questionMetric = metric.forCountAndAverage(item.SurveyQuestionId);
                    break;

                case "imagemultiple":
                    questionMetric = metric.forCountAndAverage(item.SurveyQuestionId);
                    break;

                case "slider":
                    questionMetric = metric.forSliderAverage(item.SurveyQuestionId);
                    break;

                case "rangeslider":
                    questionMetric = metric.forSliderAverage(item.SurveyQuestionId);
                    break;

                case "starrating":
                    questionMetric = metric.forStarRatingAverage(item.SurveyQuestionId);
                    break;

                case "multiplerating":
                    questionMetric = metric.forMultipleStarRatings(item.SurveyQuestionId);
                    break;

                case "customrating":
                    questionMetric = metric.forCustomRatings(item.SurveyQuestionId);
                    break;

                default:
                    break;
                }
                questionMetric.QuestionType            = type;
                questionMetric.originalQuestionOptions = _dBContext.SurveyQuestionOptions.Where(x => x.SurveyQuestionId == item.SurveyQuestionId).ToList();

                questionMetrics.Add(questionMetric);
            }

            surveyMetric.Title       = survey.Welcometitle;
            surveyMetric.Description = survey.Welcomedescription;
            surveyMetric.logo        = survey.Welcomeimage;
            surveyMetric.Questions   = questionMetrics;
            return(Ok(surveyMetric));
        }
Пример #33
0
 public IActionResult SurveyResults(Survey survey)
 {
     return(View("SurveyResults", survey));
 }
Пример #34
0
        public void SaveSurvey(Survey survey)
        {
            if (string.IsNullOrEmpty(survey.SlugName) && string.IsNullOrEmpty(survey.Title))
            {
                throw new ArgumentNullException("survey", "The survey for saving has to have the slug or the title.");
            }

            var slugName = string.IsNullOrEmpty(survey.SlugName) ? GenerateSlug(survey.Title, 100) : survey.SlugName;

            var surveyRow = new SurveyRow
            {
                SlugName     = slugName,
                Title        = survey.Title,
                CreatedOn    = DateTime.UtcNow,
                PartitionKey = survey.Tenant
            };

            surveyRow.RowKey = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", survey.Tenant, surveyRow.SlugName);

            var questionRows = new List <QuestionRow>(survey.Questions.Count);

            for (int i = 0; i < survey.Questions.Count; i++)
            {
                var question    = survey.Questions[i];
                var questionRow = new QuestionRow
                {
                    Text            = question.Text,
                    Type            = Enum.GetName(typeof(QuestionType), question.Type),
                    PossibleAnswers = question.PossibleAnswers
                };

                questionRow.PartitionKey = surveyRow.RowKey;
                questionRow.RowKey       = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", DateTime.UtcNow.GetFormatedTicks(), i.ToString("D3"));

                questionRows.Add(questionRow);
            }

            //// First add the questions
            this.questionTable.Add(questionRows);

            try
            {
                //// Then add the survey
                //// If this fails, the questions may end up orphan but data will be consistent for the user
                this.surveyTable.Add(surveyRow);

                if (this.CacheEnabled)
                {
                    TenantCacheHelper.AddToCache(survey.Tenant, slugName, survey);
                }
            }
            catch (DataServiceRequestException ex)
            {
                TraceHelper.TraceError(ex.TraceInformation());

                var dataServiceClientException = ex.InnerException as DataServiceClientException;
                if (dataServiceClientException != null)
                {
                    if (dataServiceClientException.StatusCode == 409)
                    {
                        this.questionTable.Delete(questionRows);
                        throw;
                    }
                }

                throw;
            }
        }
Пример #35
0
 public void AddNewSurveyForUser(Survey survey, int userID)
 {
     survey.UserID = userID;
     _context.Survey.InsertOnSubmit(survey);
     _context.SubmitChanges();
 }
        public IActionResult Index()
        {
            var survey = new Survey();

            return(View(survey));
        }
Пример #37
0
 public IActionResult Submission(Survey mySurvey)
 {
     {
         return(View("results", mySurvey));
     }
 }
Пример #38
0
        public async Task Update(Survey survey)
        {
            var surveyEntiity = _mapper.Map <SurveyEntity>(survey);

            await _service.Update(_collectionName, surveyEntiity.Id, surveyEntiity);
        }
        public IActionResult Index()
        {
            var model = new Survey();

            return(View(model));
        }
Пример #40
0
 public void Start()
 {
     surveyScript = GetComponent <Survey>();
 }
Пример #41
0
        public IActionResult AddNewSurvey([FromBody] SurveyViewModel newSurvey)
        {
            string userId        = Request.Headers[Constants.UserToken];
            string decyrptstring = Security.Decrypt(userId);

            if (decyrptstring == null)
            {
                return(BadRequest());
            }

            User user = _dBContext.User.Where(x => x.UserGuid == decyrptstring).FirstOrDefault();

            if (user == null)
            {
                return(BadRequest(Messages.UserNotFoundError));
            }

            int PublishedStatusId = _dBContext.Status.Where(x => x.Statusname == "Published").Select(x => x.Statusid).FirstOrDefault();

            Survey s = _mapper.Map <Survey>(newSurvey);

            s.StatusId    = PublishedStatusId;
            s.CreatedDate = DateTime.UtcNow;
            s.CreatedBy   = user.Userid;
            s.Enddate     = DateTime.UtcNow.AddYears(1);

            _dBContext.Survey.Add(s);
            _dBContext.SaveChanges();

            List <SurveyQuestions> qlist = new List <SurveyQuestions>();
            int qcount = 0;

            foreach (var item in newSurvey.SurveyQuestions)
            {
                SurveyQuestions question = _mapper.Map <SurveyQuestions>(item);
                question.SurveyId             = s.Surveyid;
                question.CreatedBy            = Convert.ToInt32(s.CreatedBy);
                question.CreatedDate          = DateTime.UtcNow;
                question.StatusId             = PublishedStatusId;
                question.QuestionDisplayOrder = qcount;
                qlist.Add(question);
                qcount++;
            }

            _dBContext.SurveyQuestions.AddRange(qlist);
            _dBContext.SaveChanges();


            for (int i = 0; i < qlist.Count; i++)
            {
                int qid     = qlist[i].SurveyQuestionId;
                var options = newSurvey.SurveyQuestions[i].Options;
                List <SurveyQuestionOptions> qoplist = new List <SurveyQuestionOptions>();
                if (options != null)
                {
                    foreach (var item in options)
                    {
                        SurveyQuestionOptions qop = new SurveyQuestionOptions();
                        qop.SurveyQuestionId = qid;
                        qop.OptionKey        = item.Key;
                        qop.OptionValue      = Convert.ToString(item.Value);
                        qop.CreatedBy        = Convert.ToInt32(s.CreatedBy);
                        qop.CreatedDate      = DateTime.UtcNow;
                        qoplist.Add(qop);
                    }
                    _dBContext.SurveyQuestionOptions.AddRange(qoplist);
                }

                _dBContext.SaveChanges();
            }

            return(GetSurvey(s.Surveyid));
        }
Пример #42
0
        public SurveyEditPage(Patient patient, Survey survey)
        {
            InitializeComponent();

            _patient = patient;
            _survey  = survey;

            this.Title = _patient.Dsc + " " + _patient.PNR;

            foreach (var q in _survey.SurveyAnswers)
            {
                Label headline = new Label();
                headline.Text = q.Dsc;
                headline.HorizontalOptions = LayoutOptions.FillAndExpand;
                stackMain.Children.Add(headline);

                switch (q.OhaTyp.ToLower())
                {
                case "top":
                    headline.BackgroundColor = Color.FromRgb(135, 206, 234);     // Samma som default Telerik i Carita
                    headline.FontSize        = headline.FontSize * 1.5;
                    headline.FontAttributes  = FontAttributes.Bold;
                    break;

                case "sel":
                    headline.FontSize = headline.FontSize * 1.25;
                    string[] sel = q.PrmChr.Split('¤');
                    if (sel.Length > 1)
                    {
                        if (q.PrmDec == 0)
                        {
                            q._checks = new List <RadCheckBox>();
                            for (int i = 0; i < sel.Length - 1; i++)
                            {
                                StackLayout stack = new StackLayout();
                                stack.Orientation = StackOrientation.Horizontal;
                                string[]    vals   = sel[i + 1].Split('|');
                                RadCheckBox button = new RadCheckBox();
                                q._checks.Add(button);
                                button.AutomationId = vals[0] + "|" + vals[1];
                                if (vals[2] == "1")
                                {
                                    button.IsChecked = true;
                                }
                                Label label = new Label();
                                label.Text = vals[0];
                                stack.Children.Add(button);
                                stack.Children.Add(label);
                                stackMain.Children.Add(stack);
                                button.IsCheckedChanged += Button_IsCheckedChanged;
                            }
                        }
                        else
                        {
                            q._checks = new List <RadCheckBox>();
                            for (int i = 0; i < sel.Length - 1; i++)
                            {
                                StackLayout stack = new StackLayout();
                                stack.Orientation = StackOrientation.Horizontal;
                                string[]    vals   = sel[i + 1].Split('|');
                                RadCheckBox button = new RadCheckBox();
                                q._checks.Add(button);
                                button.AutomationId = vals[0] + "|" + vals[1];
                                if (vals[2] == "1")
                                {
                                    button.IsChecked = true;
                                }
                                Label label = new Label();
                                label.Text = vals[0];
                                stack.Children.Add(button);
                                stack.Children.Add(label);
                                stackMain.Children.Add(stack);
                            }
                        }
                    }
                    break;

                case "chr":
                    headline.FontSize = headline.FontSize * 1.25;
                    Editor editor = new Editor();
                    q._editor = editor;
                    editor.HorizontalOptions = LayoutOptions.FillAndExpand;
                    editor.HeightRequest     = 80;
                    editor.Text = q.TextBoxText;
                    stackMain.Children.Add(editor);
                    break;

                case "int":
                    headline.FontSize = headline.FontSize * 1.25;
                    RadNumericInput numeric = new RadNumericInput();
                    q._numeric                = numeric;
                    numeric.Value             = q.NumericValue;
                    numeric.HorizontalOptions = LayoutOptions.Start;
                    stackMain.Children.Add(numeric);
                    break;

                case "tooth":
                    headline.FontSize = headline.FontSize * 1.25;
                    q._images         = new List <Image>();

                    Grid outerGrid = new Grid();
                    outerGrid.ColumnDefinitions.Add(new ColumnDefinition()
                    {
                        Width = GridLength.Auto
                    });
                    outerGrid.ColumnDefinitions.Add(new ColumnDefinition()
                    {
                        Width = GridLength.Auto
                    });
                    outerGrid.ColumnDefinitions.Add(new ColumnDefinition()
                    {
                        Width = GridLength.Auto
                    });
                    outerGrid.RowDefinitions.Add(new RowDefinition()
                    {
                        Height = GridLength.Auto
                    });
                    outerGrid.RowDefinitions.Add(new RowDefinition()
                    {
                        Height = GridLength.Auto
                    });
                    outerGrid.RowDefinitions.Add(new RowDefinition()
                    {
                        Height = GridLength.Auto
                    });

                    Label newLabel;

                    newLabel = new Label()
                    {
                        Text = "ÖK", HorizontalTextAlignment = TextAlignment.Center
                    };
                    Grid.SetColumn(newLabel, 1);
                    Grid.SetRow(newLabel, 0);
                    outerGrid.Children.Add(newLabel);

                    newLabel = new Label()
                    {
                        Text = "UK", HorizontalTextAlignment = TextAlignment.Center
                    };
                    Grid.SetColumn(newLabel, 1);
                    Grid.SetRow(newLabel, 2);
                    outerGrid.Children.Add(newLabel);

                    newLabel = new Label()
                    {
                        Text = "HÖ", VerticalTextAlignment = TextAlignment.Center
                    };
                    Grid.SetColumn(newLabel, 0);
                    Grid.SetRow(newLabel, 1);
                    outerGrid.Children.Add(newLabel);

                    newLabel = new Label()
                    {
                        Text = "VÄ", VerticalTextAlignment = TextAlignment.Center
                    };
                    Grid.SetColumn(newLabel, 2);
                    Grid.SetRow(newLabel, 1);
                    outerGrid.Children.Add(newLabel);

                    StackLayout innerStack = new StackLayout()
                    {
                        Orientation = StackOrientation.Vertical
                    };
                    Grid.SetColumn(innerStack, 1);
                    Grid.SetRow(innerStack, 1);
                    outerGrid.Children.Add(innerStack);

                    Grid newGrid = new Grid()
                    {
                        ColumnSpacing = 0, RowSpacing = 0
                    };
                    newGrid.RowDefinitions.Add(new RowDefinition());
                    for (int i = 0; i < 16; i++)
                    {
                        newGrid.ColumnDefinitions.Add(new ColumnDefinition()
                        {
                            Width = GridLength.Auto
                        });
                    }
                    Image newImg;
                    for (int i = 0; i < 16; i++)
                    {
                        newImg = new Image()
                        {
                            Source = ImageSource.FromResource("CaritaUAT.Icons.t" + i.ToString() + ".png", typeof(Patient).GetTypeInfo().Assembly)
                        };
                        Grid.SetColumn(newImg, i);
                        newGrid.Children.Add(newImg);
                        switch (q.PrmChr.Substring(i, 1))
                        {
                        case "0":
                            // Vit
                            newImg.BackgroundColor = Color.White;
                            break;

                        case "1":
                            // Röd
                            newImg.BackgroundColor = Color.Red;
                            break;

                        case "2":
                            // Blå
                            newImg.BackgroundColor = Color.Blue;
                            break;

                        case "3":
                            // Svart
                            newImg.BackgroundColor = Color.Black;
                            break;
                        }
                        TapGestureRecognizer newTap = new TapGestureRecognizer()
                        {
                            NumberOfTapsRequired = 1
                        };
                        newTap.Tapped += NewTap_Tapped;
                        newImg.GestureRecognizers.Add(newTap);
                        q._images.Add(newImg);
                    }
                    innerStack.Children.Add(newGrid);

                    newGrid = new Grid()
                    {
                        ColumnSpacing = 0, RowSpacing = 0
                    };
                    newGrid.RowDefinitions.Add(new RowDefinition());
                    for (int i = 0; i < 16; i++)
                    {
                        newGrid.ColumnDefinitions.Add(new ColumnDefinition()
                        {
                            Width = GridLength.Auto
                        });
                    }
                    for (int i = 0; i < 16; i++)
                    {
                        newImg = new Image()
                        {
                            Source = ImageSource.FromResource("CaritaUAT.Icons.t" + (i + 16).ToString() + ".png", typeof(Patient).GetTypeInfo().Assembly)
                        };
                        Grid.SetColumn(newImg, i);
                        newGrid.Children.Add(newImg);
                        switch (q.PrmChr.Substring(i + 16, 1))
                        {
                        case "0":
                            // Vit
                            newImg.BackgroundColor = Color.White;
                            break;

                        case "1":
                            // Röd
                            newImg.BackgroundColor = Color.Red;
                            break;

                        case "2":
                            // Blå
                            newImg.BackgroundColor = Color.Blue;
                            break;

                        case "3":
                            // Svart
                            newImg.BackgroundColor = Color.Black;
                            break;
                        }
                        TapGestureRecognizer newTap = new TapGestureRecognizer()
                        {
                            NumberOfTapsRequired = 1
                        };
                        newTap.Tapped += NewTap_Tapped;
                        newImg.GestureRecognizers.Add(newTap);
                        q._images.Add(newImg);
                    }
                    innerStack.Children.Add(newGrid);
                    stackMain.Children.Add(outerGrid);

                    newGrid = new Grid();
                    newGrid.RowDefinitions.Add(new RowDefinition());
                    newGrid.RowDefinitions.Add(new RowDefinition());
                    newGrid.RowDefinitions.Add(new RowDefinition());
                    newGrid.ColumnDefinitions.Add(new ColumnDefinition()
                    {
                        Width = GridLength.Auto
                    });
                    newGrid.ColumnDefinitions.Add(new ColumnDefinition()
                    {
                        Width = GridLength.Auto
                    });

                    BoxView newBox;
                    newBox = new BoxView()
                    {
                        BackgroundColor = Color.Red, WidthRequest = 16, HeightRequest = 16
                    };
                    Grid.SetRow(newBox, 0);
                    Grid.SetColumn(newBox, 0);
                    newGrid.Children.Add(newBox);
                    newBox = new BoxView()
                    {
                        BackgroundColor = Color.Blue, WidthRequest = 16, HeightRequest = 16
                    };
                    Grid.SetRow(newBox, 1);
                    Grid.SetColumn(newBox, 0);
                    newGrid.Children.Add(newBox);
                    newBox = new BoxView()
                    {
                        BackgroundColor = Color.Black, WidthRequest = 16, HeightRequest = 16
                    };
                    Grid.SetRow(newBox, 2);
                    Grid.SetColumn(newBox, 0);
                    newGrid.Children.Add(newBox);

                    newLabel = new Label()
                    {
                        Text = "Avtagbart"
                    };
                    Grid.SetRow(newLabel, 0);
                    Grid.SetColumn(newLabel, 1);
                    newGrid.Children.Add(newLabel);
                    newLabel = new Label()
                    {
                        Text = "Fastsittande tänder"
                    };
                    Grid.SetRow(newLabel, 1);
                    Grid.SetColumn(newLabel, 1);
                    newGrid.Children.Add(newLabel);
                    newLabel = new Label()
                    {
                        Text = "Saknad tand"
                    };
                    Grid.SetRow(newLabel, 2);
                    Grid.SetColumn(newLabel, 1);
                    newGrid.Children.Add(newLabel);

                    stackMain.Children.Add(newGrid);

                    break;
                }
            }
        }
Пример #43
0
        public IActionResult GetSurveyUserFeedback(string surveyUserGuid)
        {
            SurveyViewModel surview       = new SurveyViewModel();
            string          userguid      = Request.Headers[Constants.UserToken];
            string          decyrptstring = Security.Decrypt(userguid);

            if (string.IsNullOrEmpty(decyrptstring))
            {
                return(BadRequest(Messages.UnauthorizedUserError));
            }

            User user = _dBContext.User.Where(x => x.UserGuid == decyrptstring).FirstOrDefault();

            if (user == null)
            {
                return(BadRequest(Messages.UserNotFoundError));
            }

            SurveyUser surveyuser = _dBContext.SurveyUser.Where(x => x.SurveyUserGuid == surveyUserGuid).FirstOrDefault();

            if (surveyuser == null)
            {
                return(BadRequest(Messages.SurveyUserNotFoundError));
            }

            Survey survey = _dBContext.Survey.Where(x => x.CreatedBy == user.Userid && x.Surveyid == surveyuser.SurveyId).FirstOrDefault();

            if (survey == null)
            {
                return(BadRequest(Messages.SurveyNotFoundError));
            }

            surview = _mapper.Map <SurveyViewModel>(survey);

            List <SurveyQuestions>          surveyQuestions = _dBContext.SurveyQuestions.Where(x => x.StatusId != (int)EnumStatus.Deleted && x.SurveyId == survey.Surveyid).ToList();
            List <QuestionType>             questiontypes   = _dBContext.QuestionType.ToList();
            List <SurveyQuestionsViewModel> viewquestions   = new List <SurveyQuestionsViewModel>();

            foreach (var item in surveyQuestions)
            {
                SurveyQuestionsViewModel         viewquestion = _mapper.Map <SurveyQuestionsViewModel>(item);
                List <SurveyUserQuestionOptions> surveyuserquestionoptions = new List <SurveyUserQuestionOptions>();
                List <string> selectedoptions        = new List <string>();
                string        optiontypevalue        = null;
                List <SurveyQuestionOptions> options = new List <SurveyQuestionOptions>();
                options = _dBContext.SurveyQuestionOptions.Where(x => x.SurveyQuestionId == item.SurveyQuestionId).OrderBy(x => x.OptionKey).ToList();
                surveyuserquestionoptions = _dBContext.SurveyUserQuestionOptions.Where(x => x.SurveyQuestionId == item.SurveyQuestionId && x.SurveyUserId == surveyuser.SurveyUserId).ToList();
                if (questiontypes != null)
                {
                    optiontypevalue = questiontypes.FirstOrDefault(x => x.TypeId == item.TypeId).TypeValue;
                }
                if (surveyuserquestionoptions != null)
                {
                    foreach (var itemq in surveyuserquestionoptions)
                    {
                        string option = null;
                        option = itemq.SurveyQuestionOptionId;
                        selectedoptions.Add(option);
                    }
                }
                Dictionary <string, object> dict = new Dictionary <string, object>();
                foreach (var opt in options)
                {
                    dict.Add(opt.OptionKey, opt.OptionValue);
                }
                viewquestion.Options        = dict;
                viewquestion.ObjectOptions  = options;
                viewquestion.questiontype   = optiontypevalue;
                viewquestion.selectedValues = selectedoptions;
                viewquestions.Add(viewquestion);
            }
            surview.SurveyQuestions = viewquestions;
            return(Ok(surview));
        }
Пример #44
0
 public Flow(string name, Survey survey)
 {
     this.name        = name;
     this.inputSurvey = survey;
 }
Пример #45
0
 public MainWindow()
 {
     InitializeComponent();
     Survey           = StoreFitsData.Survey;
     this.DataContext = Survey;
 }
Пример #46
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="survey"></param>
 /// <param name="code"></param>
 /// <returns></returns>
 public async Task <Shortcode> GetShortcodeForSurveyAsync(Survey survey, string code)
 {
     return(await _appContext.Shortcodes
            .Where(s => s.Survey == survey && s.Code == code).FirstOrDefaultAsync());
 }
 private void ProcessSurvey(IServiceScope scope, ApplicationDbContext context, Survey item)
 {
     try
     {
         var survey = item;
         context.Surveys.Add(survey);
         context.Entry(survey).State = EntityState.Added;
         context.SaveChanges();
         var x = this.Queue.DequeueAsync(new CancellationToken()).Result;
     }
     catch (Exception e)
     {
         log.Trace($"Error in item {e} - {item}");
     }
 }
        public void NewWhenHttpVerbIsPostReturnsRedirectToMySurveysWhenModelStateIsValid()
        {
            var cachedSurvey = new Survey();
            cachedSurvey.Questions.Add(new Question());

            using (var controller = new SurveysController(new Mock<ISurveyStore>().Object, null, null, null, null, null))
            {
                controller.TenantName = "Tenant";
                controller.Tenant = new Tenant() { SubscriptionKind = SubscriptionKind.Standard };
                controller.TempData[SurveysController.CachedSurvey] = cachedSurvey;

                var result = controller.New(new Survey()) as RedirectToRouteResult;

                Assert.AreEqual("Index", result.RouteValues["action"]);
                Assert.AreEqual(null, result.RouteValues["controller"]);
            }
        }
Пример #49
0
        protected void DvItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            string returnURL = "~/ControlRoom/Modules/Setup/SurveyList.aspx";

            if (e.CommandName.ToLower() == "back")
            {
                Response.Redirect(returnURL);
            }
            if (e.CommandName.ToLower() == "refresh")
            {
                try
                {
                    odsData.DataBind();
                    dv.DataBind();
                    dv.ChangeMode(DetailsViewMode.Edit);

                    var masterPage = (IControlRoomMaster)Master;
                    if (masterPage != null)
                    {
                        masterPage.PageMessage = SRPResources.RefreshOK;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }
            if (e.CommandName.ToLower() == "add" || e.CommandName.ToLower() == "addandback")
            {
                try
                {
                    var obj = new Survey();
                    //obj.GenNotificationFlag = ((CheckBox)((DetailsView)sender).FindControl("TabContainer1").FindControl("TabPanel2").FindControl("GenNotificationFlag")).Checked;

                    obj.Name        = ((TextBox)((DetailsView)sender).FindControl("Name")).Text;
                    obj.LongName    = ((TextBox)((DetailsView)sender).FindControl("LongName")).Text;
                    obj.Description = ((TextBox)((DetailsView)sender).FindControl("Description")).Text;
                    obj.Preamble    = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("Preamble")).Text;
                    obj.Status      = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("Status")).SelectedValue);
                    //obj.TakenCount = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("TakenCount")).Text);
                    //obj.PatronCount = FormatHelper.SafeToInt(((TextBox)((DetailsView)sender).FindControl("PatronCount")).Text);
                    //obj.CanBeScored = ((CheckBox)((DetailsView)sender).FindControl("CanBeScored")).Checked;

                    if (obj.IsValid(BusinessRulesValidationMode.INSERT))
                    {
                        obj.Insert();
                        if (e.CommandName.ToLower() == "addandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        lblPK.Text     = obj.SID.ToString();
                        Session["SID"] = obj.SID;

                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = SRPResources.AddedOK;
                    }
                    else
                    {
                        var    masterPage = (IControlRoomMaster)Master;
                        string message    = String.Format(SRPResources.ApplicationError1, "<ul>");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}</ul>", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }
            if (e.CommandName.ToLower() == "save" || e.CommandName.ToLower() == "saveandback" || e.CommandName.ToLower() == "questions")
            {
                try
                {
                    var obj = new Survey();
                    int pk  = int.Parse(lblPK.Text);
                    obj.Fetch(pk);

                    obj.Name        = ((TextBox)((DetailsView)sender).FindControl("Name")).Text;
                    obj.LongName    = ((TextBox)((DetailsView)sender).FindControl("LongName")).Text;
                    obj.Description = ((TextBox)((DetailsView)sender).FindControl("Description")).Text;
                    obj.Preamble    = ((CKEditor.NET.CKEditorControl)((DetailsView)sender).FindControl("Preamble")).Text;
                    obj.Status      = FormatHelper.SafeToInt(((DropDownList)((DetailsView)sender).FindControl("Status")).SelectedValue);

                    if (obj.IsValid(BusinessRulesValidationMode.UPDATE))
                    {
                        obj.Update();
                        if (e.CommandName.ToLower() == "saveandback")
                        {
                            Response.Redirect(returnURL);
                        }

                        if (e.CommandName.ToLower() == "questions")
                        {
                            Response.Redirect("~/ControlRoom/Modules/Setup/SurveyQuestionList.aspx");
                        }

                        odsData.DataBind();
                        dv.DataBind();
                        dv.ChangeMode(DetailsViewMode.Edit);

                        var masterPage = (IControlRoomMaster)Master;
                        masterPage.PageMessage = SRPResources.SaveOK;
                    }
                    else
                    {
                        var    masterPage = (IControlRoomMaster)Master;
                        string message    = String.Format(SRPResources.ApplicationError1, "<ul>");
                        foreach (BusinessRulesValidationMessage m in obj.ErrorCodes)
                        {
                            message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage);
                        }
                        message = string.Format("{0}</ul>", message);
                        masterPage.PageError = message;
                    }
                }
                catch (Exception ex)
                {
                    var masterPage = (IControlRoomMaster)Master;
                    masterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message);
                }
            }

            if (e.CommandName.ToLower() == "results")
            {
                Response.Redirect("SurveyResults.aspx");
            }

            if (e.CommandName.ToLower() == "embed")
            {
                Response.Redirect("SurveyEmbedCode.aspx");
            }
        }
        public void NewWhenHttpVerbIsPostSavedTenantNameIsSameAsControllerWhenModelStateIsValid()
        {
            var mockSurveyStore = new Mock<ISurveyStore>();

            var cachedSurvey = new Survey();
            cachedSurvey.Questions.Add(new Question());

            using (var controller = new SurveysController(mockSurveyStore.Object, null, null, null, null, null))
            {
                controller.TenantName = "Tenant";
                controller.Tenant = new Tenant() { SubscriptionKind = SubscriptionKind.Standard };
                controller.TempData[SurveysController.CachedSurvey] = cachedSurvey;

                controller.New(new Survey());
            }

            mockSurveyStore.Verify(r => r.SaveSurvey(It.Is<Survey>(s => s.Tenant == "Tenant")), Times.Once());
        }
Пример #51
0
        public void Results_PublicResultsAnonymousUser_ReturnsViewWithViewModelWithNoComments()
        {
            var id     = Guid.NewGuid();
            var survey = new Survey()
            {
                Id = id, PublicResults = true, Owner = new ApplicationUser()
                {
                    UserName = "******"
                }
            };
            var moods = new[] { new Models.Mood()
                                {
                                    Id = 1
                                }, new Models.Mood()
                                {
                                    Id = 2
                                } };
            var answer1 = new Answer()
            {
                MoodId = 1, SurveyId = id, Details = "I am very angry"
            };
            var answer2 = new Answer()
            {
                MoodId = 2, SurveyId = id, Details = "I am very happy"
            };
            var answers = new List <Answer>()
            {
                answer1, answer2
            };

            var surveysMock = new Mock <ISurveyService>();

            surveysMock.Setup(s => s.FindAsync(id.ToString())).ReturnsAsync(survey);

            var dbMock         = new Mock <IApplicationDBContext>();
            var moodDataMock   = new Mock <DbSet <Models.Mood> >().SetupData(moods);
            var answerDataMock = new Mock <DbSet <Answer> >().SetupData(answers);

            dbMock.Setup(db => db.Moods).Returns(moodDataMock.Object);
            dbMock.Setup(db => db.Answers).Returns(answerDataMock.Object);

            var securityMock = new Mock <ISecurity>();

            securityMock.SetupGet(s => s.UserName).Returns("Peter");
            securityMock.SetupGet(s => s.IsAuthenticated).Returns(true);

            var subject = new AnswerController(dbMock.Object, surveysMock.Object, Mock.Of <IDateTimeService>(), securityMock.Object);

            var result = subject.Results(id.ToString()).Result;

            Assert.IsInstanceOfType(result, typeof(ViewResult));
            var model = (result as ViewResult).Model as ResultsViewModel;

            Assert.IsNotNull(model);
            Assert.AreSame(survey, model.Survey);
            Assert.AreEqual(2, model.Answers.Count());
            Assert.AreSame(answer1, model.Answers.ToList()[0]);
            Assert.AreSame(answer2, model.Answers.ToList()[1]);
            Assert.IsNull(model.Answers.ToList()[0].Details);
            Assert.IsNull(model.Answers.ToList()[1].Details);
        }
Пример #52
0
            /// <summary>
            /// Initialize the node answer cache
            /// </summary>
            /// <param name="element">The element to query</param>
            /// <param name="contextElement">The context element for this node</param>
            /// <param name="survey">The <see cref="Survey"/>s to initialize the node for</param>
            /// <returns>Packed bitfield integer containing all current answers</returns>
            private static int InitializeNodeData(object element, object contextElement, Survey survey)
            {
                int data          = 0;
                int questionCount = survey.Count;

                for (int i = 0; i < questionCount; ++i)
                {
                    SurveyQuestion currentQuestion = survey[i];
                    int            currentAnswer   = currentQuestion.Question.AskQuestion(element, contextElement);
                    data |= (currentAnswer << currentQuestion.Shift) & currentQuestion.Mask;
                }
                return(data);
            }
Пример #53
0
 public async Task <IActionResult> Post([FromBody] Survey value)
 {
     _surveys.Add(value);
     return(Ok());
 }
Пример #54
0
 public ActionResult Delete(Survey survey)
 {
     _db.Entry(survey).State = EntityState.Deleted;
     _db.SaveChanges();
     return(RedirectToAction("Index"));
 }
        public void NewWhenHttpVerbIsPostReturnsTitleInTheModelWhenModelStateIsNotValid()
        {
            var survey = new Survey();

            using (var controller = new SurveysController(new Mock<ISurveyStore>().Object, null, null, null, null, null))
            {
                controller.ModelState.AddModelError("error for test", "invalid model state");
                controller.TempData[SurveysController.CachedSurvey] = new Survey();

                var result = controller.New(survey) as ViewResult;

                var model = result.ViewData.Model as TenantMasterPageViewData;
                Assert.AreSame("New Survey", model.Title);
            }
        }
Пример #56
0
 public Survey4(Survey s)
 {
     InitializeComponent();
     survey = s;
 }
        public void NewWhenHttpVerbIsPostSavesCachedSurveyInTempDataWhenCachedSurveyHasNoQuestions()
        {
            var cachedSurvey = new Survey { Questions = new List<Question>() };

            using (var controller = new SurveysController(new Mock<ISurveyStore>().Object, null, null, null, null, null))
            {
                controller.TempData[SurveysController.CachedSurvey] = cachedSurvey;

                var result = controller.New(new Survey()) as ViewResult;

                var model = result.ViewData.Model as TenantPageViewData<Survey>;
                Assert.AreSame(cachedSurvey, controller.TempData[SurveysController.CachedSurvey]);
            }
        }
Пример #58
0
        public IActionResult SubmitSurvey(string guid, string session, QuestionAnswersRequestViewModel data)
        {
            List <QuestionAnswersViewModel> jObject = data.data;
            Survey sur = _dBContext.Survey.Where(x => x.SurveyGuid == guid).FirstOrDefault();

            if (sur == null)
            {
                return(BadRequest(Messages.SurveyNotFoundError));
            }

            if (sur.Enddate < DateTime.UtcNow)
            {
                return(BadRequest(Messages.SurveyEnded));
            }

            var surveyUsers = _dBContext.SurveyUser.Where(x => x.SurveyId == sur.Surveyid && x.SurveyUserGuid.Equals(session)).FirstOrDefault();

            if (surveyUsers == null)
            {
                return(BadRequest(Messages.SurveyWasNotStartedByUser));
            }
            if (surveyUsers.CompletedDatetime != null)
            {
                return(BadRequest(Messages.SurveyWasAlreadySubmitted));
            }

            List <SurveyQuestions>           questions                    = _dBContext.SurveyQuestions.Where(x => x.SurveyId == sur.Surveyid && x.StatusId != (int)EnumStatus.Deleted).ToList();
            List <QuestionType>              lstQuestionTypes             = _dBContext.QuestionType.ToList();
            List <SurveyUserQuestionOptions> lstSurveyUserQuestionOptions = new List <SurveyUserQuestionOptions>();

            for (int i = 0; i < questions.Count; i++)
            {
                SurveyUserQuestionOptions surveyUserQuestionOption = new SurveyUserQuestionOptions();
                surveyUserQuestionOption.SurveyUserId     = surveyUsers.SurveyUserId;
                surveyUserQuestionOption.SurveyQuestionId = questions[i].SurveyQuestionId;
                surveyUserQuestionOption.InsertedDatetime = DateTime.UtcNow;

                QuestionAnswersViewModel     requestViewModel      = jObject.Where(x => x.key == questions[i].SurveyQuestionId.ToString()).FirstOrDefault();
                List <SurveyQuestionOptions> surveyQuestionOptions = _dBContext.SurveyQuestionOptions.Where(x => x.SurveyQuestionId == surveyUserQuestionOption.SurveyQuestionId).OrderBy(x => x.OptionKey).ToList();
                var  questionTypeCode = lstQuestionTypes.Where(x => x.TypeId == questions[i].TypeId).FirstOrDefault().TypeCode;
                bool addToList        = true;
                int  tempNumber       = 0;

                switch (questionTypeCode)
                {
                case "essay":
                    surveyUserQuestionOption.CustomAnswer = requestViewModel.text;
                    break;

                case "radiobuttons":
                    surveyUserQuestionOption.SurveyQuestionOptionId = requestViewModel.number.ToString();
                    break;

                case "imageradiobuttons":
                    surveyUserQuestionOption.SurveyQuestionOptionId = requestViewModel.number.ToString();
                    break;

                case "multiple":
                    foreach (var item in requestViewModel.selected)
                    {
                        SurveyUserQuestionOptions tempSurveyUserQuestionOption = new SurveyUserQuestionOptions();
                        tempSurveyUserQuestionOption.SurveyUserId           = surveyUsers.SurveyUserId;
                        tempSurveyUserQuestionOption.SurveyQuestionId       = questions[i].SurveyQuestionId;
                        tempSurveyUserQuestionOption.InsertedDatetime       = DateTime.UtcNow;
                        tempSurveyUserQuestionOption.SurveyQuestionOptionId = item;
                        lstSurveyUserQuestionOptions.Add(tempSurveyUserQuestionOption);
                    }
                    addToList = false;
                    break;

                case "imagemultiple":
                    foreach (var item in requestViewModel.selected)
                    {
                        SurveyUserQuestionOptions tempSurveyUserQuestionOption = new SurveyUserQuestionOptions();
                        tempSurveyUserQuestionOption.SurveyUserId           = surveyUsers.SurveyUserId;
                        tempSurveyUserQuestionOption.SurveyQuestionId       = questions[i].SurveyQuestionId;
                        tempSurveyUserQuestionOption.InsertedDatetime       = DateTime.UtcNow;
                        tempSurveyUserQuestionOption.SurveyQuestionOptionId = item;
                        lstSurveyUserQuestionOptions.Add(tempSurveyUserQuestionOption);
                    }
                    addToList = false;
                    break;

                case "slider":
                    surveyUserQuestionOption.SurveyQuestionOptionId = requestViewModel.number.ToString();
                    break;

                case "rangeslider":
                    int j = 0;
                    foreach (var item in requestViewModel.selected)
                    {
                        SurveyUserQuestionOptions tempSurveyUserQuestionOption = new SurveyUserQuestionOptions();
                        tempSurveyUserQuestionOption.SurveyUserId           = surveyUsers.SurveyUserId;
                        tempSurveyUserQuestionOption.SurveyQuestionId       = questions[i].SurveyQuestionId;
                        tempSurveyUserQuestionOption.InsertedDatetime       = DateTime.UtcNow;
                        tempSurveyUserQuestionOption.SurveyQuestionOptionId = item;
                        tempSurveyUserQuestionOption.CustomAnswer           = j == 0 ? "min" : "max";
                        lstSurveyUserQuestionOptions.Add(tempSurveyUserQuestionOption);
                        j++;
                    }
                    addToList = false;
                    break;

                case "starrating":
                    surveyUserQuestionOption.SurveyQuestionOptionId = requestViewModel.number.ToString();
                    break;

                case "multiplerating":
                    foreach (var item in requestViewModel.selected)
                    {
                        SurveyUserQuestionOptions tempSurveyUserQuestionOption = new SurveyUserQuestionOptions();
                        tempSurveyUserQuestionOption.SurveyUserId           = surveyUsers.SurveyUserId;
                        tempSurveyUserQuestionOption.SurveyQuestionId       = questions[i].SurveyQuestionId;
                        tempSurveyUserQuestionOption.InsertedDatetime       = DateTime.UtcNow;
                        tempSurveyUserQuestionOption.SurveyQuestionOptionId = surveyQuestionOptions[tempNumber].SurveyQuestionOptionId.ToString();
                        tempSurveyUserQuestionOption.CustomAnswer           = item;
                        lstSurveyUserQuestionOptions.Add(tempSurveyUserQuestionOption);
                        tempNumber++;
                    }
                    addToList = false;
                    break;

                case "customrating":

                    var surveyQuestionOptionsValues = surveyQuestionOptions.Where(x => x.OptionKey.StartsWith("value")).OrderBy(x => x.OptionKey).ToList();
                    foreach (var item in requestViewModel.selected)
                    {
                        SurveyUserQuestionOptions tempSurveyUserQuestionOption = new SurveyUserQuestionOptions();
                        tempSurveyUserQuestionOption.SurveyUserId           = surveyUsers.SurveyUserId;
                        tempSurveyUserQuestionOption.SurveyQuestionId       = questions[i].SurveyQuestionId;
                        tempSurveyUserQuestionOption.InsertedDatetime       = DateTime.UtcNow;
                        tempSurveyUserQuestionOption.SurveyQuestionOptionId = surveyQuestionOptionsValues[tempNumber].SurveyQuestionOptionId.ToString();
                        tempSurveyUserQuestionOption.CustomAnswer           = item;
                        lstSurveyUserQuestionOptions.Add(tempSurveyUserQuestionOption);
                        tempNumber++;
                    }
                    addToList = false;
                    break;

                default:
                    surveyUserQuestionOption.CustomAnswer = requestViewModel.text;
                    break;
                }

                if (addToList)
                {
                    lstSurveyUserQuestionOptions.Add(surveyUserQuestionOption);
                }
            }

            _dBContext.SurveyUserQuestionOptions.AddRange(lstSurveyUserQuestionOptions);
            surveyUsers.CompletedDatetime = DateTime.UtcNow;
            _dBContext.Update(surveyUsers);
            _dBContext.SaveChanges();

            return(Ok());
        }
Пример #59
0
        public string GetStorageKeyFor(Survey survey)
        {
            var slugName = string.IsNullOrEmpty(survey.SlugName) ? GenerateSlug(survey.Title, 100) : survey.SlugName;

            return(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", survey.Tenant, slugName));
        }
Пример #60
0
        private async void SaveData_Activated(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(questionEntry.Text) || questionEntry.Text.Contains("~"))
            {
                checkinputs.Text = Lang.Resource.check_inputsSignin3;
                return;
            }
            Text_Question question = new Text_Question(TypeQuestion.Text, questionEntry.Text);

            question.Initialize(TypeQuestion.Text, questionEntry.Text, switchAnswer.IsToggled, " ");

            // Store Data in File Of Survey
            folder = FileSystem.Current.LocalStorage;

            username = await controlFile.GetUserName();

            folder = await folder.CreateFolderAsync("foldersurveys" + username, CreationCollisionOption.OpenIfExists);

            file = await folder.CreateFileAsync("filesurveys" + username, CreationCollisionOption.OpenIfExists);

            string content = await file.ReadAllTextAsync();

            ListSurveys = Serializable_Survey.deserialize(content);

            if (_questionSelected != null)
            {
                foreach (Survey S in ListSurveys)
                {
                    if (S.Id == survey.Id)
                    {
                        Text_Question questionText = new Text_Question(TypeQuestion.Text, questionEntry.Text);
                        questionText.Initialize(TypeQuestion.Text, questionEntry.Text, switchAnswer.IsToggled, " ");
                        (S.Questions_Property.ElementAt(_index) as Text_Question).Edit_Question(questionText);
                        survey = S;
                        break;
                    }
                }
            }
            else
            {
                foreach (Survey S in ListSurveys)
                {
                    if (S.Id == survey.Id)
                    {
                        S.Questions_Property.Add(question);

                        survey = S;
                        break;
                    }
                }
            }
            if (CheckNetwork.Check_Connectivity())
            {
                SurveysServices S_S = new SurveysServices();
                S_S.Set_UrlApi("EditSurveys/" + username);
                await S_S.PutSurveysAsync(survey);
            }


            content = Serializable_Survey.serialize(ListSurveys.ToList());

            await file.WriteAllTextAsync(content);

            await Navigation.PopModalAsync();
        }