Exemple #1
0
        public async Task <FormDTO> CreateFormAsync(FormDTO tempForm)
        {
            if (tempForm == null)
            {
                throw new BusinessLogicException(ExceptionMessages.EntityNull);
            }
            if (tempForm.Title == null)
            {
                throw new BusinessLogicException(ExceptionMessages.TitleNull);
            }

            var form = tempForm.MapFrom();

            form.CreatedOn = dateTimeProvider.GetDateTime();

            form.Id = Guid.NewGuid();

            await this.dbcontext.Forms.AddAsync(form);

            await this.dbcontext.SaveChangesAsync();

            var formDto = form.MapFrom();

            return(formDto);
        }
        public ActionResult Edit([Bind(Include = "Id, NumberForm, SurveyGeographyId, HousingTypeId, DistrictId, InterviewerId, Address, Phone,InterviewDate, StartTime, EndTime")] FormVM formVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    FormDTO formDTO = Mapper.Map <FormDTO>(formVM);
                    FormService.Update(formDTO);
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ModelState.AddModelError(null, "Что-то пошло не так. Не удалось сохранить изменения.");
                }

                ViewBag.SurveyGeographyId = GetSurveyGeographySelectList(formVM.SurveyGeographyId);
                ViewBag.HousingTypeId     = GetHousingTypeSelectList(formVM.HousingTypeId);
                ViewBag.DistrictId        = GetDistrictSelectList(formVM.DistrictId);
                ViewBag.InterviewerId     = GetInterviewerSelectList(formVM.InterviewerId);

                return(View(formVM));
            }
            catch (UniqueConstraintException ex)
            {
                return(Json(new { hasError = true, data = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
        protected FormDTO CreateFormDTO(FormType type)
        {
            var form = new FormDTO();

            form.Type = type;

            form.Fullname             = Request.Form.Get("fullname");
            form.Address              = Request.Form.Get("address");
            form.Postcode             = Request.Form.Get("postcode");
            form.City                 = Request.Form.Get("city");
            form.Email                = Request.Form.Get("email");
            form.PhoneNumberPrimary   = Request.Form.Get("phoneNumberPrimary");
            form.PhoneNumberAlternate = Request.Form.Get("phoneNumberAlternate");
            form.PreferredDate        = Request.Form.Get("preferredDate");
            form.PreferredTime        = Request.Form.Get("preferredTime");

            form.CarBrand        = Request.Form.Get("carBrand");
            form.CarModel        = Request.Form.Get("carModel");
            form.CarLicencePlate = Request.Form.Get("carLicencePlate");
            form.CarYear         = Request.Form.Get("carYear");
            form.CarAddress      = Request.Form.Get("carAddress");
            form.CarCity         = Request.Form.Get("carCity");
            form.CarPostcode     = Request.Form.Get("carPostcode");
            form.Comments        = Request.Form.Get("comments");
            form.PaymentMethod   = Request.Form.Get("paymentMethod");
            form.IpAddress       = Request.UserHostAddress;

            ValidateFormDTO(form);

            return(form);
        }
Exemple #4
0
        public List <FormDTO> GetVotedForms(string username)
        {
            //returneaza toate formurile votate de catre un user
            int               userID         = _dataAccess.UserRepository.FindFirstBy(user => user.Username == username).UserID;
            List <Form>       formList       = new List <Form>();
            List <VotedForms> votedFormsList = _dataAccess.VotedFormsRepository.FindAllBy(voted => voted.UserID == userID).ToList();
            List <FormDTO>    formDtoList    = new List <FormDTO>();
            FormDTO           formDTO;
            Form              form;

            foreach (VotedForms votedForm in votedFormsList)
            {
                form = _dataAccess.FormRepository.FindFirstBy(f => f.FormID == votedForm.FormID);
                formList.Add(form);
            }

            foreach (Form f in formList)
            {
                formDTO             = new FormDTO();
                formDTO.Title       = f.Title;
                formDTO.State       = f.State;
                formDTO.CreatedDate = f.CreatedDate.ToString();
                formDTO.Deadline    = f.Deadline.ToString();
                formDTO.Category    = _dataAccess.CategoryRepository.FindFirstBy(category => category.CategoryID == f.CategoryID).Name;
                formDTO.Username    = _dataAccess.UserRepository.FindFirstBy(user => user.UserID == f.UserID).Username;
                formDTO.Id          = f.FormID;
                formDTO.Voted       = true;

                formDtoList.Add(formDTO);
            }

            return(formDtoList);
        }
        public ActionResult Create([Bind(Include = "NumberForm, SurveyGeographyId, HousingTypeId, DistrictId, InterviewerId, Address, Phone,InterviewDate, StartTime, EndTime")] FormVM formVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    FormDTO formDTO = Mapper.Map <FormDTO>(formVM);
                    //int questionId = QuestionService.AddAndGetId(questionDTO);
                    FormService.Add(formDTO);
                    return(RedirectToAction("Index"));
                }
                ViewBag.SurveyGeographyId = GetSurveyGeographySelectList(formVM.SurveyGeographyId);
                ViewBag.HousingTypeId     = GetHousingTypeSelectList(formVM.HousingTypeId);
                ViewBag.DistrictId        = GetDistrictSelectList(formVM.DistrictId);
                ViewBag.InterviewerId     = GetInterviewerSelectList(formVM.InterviewerId);
                ViewBag.Today             = DateTime.Now.ToString("yyyy-MM-dd");
                ViewBag.Time = DateTime.Now.ToString("HH\\:mm");

                return(View(formVM));
            }
            catch (UniqueConstraintException ex)
            {
                return(Json(new { hasError = true, data = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #6
0
        /// <summary>
        /// method for converting a System.DateTime value to a UNIX Timestamp
        /// </summary>
        /// <param name = "value" > date to convert/// <returns></returns>
        //private static double ConvertToTimestamp(DateTime value)
        ////{
        ////    create Timespan by subtracting the value provided from
        ////    the Unix Epoch
        //    TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());

        //    return (double)span.TotalSeconds;

        //}


        public List <HostDTO> InformacoesPDF(FormDTO form, int userID)
        {
            Usuarios user       = _userRepository.BuscarPorID(userID);
            var      listaHosts = _hostService.ListarHostsPorIdGroup(form.GroupID, user.Id);

            //var dataInicio = ConvertToTimestamp(form.DataInicial);
            //var dataFinal = ConvertToTimestamp(form.DataFinal);

            foreach (var item in listaHosts)
            {
                var listaTrigger = _triggerService.BuscarTriggers(user, item.Id);

                var listaEvents = _eventService.ListarEvents(user, form, item.Id);

                //foreach (var events in listaEvents.Where(x => x.data > form.DataInicial && x.data < form.DataFinal))
                foreach (var events in listaEvents)
                {
                    var triggerEvent = listaTrigger.FirstOrDefault(x => x.Id == events.IdTrigger);

                    events.Mensagem = triggerEvent.Mensagem;
                }

                item.listaEvent = listaEvents;
            }
            List <HostDTO> listaHost = new List <HostDTO>();

            return(listaHost);
        }
Exemple #7
0
        public async Task EditForm(FormDTO form)
        {
            var connection = new MySqlConnection(_configuration.GetConnectionString(CONNECTION_STRING_NAME));
            await connection.OpenAsync();

            using (MySqlCommand cmdSel = new MySqlCommand($"SELECT * FROM jkh.forms WHERE UID = {form.UID}", connection))
            {
                var reader = await cmdSel.ExecuteReaderAsync();

                reader.Read();

                form.Lat = form.Lat == 0 ? Convert.ToDouble(Encoding.UTF8.GetString(((byte[])reader["lat"]))) : form.Lat;
                form.Lon = form.Lon == 0 ? Convert.ToDouble(Encoding.UTF8.GetString(((byte[])reader["Lon"]))) : form.Lon;

                form.MundepUID = form.MundepUID == 0 ? Convert.ToInt32(reader["mundep_UID"]) : form.MundepUID;
                form.UserUID   = form.UserUID == 0 ? Convert.ToInt32(reader["user_UID"]) : form.UserUID;
                form.Adress    = form.Adress == "" ? Encoding.UTF8.GetString(((byte[])reader["adress"])) : form.Adress;
            }
            connection.Close();

            connection = new MySqlConnection(_configuration.GetConnectionString(CONNECTION_STRING_NAME));
            await connection.OpenAsync();

            using var cmdUpd = new MySqlCommand($"UPDATE jkh.forms t SET t.mundep_UID = '{form.MundepUID}', t.Adress = '{form.Adress}', t.lat = {form.Lat}, t.lon = {form.Lon} WHERE t.UID = {form.UID}", connection);
            await cmdUpd.ExecuteNonQueryAsync();
        }
        public async Task <bool> SendForm(FormDTO data)
        {
            var httpClient = _clientFactory.CreateClient("HttpClient");

            httpClient.Timeout = System.TimeSpan.FromSeconds(275);
            var dataToSend = JsonSerializer.Serialize(data);

            using (var content = new StringContent(dataToSend, Encoding.UTF8, "application/json"))
            {
                try
                {
                    var result = await httpClient.PostAsync($"https://us-central1-randomfails.cloudfunctions.net/submitEmail", content);

                    // The call was a success

                    if (result.StatusCode == HttpStatusCode.OK)
                    {
                        return(true);
                    }

                    return(false);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
        public static FormViewModel MapFrom(this FormDTO dto)
        {
            if (dto == null)
            {
                throw new Exception(ExceptionMessages.EntityNull);
            }

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

            List <TextQuestionViewModel> textQuestions = new List <TextQuestionViewModel>();

            foreach (var item in dto.TextQuestions)
            {
                textQuestions.Add(item.MapFrom());
                positionsInForm.Add(item.QuestionNumber);
            }

            List <MultipleChoiceQuestionViewModel> multipleChoiceQuestions = new List <MultipleChoiceQuestionViewModel>();

            foreach (var item in dto.MultipleChoiceQuestions)
            {
                multipleChoiceQuestions.Add(item.MapFrom());
                positionsInForm.Add(item.QuestionNumber);
            }

            List <DocumentQuestionViewModel> documentQuestions = new List <DocumentQuestionViewModel>();

            foreach (var item in dto.DocumentQuestions)
            {
                documentQuestions.Add(item.MapFrom());
                positionsInForm.Add(item.QuestionNumber);
            }

            int lastQuestionNumber = 0;

            if (positionsInForm.Count() > 0)
            {
                lastQuestionNumber = positionsInForm.Max();
            }
            else
            {
                lastQuestionNumber = 0;
            }

            var result = new FormViewModel
            {
                Id                      = dto.Id,
                Title                   = dto.Title,
                Description             = dto.Description,
                UserId                  = dto.UserId,
                MultipleChoiceQuestions = multipleChoiceQuestions,
                TextQuestions           = textQuestions,
                DocumentQuestions       = documentQuestions,
                LastQuestionNumber      = lastQuestionNumber,
                CorelationTokens        = dto.CorelationTokens,
            };

            return(result);
        }
Exemple #10
0
        private async Task <Form> ConvertDTOtoBO(FormDTO formDTO)
        {
            Form form = new Form
            {
                Id = formDTO.Id,

                Graduated               = formDTO.Graduated,
                ClusterContestId        = formDTO.ClusterContestId,
                ClusterContestCode      = formDTO.ClusterContestCode,
                ClusterContestName      = formDTO.ClusterContestName,
                RegisterPlaceOfExamId   = formDTO.RegisterPlaceOfExamId,
                RegisterPlaceOfExamCode = formDTO.RegisterPlaceOfExamCode,
                RegisterPlaceOfExamName = formDTO.RegisterPlaceOfExamName,
                Biology         = formDTO.Biology,
                Chemistry       = formDTO.Chemistry,
                CivicEducation  = formDTO.CivicEducation,
                Geography       = formDTO.Geography,
                History         = formDTO.History,
                Languages       = formDTO.Languages,
                Literature      = formDTO.Literature,
                Maths           = formDTO.Maths,
                NaturalSciences = formDTO.NaturalSciences,
                Physics         = formDTO.Physics,
                SocialSciences  = formDTO.SocialSciences,

                ExceptLanguages       = formDTO.ExceptLanguages,
                Mark                  = formDTO.Mark,
                ReserveBiology        = formDTO.ReserveBiology,
                ReserveChemistry      = formDTO.ReserveChemistry,
                ReserveCivicEducation = formDTO.ReserveCivicEducation,
                ReserveGeography      = formDTO.ReserveGeography,
                ReserveHistory        = formDTO.ReserveHistory,
                ReserveLanguages      = formDTO.ReserveLanguages,
                ReserveLiterature     = formDTO.ReserveLiterature,
                ReserveMaths          = formDTO.ReserveMaths,
                ReservePhysics        = formDTO.ReservePhysics,

                Area         = formDTO.Area,
                PriorityType = formDTO.PriorityType,
                Aspirations  = formDTO.Aspirations == null ? null : formDTO.Aspirations.Select(m => new Aspiration
                {
                    Id                = m.Id ?? Guid.Empty,
                    FormId            = m.FormId,
                    MajorsId          = m.MajorsId,
                    MajorsCode        = m.MajorsCode,
                    MajorsName        = m.MajorsName,
                    UniversityId      = m.UniversityId,
                    UniversityCode    = m.UniversityCode,
                    UniversityName    = m.UniversityName,
                    UniversityAddress = m.UniversityAddress,
                    SubjectGroupId    = m.SubjectGroupId,
                    SubjectGroupCode  = m.SubjectGroupCode,
                    SubjectGroupName  = m.SubjectGroupName,
                    Sequence          = m.Sequence
                }).ToList()
            };

            return(form);
        }
Exemple #11
0
        public async Task AddForm(FormDTO form)
        {
            var connection = new MySqlConnection(_configuration.GetConnectionString(CONNECTION_STRING_NAME));
            await connection.OpenAsync();

            using var cmd = new MySqlCommand($" INSERT INTO jkh.forms (Adress, date, mundep_UID, lat, lon, user_UID) VALUES ('{form.Adress}', curdate(), {form.MundepUID}, {form.Lat}, {form.Lon}, {form.UserUID})", connection);
            await cmd.ExecuteNonQueryAsync();
        }
        public async Task <IActionResult> AddNewForm([FromBody] FormDTO form)
        {
            long userId = User.GetUserId();
            long formId = await _formService.SaveNewFormAndReturnId(userId, form.FormName, form.uniqueId);

            await _formService.SaveDetailsOfForm(formId, form.FormDetailsList);

            return(JsonResponseStatus.Success());
        }
Exemple #13
0
        public async Task AddForm(Form form)
        {
            if (form == null)
            {
                throw new ArgumentNullException(nameof(form));
            }
            FormDTO form_w_geo = await _IGeoProvider.GetAdress(new FormDTO(form));

            await _IformRepository.AddForm(form_w_geo);
        }
Exemple #14
0
 public Form(FormDTO form)
 {
     UID       = form.UID;
     Adress    = form.Adress;
     Date      = form.Date;
     MundepUID = form.MundepUID;
     UserUID   = form.UserUID;
     Lat       = form.Lat;
     Lon       = form.Lon;
 }
        public async Task <IActionResult> AddForm([FromBody] FormDTO newForm)
        {
            if (!this.IsTokenValid(_tokenService.GetTemporaryToken(this.GetCurrentUserId())))
            {
                return(Unauthorized());
            }

            newForm.Draft = true;
            FormDTO result = await _mediator.Send(new AddFormQuery { Form = newForm, UserId = this.GetCurrentUserId() });

            return(Ok(result.Id));
        }
Exemple #16
0
        public JsonResult Add(FormDTO formDTO)
        {
            UserService userService = new UserService();
            var         user        = userService.getUserWithUsername(User.Identity.Name);

            formDTO.CreatedAt = DateTime.Now;
            formDTO.CreatedBy = user.Id;

            FormService formService = new FormService();
            var         result      = formService.add(formDTO);

            return(Json(result));
        }
Exemple #17
0
        /// <summary>
        /// Returnarea tuturor sondajelor
        /// </summary>
        /// <param name="token"></param>
        /// <param name="page"></param>
        /// <param name="per_page"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public List <FormDTO> GetAllForms(string token, int page, int per_page, string state)
        {
            List <Form>    formList;
            FormDTO        formDTO;
            List <FormDTO> formDtoList;
            int            userID;

            if (state == "all")
            {
                formList = _dataAccess.FormRepository.GetAll().OrderByDescending(form => form.CreatedDate).ToList();
            }
            else
            {
                formList = _dataAccess.FormRepository.GetAll().Where(form => form.State == state).OrderByDescending(form => form.CreatedDate).ToList();
            }

            formList    = formList.Skip(page * per_page).Take(per_page).ToList();
            formDtoList = new List <FormDTO>();

            userID = _dataAccess.TokenRepository.FindFirstBy(user => user.TokenString.Equals(token)).UserID;

            foreach (Form f in formList)
            {
                formDTO             = new FormDTO();
                formDTO.Title       = f.Title;
                formDTO.State       = f.State;
                formDTO.CreatedDate = f.CreatedDate.ToString();
                formDTO.Deadline    = f.Deadline.ToShortDateString();
                formDTO.Category    = _dataAccess.CategoryRepository.FindFirstBy(category => category.CategoryID == f.CategoryID).Name;
                formDTO.Username    = _dataAccess.UserRepository.FindFirstBy(user => user.UserID == f.UserID).Username;
                formDTO.Id          = f.FormID;
                formDTO.NrVotes     = f.NrVotes;
                formDTO.Voted       = true;

                try
                {
                    userID = _dataAccess.VotedFormsRepository.FindFirstBy(voted => voted.FormID == f.FormID && voted.UserID == userID).UserID;
                }
                catch
                {
                    // Daca userul a votat sondajul deja sau sondajul este inchis, nu il va mai putea vota
                    if (formDTO.State != "closed")
                    {
                        formDTO.Voted = false;
                    }
                }

                formDtoList.Add(formDTO);
            }
            return(formDtoList.ToList());
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SendForm(FormDTO data)
        {
            if (ModelState.IsValid)
            {
                var isSend = false;

                while (isSend != true)
                {
                    isSend = await formService.SendForm(data);
                }
                return(Accepted(1));
            }
            return(StatusCode(404));
        }
Exemple #19
0
        public IActionResult Post([FromBody] FormDTO formDto)
        {
            try
            {
                Uri uri = new Uri(formDto.Uri);
                formDto.Uri = uri.AbsoluteUri;
            }
            catch (UriFormatException ex)
            {
                var res = new Dictionary <string, string>();
                res.Add("Uri", "Invalid Uri.");
                return(BadRequest(res));
            }


            var uriModel = _uriRepository.FindByField(FIELD_ORIGINAL, formDto.Uri);

            if (uriModel != null)
            {
                formDto.Alias = GetBaseUrl(Request, uriModel.Alias);
                return(Ok(formDto));
            }
            else
            {
                string token = null;
                uriModel = null;
                for (var count = 0; count < 20; count++)
                {
                    token    = Token.Generate();
                    uriModel = _uriRepository.FindByField(FIELD_ALIAS, token);
                    if (uriModel == null)
                    {
                        break;
                    }
                }

                uriModel = new UriModel
                {
                    Original = formDto.Uri,
                    Alias    = token
                };

                _uriRepository.Add(uriModel);

                formDto.Alias = GetBaseUrl(Request, token);

                return(Created("", formDto));
            }
        }
Exemple #20
0
        public static void Seeder(SurvelloContext context)
        {
            var formDto = new FormDTO
            {
                Title         = "TestForm",
                Description   = "TestDescrtiption",
                UserId        = userId,
                TextQuestions = new List <TextQuestionDTO>()
                {
                    new TextQuestionDTO
                    {
                        Description  = "Where are you from?",
                        IsLongAnswer = false,
                        IsRequired   = true,
                    }
                },
                MultipleChoiceQuestions = new List <MultipleChoiceQuestionDTO>()
                {
                    new MultipleChoiceQuestionDTO
                    {
                        Description      = "How would you rate your experience with our product?",
                        IsRequired       = true,
                        IsMultipleAnswer = false,
                        Options          = new List <MultipleChoiceOptionDTO>()
                        {
                            new MultipleChoiceOptionDTO
                            {
                                OptionDescription = "Satisfied",
                            }
                        }
                    },
                },
                DocumentQuestions = new List <DocumentQuestionDTO>()
                {
                    new DocumentQuestionDTO
                    {
                        Description     = "TestDescription",
                        FileNumberLimit = 10,
                        FileSize        = 1,
                    }
                }
            };

            var user = new User
            {
                Id       = userId,
                UserName = "******"
            };
        }
 protected void ValidateFormDTO(FormDTO form)
 {
     foreach (var prop in form.GetType().GetProperties())
     {
         var mandatory = prop.GetCustomAttribute <NLNameAttribute>()?.Mandatory;
         if (mandatory.HasValue && mandatory.Value)
         {
             var val = prop.GetValue(form) as string;
             if (val == null || val.Length == 0)
             {
                 throw new ArgumentNullException(prop.GetCustomAttribute <NLNameAttribute>().NLName);
             }
         }
     }
 }
        public IActionResult solicitarPDF([FromQuery] FormDTO form)
        {
            try
            {
                var idUsuario = Convert.ToInt32(HttpContext.User.Claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value);

                var result = _pdfService.InformacoesPDF(form, idUsuario);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemple #23
0
        public async Task ThrowException_WhenTitleIsNull()
        {
            var options = Utils.GetOptions(nameof(ThrowException_WhenTitleIsNull));
            var mockDateTimeProvider = new Mock <IDateTimeProvider>();
            var mockBlobService      = new Mock <IBlobServices>();
            var formDto = new FormDTO
            {
                Title = null
            };

            using (var assertContext = new SurvelloContext(options))
            {
                var sut = new FormServices(assertContext, mockDateTimeProvider.Object, mockBlobService.Object);
                await Assert.ThrowsExceptionAsync <BusinessLogicException>(() => sut.CreateFormAsync(formDto));
            }
        }
Exemple #24
0
        public void Update(FormDTO formDTO)
        {
            try
            {
                Form form = Mapper.Map <Form>(formDTO);

                _unitOfWork.Forms.Update(form);
                _unitOfWork.Save();
            }
            catch (DbUpdateException)
            {
                if (NotUnique(formDTO.NumberForm))
                {
                    throw new UniqueConstraintException();
                }
            }
        }
Exemple #25
0
        public async Task EditForm(Form form)
        {
            if (form == null)
            {
                throw new ArgumentNullException(nameof(form));
            }
            if (form.Adress != "")
            {
                FormDTO form_w_NewGeo = await _IGeoProvider.GetAdress(new FormDTO(form));

                await _IformRepository.EditForm(form_w_NewGeo);
            }
            else
            {
                await _IformRepository.EditForm(new FormDTO(form));
            }
        }
        public ActionResult Details(int?id)
        {
            try
            {
                FormDTO formDTO = FormService.Get(id);
                FormVM  formVM  = Mapper.Map <FormVM>(formDTO);

                return(View(formVM));
            }
            catch (ArgumentException)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            catch (NotFoundException)
            {
                return(HttpNotFound());
            }
        }
Exemple #27
0
        /// <summary>
        /// Returnarea tuturor sondajelor votate de catre un user
        /// </summary>
        /// <param name="username"></param>
        /// <param name="page"></param>
        /// <param name="per_page"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public List <FormDTO> GetVotedForms(string username, int page, int per_page, string state)
        {
            int              userID   = _dataAccess.UserRepository.FindFirstBy(user => user.Username.Equals(username)).UserID;
            List <Form>      formList = new List <Form>();
            List <VotedForm> votedFormsList;
            List <FormDTO>   formDtoList = new List <FormDTO>();
            FormDTO          formDTO;
            Form             form;

            if (state == "all")
            {
                votedFormsList = _dataAccess.VotedFormsRepository.FindAllBy(voted => voted.UserID == userID).OrderByDescending(voted => voted.Form.CreatedDate).ToList();
            }
            else
            {
                votedFormsList = _dataAccess.VotedFormsRepository.FindAllBy(voted => voted.UserID == userID && voted.Form.State == state).OrderByDescending(voted => voted.Form.CreatedDate).ToList();
            }

            votedFormsList = votedFormsList.Skip(page * per_page).Take(per_page).ToList();

            foreach (VotedForm votedForm in votedFormsList)
            {
                form = _dataAccess.FormRepository.FindFirstBy(f => f.FormID == votedForm.FormID);
                formList.Add(form);
            }

            foreach (Form f in formList)
            {
                formDTO             = new FormDTO();
                formDTO.Title       = f.Title;
                formDTO.State       = f.State;
                formDTO.CreatedDate = f.CreatedDate.ToString();
                formDTO.Deadline    = f.Deadline.ToShortDateString();
                formDTO.Category    = _dataAccess.CategoryRepository.FindFirstBy(category => category.CategoryID == f.CategoryID).Name;
                formDTO.Username    = _dataAccess.UserRepository.FindFirstBy(user => user.UserID == f.UserID).Username;
                formDTO.Id          = f.FormID;
                formDTO.NrVotes     = f.NrVotes;
                formDTO.Voted       = true;

                formDtoList.Add(formDTO);
            }

            return(formDtoList.ToList());
        }
Exemple #28
0
        public async Task <FormDTO> GetAdress(FormDTO form)
        {
            string addressToGeocode = form.Adress;

            string     requestUri = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?key={1}&address={0}&sensor=false", Uri.EscapeDataString(addressToGeocode), _configuration.GetConnectionString(API_GOOGLE_STRING_NAME));
            HttpClient client     = new HttpClient();
            var        response   = await client.GetStringAsync(requestUri);

            var yourXml = XElement.Parse(response);
            var dict    = yourXml.Descendants()
                          .Where(node => node.Name == "location")
                          .Descendants()
                          .ToDictionary(node => node.Name.ToString(), node => node.Value);

            form.Lat = Convert.ToDouble(dict["lat"]);
            form.Lon = Convert.ToDouble(dict["lng"]);

            return(form);
        }
        public static Form MapFrom(this FormDTO dto)
        {
            if (dto == null)
            {
                throw new Exception(ExceptionMessages.EntityNotFound);
            }

            return(new Form
            {
                Id = dto.Id,
                Title = dto.Title,
                Description = dto.Description,
                UserId = dto.UserId,
                NumberOfFilledForms = dto.NumberOfFilledForms,
                MultipleChoiceQuestions = dto.MultipleChoiceQuestions.MapFrom(),
                TextQuestions = dto.TextQuestions.MapFrom(),
                DocumentQuestions = dto.DocumentQuestions.MapFrom()
            });
        }
Exemple #30
0
        public void SubmitForm(FormDTO dto)
        {
            SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
            var        mail       = new MailMessage();

            mail.From = new MailAddress("*****@*****.**");
            mail.To.Add("*****@*****.**");
            mail.Subject    = dto.Subject;
            mail.IsBodyHtml = true;
            string htmlBody;

            htmlBody        = "<h3>Client " + dto.Name + " says:</h3><br/><p>" + dto.Description + "</p><br/><p>Client Email: " + dto.Email + "</p>";
            mail.Body       = htmlBody;
            SmtpServer.Port = 587;
            SmtpServer.UseDefaultCredentials = false;
            SmtpServer.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "Prognasa12");
            SmtpServer.EnableSsl             = true;
            SmtpServer.Send(mail);
        }