Пример #1
0
        public ActionResult DoDetailSurvey(SurveyViewModel model)
        {
            //string a= model.AnswerContent;
            string[] listQuestion = Request.Form.GetValues("question");
            User     currentUser  = userService.FindById(int.Parse(User.Identity.GetUserId()));
            String   action       = this.Request.QueryString["answer"];
            string   forum        = ((string)this.RouteData.Values["answer"] == null) ? (string)this.RouteData.Values["answer"] : "";

            //string[] choice = new string[] { Request.Form.Get("AnswerContent") };
            string[] choice = Request.Form.GetValues("answer");
            //string choice = Request.Form.Get("AnswerContent");
            // choice = Request.Form.GetValues("AnswerContent");
            //string[] choiceIds = Request.Form.GetValues("answerId");
            //List<string> listChoice = new List<string>(choice);
            //List<string> listQuestions = new List<string>(listQuestion);

            if (Request["answer"] != null)
            {
                string         strName        = Request["answer"].ToString();
                UserAnswerPoll UserAnswerPoll = new UserAnswerPoll();
                UserAnswerPoll.PollId = model.Id;
                UserAnswerPoll.UserId = currentUser.Id;
                //   UserAnswerPoll.UserId = 4;
                // string answerId = answerService.FindByContent(strName, model.Id).Id;
                //var answerId = answerService.FindByContent(model.AnswerContent, model.Id).Id;
                UserAnswerPoll.AnswerDate = DateTime.Now;
                UserAnswerPoll.Answer     = strName;
                userAnswerService.AddUserAnswerPoll(UserAnswerPoll);
            }



            return(RedirectToAction("DoSurvey"));

            // return RedirectToAction("DoDetailSurvey", new { PollId = @model.Id });
        }
        public ActionResult Index(int intervieweeId, int interviewerId)
        {
            using (var dbContext = new AARPDbContext())
            {
                var interview = dbContext.Interviews.Where(t => t.IntervieweeId == intervieweeId && t.InterviewerId == interviewerId)
                                .OrderByDescending(o => o.Date).FirstOrDefault();

                if (interview != null)
                {
                    var survey = new SurveyViewModel
                    {
                        Id = interview.Id,
                    };

                    ViewBag.InterviewLengths = dbContext.InterviewLengths.ToList();

                    return(View(survey));
                }
                else
                {
                    throw new ArgumentException("Interview with specified parameters not found.");
                }
            }
        }
Пример #3
0
        public ActionResult Survey(int Category, string subCategories)
        {
            var surveys           = new List <SurveyDTO>();
            var subcategories_Ids = new List <int>();

            foreach (string subcategory in subCategories.Split(','))
            {
                if (subcategory != "")
                {
                    subcategories_Ids.Add(int.Parse(subcategory));
                }
            }

            renderSubCategory(Category, surveys, subcategories_Ids);

            var userId = this.User.Identity.GetUserId();
            var user   = this.modelContext
                         .Users
                         .Single(x => x.Id == userId);

            if (!user.CompanyId.HasValue)
            {
                throw new ArgumentNullException("User company id is null");
            }

            var model = new SurveyViewModel
            {
                SurveyDTOs         = surveys,
                CategoryId         = Category,
                SurveyId           = surveys.Where(x => x.CategoryId == Category).FirstOrDefault().SurveyId,
                CompanyId          = user.CompanyId.Value,
                SurveyCompletionId = 0
            };

            return(View("~/Views/Oferta/Survey/Survey.cshtml", model));
        }
Пример #4
0
        // This region should probably have its own DAO
        #region Survey
        public bool SaveNewPost(SurveyViewModel survey)
        {
            bool result = false;

            // Create a connection
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                // Open the connection
                conn.Open();

                // Create the command
                SqlCommand cmd = new SqlCommand("INSERT INTO survey_result VALUES (@parkCode, @emailAddress, @state, @activityLevel);", conn);
                cmd.Parameters.AddWithValue("@parkCode", survey.ParkCode);
                cmd.Parameters.AddWithValue("@emailAddress", survey.Email);
                cmd.Parameters.AddWithValue("@state", survey.StateOfResidence);
                cmd.Parameters.AddWithValue("@activityLevel", survey.UserActivityLevel);

                // Execute the command
                int rowsAffected = cmd.ExecuteNonQuery();
                result = rowsAffected == 1;
            }

            return(result);
        }
Пример #5
0
        public static HtmlString GetSurvey(this IHtmlHelper helper, SurveyViewModel model)
        {
            var html = SurveyBuilder.GetInstance(model).GetHTML();

            return(new HtmlString(html));
        }
        public async Task <IActionResult> UpdateSurvey([FromBody] SurveyViewModel data)
        {
            try
            {
                var surveyId = _surveySectionService.Update(data.survey).Result;

                if (data.survey.Pages.Count() > 0)
                {
                    List <BaseQuestionModel> questionList = new List <BaseQuestionModel>();
                    foreach (var page in data.survey.Pages)
                    {
                        if (page.State == ControlStates.Created.ToString())
                        {
                            Guid pageId = await _pageService.AddAsync(page, Guid.Parse(data.survey.Id));

                            questionList = _questionService.GetTypedQuestionList(page);
                            if (questionList.Count() > 0)
                            {
                                foreach (var question in questionList)
                                {
                                    _questionService.SaveQuestionByType(question, pageId);
                                }
                            }
                        }
                        else
                        {
                            Guid pageId = await _pageService.UpdateAsync(page, Guid.Parse(data.survey.Id));

                            questionList = _questionService.GetTypedQuestionList(page);
                            if (questionList.Count() > 0)
                            {
                                _questionService.Update(questionList, page.Id);
                            }
                        }
                    }

                    var deleteQuestionList = data.deleteQuestions.Distinct().ToList();
                    if (deleteQuestionList.Count > 0)
                    {
                        foreach (var item in deleteQuestionList)
                        {
                            var questionOptions = _questionOptionService.GetAllAsync().Result.Where(x => x.QuestionId == item);


                            if (questionOptions.Count() > 0)
                            {
                                foreach (var q_o in questionOptions)
                                {
                                    var answerList = _answerService.GetAllAsync().Result.Where(x => x.QuestionOptionId == q_o.Id);
                                    foreach (var answer in answerList)
                                    {
                                        await _answerService.Remove(answer);
                                    }
                                    await _questionOptionService.Remove(q_o);
                                }
                                ;
                            }
                            var childQuestions = await _questionService.GetListByBaseQuestion(item);

                            if (childQuestions.Count() > 0)
                            {
                                foreach (var childQuestion in childQuestions)
                                {
                                    var questionOptionList = _questionOptionService.GetAllAsync().Result.Where(x => x.QuestionId == childQuestion.Id);


                                    if (questionOptionList.Count() > 0)
                                    {
                                        foreach (var q_o in questionOptionList)
                                        {
                                            var answerList = _answerService.GetAllAsync().Result.Where(x => x.QuestionOptionId == q_o.Id);
                                            foreach (var answer in answerList)
                                            {
                                                await _answerService.Remove(answer);
                                            }
                                            await _questionOptionService.Remove(q_o);
                                        }
                                        ;
                                    }
                                    await _questionService.DeleteQuestionById(childQuestion.Id);
                                }
                            }
                            await _questionService.DeleteQuestionById(item);
                        }
                    }
                    var deletePageList = data.deletePages.Distinct().ToList();
                    if (deletePageList.Count > 0)
                    {
                        foreach (var pageId in deletePageList)
                        {
                            var questions = _questionService.GetListByPageId(pageId).Select(x => x.Id).ToList();
                            foreach (var question in questions)
                            {
                                var questionOptions = _questionOptionService.GetAllAsync().Result.Where(x => x.QuestionId == question);
                                if (questionOptions.Count() > 0)
                                {
                                    foreach (var q_o in questionOptions)
                                    {
                                        var answerList = _answerService.GetAllAsync().Result.Where(x => x.QuestionOptionId == q_o.Id);
                                        foreach (var answer in answerList)
                                        {
                                            await _answerService.Remove(answer);
                                        }
                                        await _questionOptionService.Remove(q_o);
                                    }
                                    ;
                                }
                                var childQuestions = await _questionService.GetListByBaseQuestion(question);

                                if (childQuestions.Count() > 0)
                                {
                                    foreach (var childQuestion in childQuestions)
                                    {
                                        await _questionService.DeleteQuestionById(childQuestion.Id);
                                    }
                                }
                                await _questionService.DeleteQuestionById(question);
                            }
                            _pageService.DeletePageById(pageId);
                        }
                    }
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                var check = ex;
                throw;
            }
        }
Пример #7
0
        public ActionResult SaveSurvey(ViewModels.Creating.SurveyViewModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                if (questions.Where(q => q.ParentContent == null).Count() > 1)
                {
                    this.TempData["error"] = "Please specify the next question for each answer from EDIT menu.";
                    return this.RedirectToAction("Create", model);
                }

                var newSurvey = new SurveyViewModel()
                {
                    IsPublic = model.IsPublic,
                    Title = model.Title,
                    AuthorId = this.CurrentUser.Id,
                    Questions = questions
                };

                var viewModel = this.Mapper.Map<Survey>(newSurvey);
                this.SurveyService.Add(viewModel);

                questions.Clear();
                return this.RedirectToAction("Index", "Surveys", new { area = "Surveys" });
            }

            return this.RedirectToAction("Create");
        }
Пример #8
0
        private SurveyCompletionParent InsertSurveyCompletion(SurveyViewModel model, bool partial)
        {
            var category = this.modelContext
                           .Categories
                           .Where(x => x.Id == model.CategoryId)
                           .FirstOrDefault();

            var role = this.roleManager.FindByName("DEMANDA");

            var surveyCompletionParent = new SurveyCompletionParent
            {
                Product        = null,
                Role           = role,
                Status         = "Aprobado",
                PartialSave    = partial,
                Category       = category,
                Email          = model.Email,
                PartialSaveKey = Guid.NewGuid().ToString()
            };

            foreach (var survey in model.SurveyDTOs)
            {
                var surveyCompletion = new SurveyCompletion
                {
                    SurveyId    = survey.SurveyId,
                    CategoryId  = survey.CategoryId,
                    Category    = survey.CategoryName,
                    Email       = model.Email,
                    Role        = role,
                    Parent      = surveyCompletionParent,
                    PartialSave = partial
                };

                var surveyQuestions = this.modelContext
                                      .Questions
                                      .Include("Answers")
                                      .Where(x => x.Survey.Id == survey.SurveyId)
                                      .ToList();

                foreach (var question in model.surveyCompletionDTOs)
                {
                    var answers = new List <SurveyCompletionAnswer>();
                    if (question.SurveyId == survey.SurveyId)
                    {
                        if (question.Answers != null)
                        {
                            answers = surveyQuestions
                                      .Where(x => x.Id == question.QuestionId)
                                      .FirstOrDefault()
                                      .Answers
                                      .Where(x => question.Answers.Contains(x.Id))
                                      .Select(x => new SurveyCompletionAnswer
                            {
                                Answer      = x.DemandAnswer,
                                AnswerValue = x.Value
                            })
                                      .ToList();
                        }

                        string          currentUserId = User.Identity.GetUserId();
                        ApplicationUser currentUser   = this.modelContext.Users.FirstOrDefault(x => x.Id == currentUserId);

                        var surveyCompletionQuestion = new SurveyCompletionQuestion
                        {
                            Question   = question.Question,
                            QuestionId = question.QuestionId,
                            Answers    = answers
                        };

                        surveyCompletion.Questions.Add(surveyCompletionQuestion);
                    }
                }

                this.modelContext.SurveysCompletion.Add(surveyCompletion);
            }

            this.modelContext.SurveyCompletionParent.Add(surveyCompletionParent);
            this.modelContext.SaveChanges();

            return(surveyCompletionParent);
        }
 private async Task <HttpResponseMessage> PostSurvey(SurveyViewModel survey)
 {
     return(await PostAsJson(PostEndPoint, survey));
 }
Пример #10
0
 public Page5()
 {
     this.DataContext = this.NavigationService.GetData();
     model            = this.DataContext as SurveyViewModel;
     InitializeComponent();
 }
Пример #11
0
        public IActionResult Vote(int?vote, int idSurvey)
        {
            ViewBag.NbreVisitUnique = GetVisitIP();
            ViewBag.NbrePagesVues   = GetPageVues();
            UserConnect(ViewBag);
            ConsentCookie(ViewBag);


            List <string> errors = new List <string>();

            if (vote == null)
            {
                errors.Add("Vous devez cocher une case pour voter!");
                ViewBag.errors = errors;
                Survey survey = new Survey {
                    Id = idSurvey
                };
                survey = survey.GetSurvey();

                Membres membre = new Membres(); //Récupérer le membre auteur du sondage
                membre = membre.GetMembreById(survey.IdCreateur);
                SurveyViewModel viewModel = new SurveyViewModel {
                    Survey = survey, Membre = membre
                };

                return(View("ViewSurvey", viewModel));
            }

            if (ViewBag.Logged)
            {
                AnswerByMembre answer = new AnswerByMembre {
                    IdMembre = Convert.ToInt32(ViewBag.Id), IdSurvey = idSurvey, IdAnswer = (int)vote
                };
                answer.SaveVoteMembre();
            }
            else
            {
                Visiteur   v = new Visiteur();
                string     remoteIpAddress = Convert.ToString(Request.HttpContext.Connection.RemoteIpAddress);
                AnswerByIp answer          = new AnswerByIp {
                    IdIp = v.GetIdIp(remoteIpAddress), IdAnswer = (int)vote, IdSurvey = idSurvey
                };
                answer.SaveVoteIdIp();

                CookieOptions option = new CookieOptions
                {
                    Expires  = DateTime.Now.AddDays(365),
                    HttpOnly = true
                };

                Response.Cookies.Append("Survey" + idSurvey, Convert.ToString(vote), option);
            }

            Survey s = new Survey {
                Id = idSurvey
            };

            s = s.GetSurvey();

            Membres m = new Membres(); //Récupérer le membre auteur du sondage

            m = m.GetMembreById(s.IdCreateur);
            List <Survey>         surveys = s.GetAllSurveys(true);
            SurveyResultViewModel result  = new SurveyResultViewModel {
                Survey = s, Surveys = surveys, Membre = m
            };

            return(View("ResultSurvey", result));
        }
Пример #12
0
        public ActionResult <SurveyViewModel> Surveys()
        {
            SurveyViewModel result = mainManager.GetSurveys();

            return(result);
        }
Пример #13
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));
        }
Пример #14
0
        public IActionResult Index()
        {
            SurveyViewModel vm    = new SurveyViewModel();
            IList <Park>    Parks = parkDAO.GetParks();

            vm.ParkList = new SelectList(Parks, "ParkCode", "ParkName");

            var State = new List <SelectListItem> {
                new SelectListItem {
                    Text = "Alabama"
                },
                new SelectListItem {
                    Text = "Alaska"
                },
                new SelectListItem {
                    Text = "Arizona"
                },
                new SelectListItem {
                    Text = "Arkansas"
                },
                new SelectListItem {
                    Text = "California"
                },
                new SelectListItem {
                    Text = "Colorado"
                },
                new SelectListItem {
                    Text = "Connecticut"
                },
                new SelectListItem {
                    Text = "Delaware"
                },
                new SelectListItem {
                    Text = "Florida"
                },
                new SelectListItem {
                    Text = "Georgia"
                },
                new SelectListItem {
                    Text = "Hawaii"
                },
                new SelectListItem {
                    Text = "Idaho"
                },
                new SelectListItem {
                    Text = "Illinois"
                },
                new SelectListItem {
                    Text = "Indiana"
                },
                new SelectListItem {
                    Text = "Iowa"
                },
                new SelectListItem {
                    Text = "Kansas"
                },
                new SelectListItem {
                    Text = "Kentucky"
                },
                new SelectListItem {
                    Text = "Louisiana"
                },
                new SelectListItem {
                    Text = "Maine"
                },
                new SelectListItem {
                    Text = "Maryland"
                },
                new SelectListItem {
                    Text = "Massachusetts"
                },
                new SelectListItem {
                    Text = "Michigan"
                },
                new SelectListItem {
                    Text = "Minnesota"
                },
                new SelectListItem {
                    Text = "Mississippi"
                },
                new SelectListItem {
                    Text = "Missouri"
                },
                new SelectListItem {
                    Text = "Montana"
                },
                new SelectListItem {
                    Text = "North Carolina"
                },
                new SelectListItem {
                    Text = "North Dakota"
                },
                new SelectListItem {
                    Text = "Nebraska"
                },
                new SelectListItem {
                    Text = "Nevada"
                },
                new SelectListItem {
                    Text = "New Hampshire"
                },
                new SelectListItem {
                    Text = "New Jersey"
                },
                new SelectListItem {
                    Text = "New Mexico"
                },
                new SelectListItem {
                    Text = "New York"
                },
                new SelectListItem {
                    Text = "Ohio"
                },
                new SelectListItem {
                    Text = "Oklahoma"
                },
                new SelectListItem {
                    Text = "Oregon"
                },
                new SelectListItem {
                    Text = "Pennsylvania"
                },
                new SelectListItem {
                    Text = "Rhode Island"
                },
                new SelectListItem {
                    Text = "South Carolina"
                },
                new SelectListItem {
                    Text = "South Dakota"
                },
                new SelectListItem {
                    Text = "Tennessee"
                },
                new SelectListItem {
                    Text = "Texas"
                },
                new SelectListItem {
                    Text = "Utah"
                },
                new SelectListItem {
                    Text = "Vermont"
                },
                new SelectListItem {
                    Text = "Virginia"
                },
                new SelectListItem {
                    Text = "Washington"
                },
                new SelectListItem {
                    Text = "West Virginia"
                },
                new SelectListItem {
                    Text = "Wisconsin"
                },
                new SelectListItem {
                    Text = "Wyoming"
                }
            };

            vm.StateList = new SelectList(State, "Text", "Text");

            return(View(vm));
        }
Пример #15
0
        public ActionResult RegisterContinuePartial(App.Models.Oferta.RegisterViewModel model, string Argument)
        {
            this.ValidateRegistration(model, true);

            if (!ModelState.IsValid)
            {
                ViewBag.Argument = Argument;
                return(View("~/Views/Oferta/Register.cshtml", model));
            }

            var surveyCompletionTmp = this.RegisterViewModelCompanyMap(model);

            this.modelContext.Companies.Add(surveyCompletionTmp.Company);
            this.modelContext.Products.Add(surveyCompletionTmp.Product);
            this.modelContext.Contacts.Add(surveyCompletionTmp.Company.ComercialContact);
            this.modelContext.Contacts.Add(surveyCompletionTmp.Product.ProductContact);
            this.modelContext.SaveChanges();

            if (model.CompanyLogo != null)
            {
                surveyCompletionTmp.Company.CompanyLogo = surveyCompletionTmp.Company.Id + "_" + model.CompanyLogo.FileName;
            }

            this.modelContext.SaveChanges();

            if (model.CompanyLogo != null)
            {
                var fileName = Path.GetFileName(surveyCompletionTmp.Company.CompanyLogo);
                var path     = Path.Combine(Server.MapPath("~/Content/images/logos"), fileName);
                model.CompanyLogo.SaveAs(path);
            }
            else
            {
                if (model.SurveyCompletionId != 0)
                {
                    var surveyCompletionPartialCompany = this.modelContext
                                                         .SurveysCompletion
                                                         .Include("Company")
                                                         .FirstOrDefault(x => x.Id == model.SurveyCompletionId)
                                                         .Company;

                    surveyCompletionTmp.Company.CompanyLogo = surveyCompletionPartialCompany.CompanyLogo;

                    this.modelContext.SaveChanges();
                }
            }

            var surveyViewModel = new SurveyViewModel
            {
                CompanyId          = surveyCompletionTmp.Company.Id,
                SurveyId           = model.CategoryId,
                SurveyCompletionId = model.SurveyCompletionId,
                CategoryId         = model.CategoryId
            };

            var surveyCompletionPartial = this.modelContext
                                          .SurveysCompletion
                                          .Include("Questions")
                                          .Include("Questions.Answers")
                                          .FirstOrDefault(x => x.Id == model.SurveyCompletionId);

            var surveyCompletionParent = this.InsertSurveyCompletion(surveyViewModel, true);

            //surveyCompletionParent.Questions = surveyCompletionPartial.Questions;

            /*this.modelContext.SaveChanges();
             *
             * var template = this.RenderRazorViewToString("~/Views/Demanda/Email/EvaluationTemplate.cshtml", surveyCompletion);
             * var pdfFileName = this.pdfService.GetEvaluationFileName(surveyCompletion.Id);
             * var pdfFullName = this.pdfService.Generate(surveyCompletion.Id, template, pdfFileName);
             *
             * this.surveyPartialCompletionBySupplyEmailService.Send(pdfFullName, surveyCompletion);*/

            return(RedirectToAction("ThanksPartial", "../Product/Evaluation"));
        }
Пример #16
0
        public async Task <IActionResult> Survey(SurveyViewModel model)
        {
            System.Diagnostics.Debug.WriteLine("Buyer: " + model.buyer);
            System.Diagnostics.Debug.WriteLine("Canceled: " + model.canceled);
            if (model.buyer)
            {
                byte[]   data    = Convert.FromBase64String(model.token);
                DateTime when    = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
                var      logid   = BitConverter.ToInt32(data, 8);
                var      log     = _context.TransactionLogs.Where(a => a.ID == logid).FirstOrDefault();
                var      listing = _context.BookListings.Where(a => a.ID == model.listingId).FirstOrDefault();
                if (model.canceled)
                {
                    // Restore old listing and remove pending transaction
                    listing.Status = 0;
                    _context.TransactionLogs.Remove(log);
                    await _context.SaveChangesAsync();
                }
                else
                {
                    // If the condition or the price is different, discard this transaction and book listing.
                    _context.BookListings.Remove(listing);
                    if (log.Condition != model.condition || log.SoldPrice != model.finalPrice)
                    {
                        _context.TransactionLogs.Remove(log);
                        await _context.SaveChangesAsync();
                    }
                    else
                    {
                        // Otherwise remove the pending book listing, close the transaction, and update seller's rating.
                        log.Status      = 0;
                        log.TransRating = model.rating;
                        log.Comments    = model.comments;
                        var seller = await _userManager.FindByIdAsync(log.SellerID);

                        var sellerLogs = _context.TransactionLogs.Where(a => a.SellerID == log.SellerID && a.Status == 0).ToList();
                        var newRating  = model.rating;
                        foreach (TransactionLog tl in sellerLogs)
                        {
                            newRating += tl.TransRating;
                        }
                        seller.Rating = newRating / (sellerLogs.Count + 1);
                        await _context.SaveChangesAsync();
                    }
                }
                return(View("Complete"));
            }
            else
            {
                var listing = _context.BookListings.Where(a => a.ID == model.listingId).FirstOrDefault();
                listing.CourseID    = model.courseID;
                listing.Condition   = model.condition;
                listing.AskingPrice = model.finalPrice;
                listing.Status      = 1;
                var log = _context.TransactionLogs.Where(a => a.SellerID == listing.ApplicationUserID && a.BuyerID == model.buyerId && a.BookID == listing.BookID && a.Status == 1).FirstOrDefault();
                log.Condition = model.condition;
                log.SoldPrice = model.finalPrice;
                await _context.SaveChangesAsync();

                // Send email to buyer and notify them of the sell with link to fill out the survey
                var seller = await _userManager.FindByIdAsync(listing.ApplicationUserID);

                var buyer = await _userManager.FindByIdAsync(model.buyerId);

                var book = _context.Books.Where(a => a.ID == listing.BookID).FirstOrDefault();
                System.Diagnostics.Debug.WriteLine("LogId: " + log.ID);

                byte[] time        = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
                byte[] logid       = BitConverter.GetBytes(log.ID);
                byte[] key         = Guid.NewGuid().ToByteArray();
                string token       = Convert.ToBase64String(time.Concat(logid).Concat(key).ToArray());
                var    callbackUrl = Url.Action("Survey", "Transaction", new { id = listing.ID, token = token, buyerId = buyer.Id }, protocol: HttpContext.Request.Scheme);
                await _emailSender.SendEmailAsync(buyer.Email, "NYBE Complete Purchase",
                                                  $"<b>{seller.FirstName} {seller.LastName}</b> has marked you as the purchaser of <b>{book.Title}</b>. Please fill out our <a href='{callbackUrl}'>survey</a> to confirm your purchase and leave a rating.  If you have not purchased this book, you can say so in the survey.  You should hurry!  The survey expires in 48 hours from receiving this email!");

                return(RedirectToAction(nameof(ProfileController.Index), "Profile"));
            }
        }
Пример #17
0
        public IActionResult GetSurveyUserFeedback(string surveyUserGuid)
        {
            SurveyUserFeedbackViewModel surveyUserFeedbackViewModel = new SurveyUserFeedbackViewModel();

            _memoryCache.TryGetValue($"survey_feedback_{surveyUserGuid}", out surveyUserFeedbackViewModel);
            if (surveyUserFeedbackViewModel != null)
            {
                return(Ok(surveyUserFeedbackViewModel));
            }

            SurveyViewModel surview = new SurveyViewModel();
            string          userId  = Request.Headers[Constants.UserToken];
            User            user;

            _memoryCache.TryGetValue(userId, out user);
            if (user == null)
            {
                return(Unauthorized(Messages.UserNotFoundError));
            }

            SurveyFeedback surveyFeedback = _dBContext.SurveyFeedback.Where(x => x.SurveyUserGuid == surveyUserGuid).FirstOrDefault();

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

            Survey survey = _dBContext.Survey.Where(x => x.CreatedBy == user.Userid && x.Surveyid == surveyFeedback.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 <SurveyFeedbackQuestionOptions> surveyFeedbackquestionoptions = new List <SurveyFeedbackQuestionOptions>();
                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();
                surveyFeedbackquestionoptions = _dBContext.SurveyFeedbackQuestionOptions.Where(x => x.SurveyQuestionId == item.SurveyQuestionId && x.SurveyFeedbackId == surveyFeedback.SurveyFeedbackId).ToList();
                if (questiontypes != null)
                {
                    optiontypevalue = questiontypes.FirstOrDefault(x => x.TypeId == item.TypeId).TypeValue;
                }
                if (surveyFeedbackquestionoptions != null)
                {
                    foreach (var itemq in surveyFeedbackquestionoptions)
                    {
                        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;

            surveyUserFeedbackViewModel = _mapper.Map <SurveyUserFeedbackViewModel>(surview);
            surveyUserFeedbackViewModel.SurveyFeedbacks = new List <SurveyFeedback>()
            {
                surveyFeedback
            };

            _memoryCache.Set($"survey_feedback_{surveyUserGuid}", surveyUserFeedbackViewModel);
            return(Ok(surveyUserFeedbackViewModel));
        }
Пример #18
0
        public ActionResult Surveys(SurveyViewModel model)
        {
            if (ModelState.IsValid)
            {
                //    string[] title = Request.Form.GetValues("Title");
                var      ti              = Request.QueryString["Title"];
                string[] listQuestion    = Request.Form.GetValues("question");
                string[] listAnwser      = Request.Form.GetValues("anwser1");
                string[] listCountAnwser = Request.Form.GetValues("count");

                string[] imagUrl  = Request.Form.GetValues("image_from_list");
                string[] member   = Request.Form.GetValues("people");
                string[] privacy  = Request.Form.GetValues("privacy");
                string[] priority = Request.Form.GetValues("priority");
                // string[] listMem = Request.Form.GetValues("count");
                //  string[] listCountAnwser = {"1", "2", "3","1","2","1","2","3","4"};
                List <string> listCountAnwsers = new List <string>(listCountAnwser);
                List <string> listQuestions    = new List <string>(listQuestion);
                List <string> listAnwsers      = new List <string>(listAnwser);

                // count number anwser of question
                List <int>            listCount        = new List <int>();
                List <List <string> > totalAnsertGroup = new List <List <string> >();
                for (int i = 0; i < (listCountAnwsers.Count) - 1; i++)
                {
                    if (Int32.Parse(listCountAnwsers[i]) > Int32.Parse(listCountAnwsers[i + 1]))
                    {
                        listCount.Add(Int32.Parse(listCountAnwsers[i]));
                    }
                }
                listCount.Add(Int32.Parse((listCountAnwsers[(listCountAnwsers.Count) - 1])));
                for (int i = 0; i < listCount.Count; i++)
                {
                    List <string> listAnwserGroup = new List <string>();
                    int           countAneser     = 0;
                    for (int j = 0; j < listAnwsers.Count; j++)
                    {
                        if (countAneser != listCount[i] && countAneser < listCount[i])
                        {
                            listAnwserGroup.Add(listAnwsers[j]);
                            countAneser++;
                            listAnwsers.Remove(listAnwsers[j]);
                            j = j - 1;
                        }
                    }
                    totalAnsertGroup.Add(listAnwserGroup);
                }
                Poll survey = new Poll();

                int number = totalAnsertGroup.Count;
                int ii     = 0;
                foreach (var content in listQuestions)
                {
                    if (ii < number)
                    {
                        survey.Description = model.Title;

                        //survey.CreateDate = (DateTime.Now);

                        survey.EndDate     = (model.EndDate);
                        survey.PublishDate = (model.PublishDate);
                        // int result = DateTime.Compare(survey.CreateDate.Value, survey.EndDate.Value);
                        int result1 = DateTime.Compare(survey.PublishDate.Value, survey.EndDate.Value);
                        //int result2 = DateTime.Compare(survey.CreateDate.Value, survey.PublishDate.Value);
                        //if (survey.CreateDate.ToString() == "")
                        //{
                        //    ModelState.AddModelError("StartDate", "Xin chon ngay hop ly.");
                        //}
                        //if ((result) < 0)
                        //{
                        //    ModelState.AddModelError("StartDate", "Xin chon ngay hop ly.");
                        //}
                        //else if ((result1) < 0)
                        //{
                        //    ModelState.AddModelError("StartDate", "Xin chon ngay hop ly.");
                        //}
                        //else if ((result2) < 0)
                        //{
                        //    ModelState.AddModelError("EndDate", "Xin chon ngay hop ly.");
                        //}
                        survey.Status = 1;

                        //   survey.Privacy = int.Parse(privacy[0]);
                        survey.Mode     = int.Parse(member[0]);
                        survey.Priority = int.Parse(priority[0]);
                        survey.ImageUrl = imagUrl[0];
                        survey.Question = content;
                        survey.Answer1  = listAnwser[0];
                        survey.Answer2  = listAnwser[1];
                        survey.Answer3  = listAnwser[2];
                        survey.Answer4  = listAnwser[3];
                        if (listAnwser.Length == 5)
                        {
                            survey.Answer5 = listAnwser[(listAnwser.Length) - 1];
                        }


                        PollService.AddPoll(survey);
                    }
                }
                int k = 0;
                // BlockPoll BlockPoll = new BlockPoll();

                string[] listBlock = Request.Form.GetValues("block");

                if (listBlock != null)
                {
                    List <string> listBlockrs = new List <string>(listBlock);
                    List <Block>  list        = new List <Block>();
                    foreach (var item in listBlockrs)
                    {
                        list.Add(blockService.FindBlockByName(item));
                    }
                    foreach (var obj in list)
                    {
                        BlockPoll BlockPoll = new BlockPoll();
                        BlockPoll.BlockId = obj.Id;
                        BlockPoll.PollId  = survey.Id;
                        BlockPollService.AddBlockPoll(BlockPoll);
                    }
                    int p = 0;
                    // List<User> listuUsers = userService.GetAllResident();
                    List <User> listAllUsers = userService.GetAllUsers();
                    User        curUser      = userService.FindById(int.Parse(User.Identity.GetUserId()));
                    foreach (var u in listAllUsers)
                    {
                        if (u.HouseId != null)
                        {
                            int kk = 0;
                            if (list.ElementAt(p).Id == BlockPollService.FindBlockIdByHouseId(u.HouseId.Value).BlockId&&
                                p < list.Count)
                            {
                                kk++;
                            }
                            if (kk == 1)
                            {
                                Console.WriteLine(u);
                                //notificationService.addNotification("", u.Id, SLIM_CONFIG.NOTIC_VERB_POLL, 2, null);
                                notificationService.addNotification(SLIM_CONFIG.NOTIC_TARGET_OBJECT_POLL, u.Id,
                                                                    SLIM_CONFIG.NOTIC_VERB_CREATE, curUser.Id, null);
                            }
                        }
                        else if (survey.Mode == 1)
                        {
                            int kk = 0;

                            if (u.HouseId.HasValue)
                            {
                                if (list.ElementAt(p).Id ==
                                    BlockPollService.FindBlockIdByHouseId(u.HouseId.Value).BlockId&& p < list.Count)
                                {
                                    kk++;
                                }
                            }
                            if (kk == 1 || kk == 0)
                            {
                                Console.WriteLine(u);
                                //notificationService.addNotification("", u.Id, SLIM_CONFIG.NOTIC_VERB_POLL, 2, null);
                                notificationService.addNotification(SLIM_CONFIG.NOTIC_TARGET_OBJECT_POLL, u.Id,
                                                                    SLIM_CONFIG.NOTIC_VERB_CREATE, curUser.Id, null);
                            }
                        }
                        else if (survey.Mode == 2 && SLIM_CONFIG.USER_ROLE_HOUSEHOLDER == u.RoleId)
                        {
                            int kk = 0;

                            if (u.HouseId.HasValue)
                            {
                                if (list.ElementAt(p).Id ==
                                    BlockPollService.FindBlockIdByHouseId(u.HouseId.Value).BlockId&& p < list.Count)
                                {
                                    kk++;
                                }
                            }
                            if (kk == 1 || kk == 0)
                            {
                                Console.WriteLine(u);
                                //notificationService.addNotification("", u.Id, SLIM_CONFIG.NOTIC_VERB_POLL, 2, null);
                                notificationService.addNotification(SLIM_CONFIG.NOTIC_TARGET_OBJECT_POLL, u.Id,
                                                                    SLIM_CONFIG.NOTIC_VERB_CREATE, curUser.Id, null);
                            }
                        }
                        else if ((survey.Mode == 3 && SLIM_CONFIG.USER_ROLE_HOUSEHOLDER == u.RoleId) ||
                                 (survey.Mode == 3 && SLIM_CONFIG.USER_ROLE_RESIDENT == u.RoleId))
                        {
                            int kk = 0;

                            if (u.HouseId.HasValue)
                            {
                                if (list.ElementAt(p).Id ==
                                    BlockPollService.FindBlockIdByHouseId(u.HouseId.Value).BlockId&& p < list.Count)
                                {
                                    kk++;
                                }
                            }
                            if (kk == 1 || kk == 0)
                            {
                                Console.WriteLine(u);
                                //notificationService.addNotification("", u.Id, SLIM_CONFIG.NOTIC_VERB_POLL, 2, null);
                                notificationService.addNotification(SLIM_CONFIG.NOTIC_TARGET_OBJECT_POLL, u.Id,
                                                                    SLIM_CONFIG.NOTIC_VERB_CREATE, curUser.Id, null);
                            }
                        }
                    }
                }
                else
                {
                    // List<User> listuUsers = userService.GetAllResident();
                    List <User> listAllUsers = userService.GetAllUsers();
                    User        curUser      = userService.FindById(int.Parse(User.Identity.GetUserId()));
                    foreach (var u in listAllUsers)
                    {
                        if (survey.Mode == 1)
                        {
                            Console.WriteLine(u);
                            //notificationService.addNotification("", u.Id, SLIM_CONFIG.NOTIC_VERB_POLL, 2, null);
                            notificationService.addNotification(SLIM_CONFIG.NOTIC_TARGET_OBJECT_POLL, u.Id, SLIM_CONFIG.NOTIC_VERB_CREATE, curUser.Id, null);
                        }
                        else if (survey.Mode == 2 && SLIM_CONFIG.USER_ROLE_HOUSEHOLDER == u.RoleId)
                        {
                            notificationService.addNotification(SLIM_CONFIG.NOTIC_TARGET_OBJECT_POLL, u.Id, SLIM_CONFIG.NOTIC_VERB_CREATE, curUser.Id, null);
                        }
                        else if ((survey.Mode == 3 && SLIM_CONFIG.USER_ROLE_HOUSEHOLDER == u.RoleId) ||
                                 (survey.Mode == 3 && SLIM_CONFIG.USER_ROLE_RESIDENT == u.RoleId))
                        {
                            notificationService.addNotification(SLIM_CONFIG.NOTIC_TARGET_OBJECT_POLL, u.Id, SLIM_CONFIG.NOTIC_VERB_CREATE, curUser.Id, null);
                        }
                    }
                }
            }
            ViewBag.Alert = "Tạo survey thành công!!";
            //  return View("Survey");
            return(RedirectToAction("ListPoll", new { alerts = "Tạo survey thành công!!" }));
        }
Пример #19
0
        public ActionResult UpdateSurvey(SurveyViewModel model)
        {
            string[]      listQuestion     = Request.Form.GetValues("question");
            string[]      listAnwser       = Request.Form.GetValues("anwser1");
            string[]      listCountAnwser  = Request.Form.GetValues("count");
            List <string> listCountAnwsers = new List <string>(listCountAnwser);
            List <string> listQuestions    = new List <string>(listQuestion);
            List <string> listAnwsers      = new List <string>(listAnwser);

            string[]   member    = Request.Form.GetValues("people");
            string[]   privacy   = Request.Form.GetValues("privacy");
            string[]   priority  = Request.Form.GetValues("priority");
            string[]   status    = Request.Form.GetValues("status");
            List <int> listCount = new List <int>();

            List <List <string> > totalAnsertGroup = new List <List <string> >();

            for (int i = 0; i < (listCountAnwsers.Count) - 1; i++)
            {
                if (Int32.Parse(listCountAnwsers[i]) > Int32.Parse(listCountAnwsers[i + 1]))
                {
                    listCount.Add(Int32.Parse(listCountAnwsers[i]));
                }
            }
            listCount.Add(Int32.Parse((listCountAnwsers[(listCountAnwsers.Count) - 1])));
            for (int i = 0; i < listCount.Count; i++)
            {
                List <string> listAnwserGroup = new List <string>();
                int           countAneser     = 0;
                for (int j = 0; j < listAnwsers.Count; j++)
                {
                    if (countAneser != listCount[i] && countAneser < listCount[i])
                    {
                        listAnwserGroup.Add(listAnwsers[j]);
                        countAneser++;
                        listAnwsers.Remove(listAnwsers[j]);
                        j = j - 1;
                    }
                }
                totalAnsertGroup.Add(listAnwserGroup);
            }
            //
            int  a   = 0;
            Poll obj = PollService.FindById(model.Id);

            if (listAnwser.Length == 2)
            {
                obj.Answer1 = listAnwser[0];
                obj.Answer2 = listAnwser[1];
            }
            else if (listAnwser.Length == 3)
            {
                obj.Answer1 = listAnwser[0];
                obj.Answer2 = listAnwser[1];
                obj.Answer3 = listAnwser[2];
            }
            else if (listAnwser.Length == 4)
            {
                obj.Answer1 = listAnwser[0];
                obj.Answer2 = listAnwser[1];
                obj.Answer3 = listAnwser[2];
                obj.Answer4 = listAnwser[3];
            }
            else if (listAnwser.Length == 5)
            {
                obj.Answer1 = listAnwser[0];
                obj.Answer2 = listAnwser[1];
                obj.Answer3 = listAnwser[2];
                obj.Answer4 = listAnwser[3];
                if (listAnwser.Length == 5)
                {
                    obj.Answer5 = listAnwser[(listAnwser.Length) - 1];
                }
            }



            obj.Description = model.Title;
            obj.Question    = listQuestion[0];

            obj.EndDate     = (model.EndDate);
            obj.PublishDate = (model.PublishDate);
            obj.Status      = int.Parse(status[0]);
            obj.Mode        = int.Parse(member[0]);

            obj.Priority = int.Parse(priority[0]);
            PollService.UpdatePoll(obj);
            string[] listBlock = Request.Form.GetValues("block");
            if (listBlock != null)
            {
                List <string> listBlockrs = new List <string>(listBlock);

                List <BlockPoll> listBlockPollsDb = BlockPollService.FindByPollId(model.Id);

                List <int> listEditBlock = new List <int>();
                List <int> listLoad      = new List <int>();

                foreach (var VARIABLE in listBlockrs)
                {
                    listEditBlock.Add(blockService.FindBlockByName(VARIABLE).Id);
                }
                foreach (var aa in listBlockPollsDb)
                {
                    listLoad.Add(aa.BlockId);
                }
                if (listEditBlock.Count < listLoad.Count)
                {
                    List <int> list3 = listLoad.Except(listEditBlock).ToList();
                    // number of check less than before, delete
                    List <int> list5 = listEditBlock.Intersect(listLoad).ToList();
                    if (list5.Count == 0)
                    {
                        // uncheck A, check B
                        foreach (var object1 in listLoad)
                        {
                            BlockPoll BlockPoll = BlockPollService.FIndBlockPollByBlockIdPollId(object1, model.Id);
                            BlockPollService.DeleteBlockPoll(BlockPoll);
                        }
                        foreach (var obj1 in listEditBlock)
                        {
                            BlockPoll blockPoll = new BlockPoll();
                            blockPoll.BlockId = obj1;
                            blockPoll.PollId  = model.Id;
                            BlockPollService.AddBlockPoll(blockPoll);
                        }
                    }
                    else if (list5.Count != 0)
                    {
                        foreach (var object1 in list3)
                        {
                            BlockPoll BlockPoll = BlockPollService.FIndBlockPollByBlockIdPollId(object1, model.Id);
                            BlockPollService.DeleteBlockPoll(BlockPoll);
                        }
                    }
                }
                else if (listEditBlock.Count >= listLoad.Count)
                {
                    List <int> list4 = listEditBlock.Except(listLoad).ToList();
                    // number of check more than before,
                    List <int> list5 = listEditBlock.Intersect(listLoad).ToList();
                    if (list5.Count == 0)
                    {
                        // uncheck A, check B
                        foreach (var object1 in listLoad)
                        {
                            BlockPoll BlockPoll = BlockPollService.FIndBlockPollByBlockIdPollId(object1, model.Id);
                            BlockPollService.DeleteBlockPoll(BlockPoll);
                        }
                        foreach (var obj1 in listEditBlock)
                        {
                            BlockPoll blockPoll = new BlockPoll();
                            blockPoll.BlockId = obj1;
                            blockPoll.PollId  = model.Id;
                            BlockPollService.AddBlockPoll(blockPoll);
                        }
                    }
                    else if (list5.Count != 0)
                    {
                        foreach (var obj1 in list4)
                        {
                            BlockPoll blockPoll = new BlockPoll();
                            blockPoll.BlockId = obj1;
                            blockPoll.PollId  = model.Id;
                            BlockPollService.AddBlockPoll(blockPoll);
                        }
                    }
                }
            }
            else
            {
                List <BlockPoll> listBlockPollsDb = BlockPollService.FindByPollId(model.Id);


                List <int> listLoad = new List <int>();


                foreach (var aa in listBlockPollsDb)
                {
                    listLoad.Add(aa.BlockId);
                }

                List <int> list3 = listLoad.ToList();
                // number of check less than before, delete
                foreach (var object1 in list3)
                {
                    BlockPoll BlockPoll = BlockPollService.FIndBlockPollByBlockIdPollId(object1, model.Id);
                    BlockPollService.DeleteBlockPoll(BlockPoll);
                }
            }

            List <int> aaa = new List <int>();

            aaa.Add(1);
            aaa.Add(2);
            List <int> aaa1 = new List <int>();

            aaa1.Add(2);
            aaa1.Add(3);
            aaa1.Add(4);
            List <int> asd = aaa1.Except(aaa).ToList();

            return(RedirectToAction("DetailSurvey", new { PollId = obj.Id, alert = "Cập nhật thành công!" }));
        }
Пример #20
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));
        }
Пример #21
0
        private SurveyCompletionParent InsertSurveyCompletion(SurveyViewModel model, bool partial = false)
        {
            this.RemovePartialSurveyCompletion(model);

            var category = this.modelContext
                           .Categories
                           .Where(x => x.Id == model.CategoryId)
                           .FirstOrDefault();

            var userId = User.Identity.GetUserId();
            var role   = this.roleManager.FindByName("OFERTA");

            var user = this.modelContext
                       .Users
                       .FirstOrDefault(x => x.Id == userId);

            var company = this.modelContext
                          .Companies
                          .Include("ComercialContact")
                          .FirstOrDefault(x => x.Id == model.CompanyId);
            //aca  crear el pridcuto con el contactro del producto
            var producto = new Product
            {
                Name           = model.ProductName,
                Description    = model.ProductDescription,
                WebSite        = model.ProductWebSite,
                Version        = model.ProductVersion,
                User           = user,
                ProductContact = new Contact
                {
                    FullName = model.ProductContactFullName,
                    Position = model.ProductContactPosition,
                    Phone    = model.ProductContactPhone,
                    Email    = model.ProductContactEmail
                }
            };

            producto.Company = company;
            modelContext.Products.Add(producto);
            modelContext.SaveChanges();

            var surveyCompletionParent = new SurveyCompletionParent(company)
            {
                Product     = producto,
                Role        = role,
                Status      = "Pendiente",
                PartialSave = partial,
                Category    = category
            };

            foreach (var surveyDTO in model.SurveyDTOs)
            {
                var categoryObj = this.modelContext
                                  .Categories
                                  .Where(x => x.Id == surveyDTO.CategoryId)
                                  .FirstOrDefault();

                var surveyCompletion = new SurveyCompletion(company)
                {
                    SurveyId    = surveyDTO.SurveyId,
                    CategoryId  = surveyDTO.CategoryId,
                    Product     = producto,
                    Category    = surveyDTO.CategoryName,
                    CategoryObj = categoryObj,
                    Role        = role,
                    PartialSave = partial,
                    Parent      = surveyCompletionParent
                };

                var surveyQuestions = this.modelContext
                                      .Questions
                                      .Include("Answers")
                                      .Where(x => x.Survey.Id == surveyDTO.SurveyId)
                                      .ToList();

                foreach (var question in model.surveyCompletionDTOs)
                {
                    var answers = new List <SurveyCompletionAnswer>();

                    if (question.SurveyId == surveyDTO.SurveyId)
                    {
                        if (question.Answers != null)
                        {
                            answers = surveyQuestions
                                      .Where(x => x.Id == question.QuestionId)
                                      .FirstOrDefault()
                                      .Answers
                                      .Where(x => question.Answers.Contains(x.Id))
                                      .Select(x => new SurveyCompletionAnswer
                            {
                                Answer      = x.SupplyAnswer,
                                AnswerValue = x.Value
                            })
                                      .ToList();
                        }

                        string          currentUserId = User.Identity.GetUserId();
                        ApplicationUser currentUser   = this.modelContext.Users.FirstOrDefault(x => x.Id == currentUserId);

                        var surveyCompletionQuestion = new SurveyCompletionQuestion
                        {
                            Question   = question.Question,
                            QuestionId = question.QuestionId,
                            Answers    = answers
                        };

                        surveyCompletion.Questions.Add(surveyCompletionQuestion);
                    }
                }

                this.modelContext.SurveysCompletion.Add(surveyCompletion);
            }
            this.modelContext.SurveyCompletionParent.Add(surveyCompletionParent);
            this.modelContext.SaveChanges();

            return(surveyCompletionParent);
        }
Пример #22
0
        public IActionResult DisplaySurvey(int id)
        {
            ViewBag.NbreVisitUnique = GetVisitIP();
            ViewBag.NbrePagesVues   = GetPageVues();
            UserConnect(ViewBag);
            ConsentCookie(ViewBag);


            Survey s = new Survey {
                Id = id
            };

            s = s.GetSurvey();

            Membres m = new Membres(); //Récupérer le membre auteur du sondage

            m = m.GetMembreById(s.IdCreateur);

            SurveyViewModel viewModel = new SurveyViewModel {
                Survey = s, Membre = m
            };


            bool DejaVote; // Vérifier si déjà voté

            if (ViewBag.Logged)
            {
                AnswerByMembre answer   = new AnswerByMembre();
                int            IdMembre = Convert.ToInt32(ViewBag.Id);
                DejaVote = answer.VerifVoteMembre(IdMembre, id);
            }
            else
            {
                Visiteur   v = new Visiteur();
                string     remoteIpAddress = Convert.ToString(Request.HttpContext.Connection.RemoteIpAddress);
                AnswerByIp answer          = new AnswerByIp();

                bool VerifByIp = answer.VerifVoteIp(v.GetIdIp(remoteIpAddress), id);
                bool VerifByCookie;

                if (Request.Cookies["Survey" + id] == null)
                {
                    VerifByCookie = false;
                }
                else
                {
                    VerifByCookie = true;
                }

                if (VerifByIp && VerifByCookie)
                {
                    DejaVote = true;
                }
                else
                {
                    DejaVote = false;
                }
            }

            if (DejaVote)
            {
                List <Survey>         surveys = s.GetAllSurveys(true);
                SurveyResultViewModel result  = new SurveyResultViewModel {
                    Survey = s, Surveys = surveys, Membre = m
                };
                return(View("ResultSurvey", result));
            }

            return(View("ViewSurvey", viewModel));
        }
Пример #23
0
        public ActionResult Surveys_Update([DataSourceRequest] DataSourceRequest request, SurveyViewModel vm)
        {
            if (ModelState.IsValid)
            {
                using (var tx = db.Database.BeginTransaction())
                {
                    db.AddUpdateItem(vm.SurveyId, vm.ItemTypeId, vm.Name, vm.TemplateId, UserId).SingleOrDefault();
                    db.AddUpdateSurvey(vm.SurveyId, vm.AllowRestart);
                    tx.Commit();
                }
            }

            return(Json(new[] { vm }.ToDataSourceResult(request, ModelState)));
        }
Пример #24
0
        public IHttpActionResult PublishQuestion(PublishSurveyViewModel survey)
        {
            SurveyViewModel questionSurvey = new SurveyViewModel();

            questionSurvey.QuestionIds_String = survey.SurveyId.Value.ToString();
            questionSurvey.SurveyName         = Guid.NewGuid().ToString();
            questionSurvey.SurveyType         = SurveyType.Message;

            var result = SaveQuestionSurvey(questionSurvey);

            survey.SurveyId = result;

            var surveyDetails = db.Surveys.Find(result);

            if (surveyDetails != null)
            {
                if (surveyDetails.SurveyType == SurveyType.Message)
                {
                    //based on recurrence Add to X_Survey_Group

                    try
                    {
                        switch (survey.FrequencyOfNotifications)
                        {
                        case Frequency.Daily:
                        {
                            String[] times          = survey.Time1.Split(':');
                            String   cornExpression = times[1] + " " + times[0] + " * * * ";
                            RecurringJob.AddOrUpdate(survey.SurveyId + "", () => SendNotification(survey), cornExpression, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
                            break;
                        }

                        case Frequency.Hourly:
                        {
                            SendNotification(survey);
                            RecurringJob.AddOrUpdate(survey.SurveyId + "", () => SendNotification(survey), Cron.Hourly, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
                            break;
                        }

                        case Frequency.TwiceDaily:
                        {
                            String[] times           = survey.Time1.Split(':');
                            String   cornExpression  = times[1] + " " + times[0] + " * * *";
                            String[] times2          = survey.Time2.Split(':');
                            String   cornExpression2 = times2[1] + " " + times2[0] + " * * *";
                            RecurringJob.AddOrUpdate(survey.SurveyId + "First", () => SendNotification(survey), cornExpression, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
                            RecurringJob.AddOrUpdate(survey.SurveyId + "Second", () => SendNotification(survey), cornExpression2, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
                            break;
                        }
                        }
                    }
                    catch (DbUpdateException)
                    {
                        if (SurveyExists(survey.SurveyId.Value))
                        {
                            return(Conflict());
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                else
                {
                    //add to X_Survey_Group and send right now
                    SendNotification(survey);
                }
            }
            else
            {
                return(NotFound());
            }
            return(Ok());
        }
Пример #25
0
        public ActionResult Surveys_Destroy([DataSourceRequest] DataSourceRequest request, SurveyViewModel vm)
        {
            db.DeleteSurvey(vm.SurveyId);

            return(Json(new[] { vm }.ToDataSourceResult(request, ModelState)));
        }
Пример #26
0
        public async Task <ActionResult> SurveyOperation(SurveyViewModel model)
        {
            if (model.Operation == Operations.Create)
            {
                model.PageInfo = new PageInfo()
                {
                    PageTitle       = "Create New Survey",
                    PageDescription = "Create new survey."
                };

                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                Survey quiz = await CreateQuizAsync(model);

                return(RedirectToAction("SQuestionOperation", "SQuestion", new { Operation = Operations.Create, SurveyID = quiz.ID, }));
            }
            else if (model.Operation == Operations.Update && model.ID > 0)
            {
                model.PageInfo = new PageInfo()
                {
                    PageTitle       = "Modify Survey",
                    PageDescription = "Modify this survey."
                };

                var quiz = await db.Surveys.FindAsync(model.ID);

                if (quiz == null)
                {
                    return(HttpNotFound());
                }

                if (!ModelState.IsValid)
                {
                    model.SQuestions = quiz.SQuestions.Where(q => q.IsActive).ToList();

                    return(View(model));
                }

                await UpdateQuizAsync(model, quiz);

                return(RedirectToAction("Index"));
            }
            else if (model.Operation == Operations.Delete && model.ID > 0)
            {
                model.PageInfo = new PageInfo()
                {
                    PageTitle       = "Modify Survey",
                    PageDescription = "Modify this survey."
                };

                var quiz = await db.Surveys.FindAsync(model.ID);

                if (quiz == null)
                {
                    return(HttpNotFound());
                }

                await DeleteQuizAsync(model, quiz);

                return(RedirectToAction("Index"));
            }
            else
            {
                return(HttpNotFound());
            }
        }
Пример #27
0
 public static void RememberSurvey(SurveyViewModel obj)
 {
     System.Web.HttpContext.Current.Session["Survey"] = obj;
 }
Пример #28
0
        public void ParkRankings()
        {
            SurveyViewModel testSurveyModel = new SurveyViewModel()
            {
                ParkCode          = "TEST",
                StateOfResidence  = "OH",
                UserActivityLevel = "Inactive",
                Email             = "*****@*****.**"
            };

            NationalParkItem secondPark = new NationalParkItem()
            {
                ParkCode              = "QWER",
                Name                  = "Test park two",
                State                 = "Garry",
                Acreage               = 203955,
                ElevationInFt         = 5302,
                MilesOfTrail          = 508.34,
                NumberOfCampsites     = 25,
                Climate               = "Rainforest",
                YearFounded           = 1928,
                AnnualVisitorCt       = 20890567,
                InspirationalQuote    = "Who likes the cherry ones?!",
                InspirationalQuoteSrc = "Garry Le",
                ParkDescription       = "This is Garry's favorite place to be.",
                EntryFee              = 9,
                NumberAnimalSpecies   = 48
            };

            // must first populate DB w/national parks due to pK / fK relationships
            var isParkOneAdded = _db.AddNewNationalPark(_nationalParkItem);

            Assert.IsTrue(isParkOneAdded);

            var isParkTwoAdded = _db.AddNewNationalPark(secondPark);

            Assert.IsTrue(isParkTwoAdded);

            // save new posts to database; post votes for park Codes
            // 3x "TEST", 1x for "QWER"
            var isPostAdded = _db.SaveNewPost(testSurveyModel);

            Assert.IsTrue(isPostAdded);

            testSurveyModel.Email = "*****@*****.**";
            isPostAdded           = _db.SaveNewPost(testSurveyModel);
            Assert.IsTrue(isPostAdded);

            testSurveyModel.Email = "*****@*****.**";
            isPostAdded           = _db.SaveNewPost(testSurveyModel);
            Assert.IsTrue(isPostAdded);

            testSurveyModel.ParkCode = secondPark.ParkCode;
            isPostAdded = _db.SaveNewPost(testSurveyModel);
            Assert.IsTrue(isPostAdded);

            // pull DESC list of park rankings from DB
            var listParkRankings = _db.ParkRankings();

            int parkOneCount = -1;
            int parkTwoCount = -1;

            foreach (var surveyResult in listParkRankings)
            {
                if (_nationalParkItem.ParkCode.Equals(surveyResult.ParkCode))
                {
                    parkOneCount = surveyResult.count;
                }

                if (secondPark.ParkCode.Equals(surveyResult.ParkCode))
                {
                    parkTwoCount = surveyResult.count;
                }
            }
            // Ensure both parks were found
            Assert.IsTrue(parkOneCount != -1 && parkTwoCount != -1);

            // ensure the 3x added _nationalParkItem is greater than 1x added secondPark
            Assert.IsTrue(parkOneCount > parkTwoCount);
        }
Пример #29
0
        public IActionResult Create(SurveyViewModel surveyViewModel)
        {
            _surveyRepository.Create(surveyViewModel.Survey);

            return(RedirectToAction("List"));
        }
Пример #30
0
        public ActionResult updateSurvey(SurveyViewModel model)
        {
            Dictionary <int, bool> outdatedSurveys = new Dictionary <int, bool>();

            var surveysCompletions = modelContext
                                     .SurveysCompletion
                                     .Include("CategoryObj")
                                     .Include("Questions")
                                     .FirstOrDefault(x => x.Id == model.SurveyCompletionId);

            List <int> answeredQuestionIds = new List <int>();

            surveysCompletions.Questions.ToList().ForEach(z => answeredQuestionIds.Add(z.QuestionId));

            var questions = modelContext
                            .Questions
                            .Include("Survey")
                            .Include("Answers")
                            .Where(x => x.Survey.Id == surveysCompletions.SurveyId) // && !answeredQuestionIds.Contains(x.Id) && x.Old == false)
                            .ToList();

            var surveysCompletion = modelContext
                                    .SurveysCompletion
                                    .Include("CategoryObj")
                                    .Include("Questions")
                                    .Include("Questions.Answers")
                                    .FirstOrDefault(x => x.Id == model.SurveyCompletionId);

            foreach (var DTO in model.surveyCompletionDTOs)
            {
                if (DTO.Answers != null)
                {
                    bool nueva    = false;
                    var  question = surveysCompletion.Questions.FirstOrDefault(x => x.QuestionId == DTO.QuestionId);
                    if (question == null)
                    {
                        question = new SurveyCompletionQuestion();
                        nueva    = true;
                    }
                    question.Question   = DTO.Question;
                    question.QuestionId = DTO.QuestionId;
                    if (!nueva && question.Answers != null && question.Answers.Count > 0)
                    {
                        question.Answers.Clear();
                    }
                    question.Answers = questions
                                       .Where(x => x.Id == DTO.QuestionId)
                                       .FirstOrDefault()
                                       .Answers
                                       .Where(x => DTO.Answers.Contains(x.Id))
                                       .Select(x => new SurveyCompletionAnswer
                    {
                        Answer      = x.SupplyAnswer,
                        AnswerValue = x.Value
                    })
                                       .ToList();
                    if (nueva)
                    {
                        surveysCompletion.Questions.Add(question);
                    }
                }
            }
            modelContext.SaveChanges();

            return(RedirectToAction("UpdateProduct/" + model.ProductId));
        }
Пример #31
0
 public SurveyThree(SurveyViewModel survey)
 {
     InitializeComponent();
     svm = survey;
     HowDidYou.ItemsSource = svm.HowDidYouDS;
 }