Esempio n. 1
0
        public ActionResult ViewMashov(string file_number, string form_ver)
        {
            // get the user
            UserData user = (UserData)this.Session["user"];

            if (user.Type.ToLower() == "momhee")
            {
                // check if the momhee has excess to this request
                if (!RequestManager.Manager.IsRequestAllowedForMomhee(user.Id, file_number))
                {
                    return(RedirectToAction("RequestsManage", "AdminGovExp"));
                }
            }
            // load the mashov
            var    dataFile = Server.MapPath("~/App_Data/Mashovs/mashov_" + file_number + ".json");
            string json     = System.IO.File.ReadAllText(@dataFile);
            Dictionary <string, string> values = FormValues.LoadJson(json).Values;
            // load the form of the mashov
            var        mashovFile = Server.MapPath("~/App_Data/Forms/MashovForm_v_" + form_ver + ".xml");
            PostedForm pR         = new PostedForm(FormManager.Manager.Load(mashovFile).FormComponents[0], values);

            // load extra data of the request
            string where        = "file_number='" + file_number + "'";
            ViewData["request"] = RequestManager.Manager.GetAllWhere(where, null, 1, 1)[0];
            ViewData["names"]   = RequestManager.Manager.GetAllColNames();

            return(View(pR));
        }
Esempio n. 2
0
        public async Task <ActionResult <FormValues> > AddFormValues(FormValues item)
        {
            _context.FormValues.Add(item);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(AddFormValues), new { id = item.Id }, item));
        }
 public bool ValidateAll(FormValues values, FormComponent comp)
 {
     if (comp.FormComponents == null || comp.FormComponents.Count == 0)
     {
         if (comp.Type.ToLower() == "input")
         {
             var range    = comp.Properties.ContainsKey("range") ? comp.Properties["range"] : "Letters";
             var required = comp.Properties.ContainsKey("required") ? comp.Properties["required"] : "false";
             var value    = values.Values[comp.Properties["id"]];
             if (value == "" && required == "false")
             {
                 // not required and empty input
                 return(true);
             }
             // validate using the TypeValidator
             return(TypeValidator.Validator.Validate(value, range));
         }
         return(true);
     }
     else
     {
         /// check all children of the component
         foreach (FormComponent c in comp.FormComponents)
         {
             if (!ValidateAll(values, c))
             {
                 // found an invalid input
                 return(false);
             }
         }
         return(true);
     }
 }
Esempio n. 4
0
        public override IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            if (FormValues == null || !FormValues.Any())
            {
                return(new List <ValidationResult>());
            }

            if (FormTemplate == null)
            {
                var context = new LightMethods.Survey.Models.DAL.SurveyContext();
                using (var uow = new UnitOfWork(context))
                {
                    FormTemplate = uow.FormTemplatesRepository.GetNotTrackedFullTemplate(FormTemplateId);
                }
            }

            foreach (var value in FormValues)
            {
                if (value.MetricId != Guid.Empty && value.Metric == null)
                {
                    value.Metric = FormTemplate.MetricGroups.SelectMany(g => g.Metrics).Where(m => m.Id == value.MetricId).Single();
                }
            }

            return(FormValues.SelectMany(v => v.Validate(validationContext)));
        }
        public ActFormRequest(string selectedTerm, string courses)
        {
            var courseQuerry       = new KeyValuePair <string, string>("courses", courses);
            var selectedTermQuerry = new KeyValuePair <string, string>("selectedTerm", selectedTerm);

            FullFormValues = FormValues.ToList();
            FullFormValues.Add(courseQuerry);
            FullFormValues.Add(selectedTermQuerry);
        }
        public override JsonResult Update(FormValues <TFormDetailViewModel> formValues)
        {
            var entityDetails = FormUtitities.ViewModelToEntityDetails <TEntityDetail>(formValues.Details, formValues.Language);
            var result        = _entityController.Update(long.Parse(formValues.Meta["id"]), entityDetails.ToArray(), formValues.GetTaxonomuTypeIdTaxonomyId(), _userManager.FindByNameAsync(User.Identity.Name).Result);

            return(Json(
                       result > 0 ?
                       new BaseAjaxResult(JsonResultState.Success, "Update successuly") :
                       new BaseAjaxResult(JsonResultState.Failed, "Update failed")));
        }
Esempio n. 7
0
        public JsonResult NewTaxonomy(FormValues formValues)
        {
            var taxonomyTypeId = formValues.Meta[AppKey.TaxonomyTypeId];
            var parentId       = formValues.GetMetaValueAsLong(AppKey.ParentId);

            var user              = _userManager.FindByNameAsync(User.Identity.Name).Result;
            var taxonomy          = _taxonomyHelper.CreateTaxonomy(Int64.Parse(taxonomyTypeId), parentId, null, formValues.Details, user);
            var taxonomyViewModel = _taxonomyHelper.TaxonomyToViewModel(taxonomy);

            return(Json(taxonomyViewModel));
        }
Esempio n. 8
0
        public async Task <JsonResult> Update(FormValues <ImageViewModel> formValues)
        {
            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            var fileId = long.Parse(formValues.GetMetaValue("id"));
            Dictionary <long, long[]> taxonomyTypeTaxonomies = formValues.TaxonomyTypes?.ToDictionary(o => o.Key, o => o.Value.Keys.ToArray());
            var entityDetails = FormUtitities.ViewModelToEntityDetails <FileEntityDetail>(formValues.Details, formValues.Language);
            var result        = _mediaHelper.Update(fileId, entityDetails, taxonomyTypeTaxonomies, user);

            return(Json(result));
        }
Esempio n. 9
0
        public async Task <IActionResult> UpdateFormValues(long id, FormValues formValues)
        {
            if (id != formValues.Id)
            {
                return(BadRequest());
            }

            _context.Entry(formValues).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(NoContent());
        }
Esempio n. 10
0
 public static FormValues AsFormValues(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
 {
     var formValues = source as FormValues;
     if (formValues == null)
     {
         formValues = new FormValues();
         foreach (var u in source.GetType().GetProperties(bindingAttr).Where(p => p.GetValue(source, null) != null))
         {
             formValues.Add(u.Name, u.GetValue(source, null).ToString());
         }
     }
     return formValues;
 }
Esempio n. 11
0
        public virtual JsonResult Create(FormValues <TFormDetailViewModel> formValues)
        {
            var entityDetails = FormUtitities.ViewModelToEntityDetails <TEntityDetail>(formValues.Details, formValues.Language);

            var entity = new TEntity
            {
                Name = formValues.Details.Title,
            };

            entity = _entityController.Create(entity, entityDetails.ToArray(), _userManager.FindByNameAsync(User.Identity.Name).Result);

            return(Json(new BaseAjaxResult(JsonResultState.Success, _entityController.GetLocalizationString("Create successfuly."), Url.Action("update", new { id = entity.Id }))));
        }
Esempio n. 12
0
        public JsonResult UpdateTaxonomy(FormValues formValues)
        {
            var id       = formValues.GetMetaValueAsLong("id") ?? 0;
            var parentId = formValues.GetMetaValueAsLong(AppKey.ParentId);

            var user              = _userManager.FindByNameAsync(User.Identity.Name).Result;
            var taxonomy          = _taxonomyHelper.UpdateTaxonomy(parentId, id, formValues.Details, user);
            var taxonomyViewModel = _taxonomyHelper.TaxonomyToViewModel(taxonomy);

            var result = new BaseAjaxResult(JsonResultState.Success, "The taxonomy was deleted.", taxonomyViewModel);

            return(Json(result));
        }
Esempio n. 13
0
        public List <ArrayList> ColumnsNamesDetail(object detail)
        {
            ArrayList        columnsNames = new ArrayList();
            ArrayList        rows         = new ArrayList();
            List <ArrayList> listDetail   = new List <ArrayList>();
            FormValues       formValue    = null;
            int idDetalle = 0;
            var obj       = JToken.Parse(detail.ToString());

            foreach (var item in obj.Children())
            {
                formValue = JsonConvert.DeserializeObject <FormValues>(item.ToString());
                bool canConvert = int.TryParse(formValue.apiId, out idDetalle);
                if (canConvert)
                {
                    // Guardamos los valores de una solo registro
                    ArrayList values = new ArrayList();
                    foreach (var column in JToken.Parse(formValue.Value.ToString()).Children())
                    {
                        formValue = JsonConvert.DeserializeObject <FormValues>(column.ToString());
                        // Si idDetalle es igual a 1 extraemos las columnas del detalle
                        // Guardamos los nombres de las columnas
                        if (idDetalle == 1)
                        {
                            columnsNames.Add(EliminarEspaciosAcentos(formValue.apiId.ToString()));
                        }
                        // Guardamos los registros del detalle
                        values.Add(ConfigurarDato(formValue.Value.ToString()));
                    }

                    // Añadimos los valores al array de filas
                    rows.Add(values);
                }
                else
                {
                    // Guardamos los nombres de las columnas
                    foreach (var column in JToken.Parse(formValue.Value.ToString()).Children())
                    {
                        formValue = JsonConvert.DeserializeObject <FormValues>(column.ToString());
                        columnsNames.Add(formValue.apiId);
                    }
                }
            }
            // Guardamos las lista que contiene las columnas y registros
            listDetail.Add(columnsNames);
            listDetail.Add(rows);
            return(listDetail);
        }
Esempio n. 14
0
 public async Task<HttpResponseMessage> Post(string url, FormValues formValues, FormValues defaults)
 {
     foreach (var value in defaults)
     {
         formValues[value.Key] = value.Value;
     }
     ResponseMsg = await SendRequest(HttpMethod.Post, url, formValues);
     if (ResponseMsg.StatusCode != HttpStatusCode.OK)
     {
         File.WriteAllText($"error{++_errorNumber}.html", Html);
         File.WriteAllText($"error{_errorNumber}.txt", string.Join(
             "\n", formValues.Select(a => $"'{a.Key}'='{a.Value}'")
             ));
     }
     return await Task.FromResult(ResponseMsg);
 }
        public HvacSetLevelResult(decimal desiredLevel, TempLocations setLocation) :
            base(CommandUrls.HvacSetTemp)
        {
            string location;

            if (setLocation == TempLocations.Driver)
            {
                location = "driver_temp";
            }
            else
            {
                location = "passenger_temp";
            }

            FormValues.AddFormValue(location, desiredLevel.ToString());
        }
        public ActionResult AddMashov(string file_number, string isContinue, string form_ver)
        {
            // check if the momhee has this request
            UserData user = (UserData)this.Session["user"];

            if (!RequestManager.Manager.IsRequestAllowedForMomhee(user.Id, file_number))
            {
                return(RedirectToAction("RequestManage", "AdminGovExp"));
            }
            // add extra data of the request for the mashov page
            string where        = "file_number='" + file_number + "'";
            ViewData["request"] = RequestManager.Manager.GetAllWhere(where, null, 1, 1)[0];
            ViewData["names"]   = RequestManager.Manager.GetAllColNames();

            var temp = new Dictionary <string, string>();

            // check if continue
            if (isContinue != null && isContinue.ToLower() == "true")
            {
                // load the save file
                var    dataFile = Server.MapPath("~/App_Data/Mashovs/temp_" + file_number + ".json");
                string json     = System.IO.File.ReadAllText(@dataFile);
                temp = FormValues.LoadJson(json).Values;
            }
            else
            {
                Settings sett = Settings.GetSettings();
                temp["file_version"] = sett.MashovVersion.ToString();
            }
            // load the mashov form
            var mashovFile = Server.MapPath("~/App_Data/Forms/MashovForm_v_" + temp["file_version"] + ".xml");

            // add extra data for "pull from" fields
            temp["file_number"]  = file_number;
            temp["gov_exp_name"] = user.Name;
            temp["misrad_name"]  = user.Office;
            ViewData["temp"]     = temp;
            FormComponent mashovForm = FormManager.Manager.Load(mashovFile);

            if (isContinue != null && isContinue.ToLower() == "true")
            {
                // validate the filled in fields
                ValidateAllNotEmpty(temp, mashovForm);
            }
            return(View(mashovForm.FormComponents[0]));
        }
Esempio n. 17
0
        public void ProcessLoginForm()
        {
            WebAuthentication auth = WebAuthentication.Instance;

            if (auth.ProcessLoginForm("SprocketUsername", "SprocketPassword", "SprocketPreserveLogin"))
            {
                if (WebAuthentication.VerifyAccess(PermissionType.AccessAdminArea))
                {
                    WebUtility.Redirect("admin");
                }
                else
                {
                    auth.ClearAuthenticationCookie();
                }
            }
            FormValues.Set("login", "", null, true);
        }
Esempio n. 18
0
        public FormValues <TFormDetailViewModel> GetEntityValues(long entityId, string language)
        {
            var result = new FormValues <TFormDetailViewModel>();
            var entity = EntityHelper.Entity(entityId);

            var details = EntityHelper.GetDetails(entity, language, _localizationOptions.Value.DefaultRequestCulture.Culture.Name).ToList();
            var localizationFieldNames      = details.Where(o => o.Language != null).Select(o => o.Field);
            var localizationFilteredDetails = details.AsEnumerable().Where(o => !(localizationFieldNames.Contains(o.Field) && o.Language == null)).ToList();

            //kiểm tra Detail trong list có móc vào file(chứa "Suffix" == "url")
            //thêm các Detail vào list để bổ sung chi tiết(dimension, size,..etc)
            var tempDetails = new List <TEntityDetail>();

            foreach (var detail in localizationFilteredDetails.Where(o => o.Suffix == AppKey.FileUrlPropertyName))
            {
                var fileEntity = _mediaHelper.Entity(detail.Value, true);
                if (fileEntity != null)
                {
                    foreach (var fileDetail in fileEntity.Details)
                    {
                        if (fileDetail.Field == AppKey.FileUrlPropertyName)
                        {
                            continue;
                        }

                        var tempDetail = detail.Clone() as TEntityDetail;
                        tempDetail.Suffix = fileDetail.Field;
                        tempDetail.Value  = fileDetail.Value;

                        tempDetails.Add(tempDetail);
                    }
                }
            }
            localizationFilteredDetails.AddRange(tempDetails);

            result.Meta = new Dictionary <string, string>()
            {
                { "id", entityId.ToString() },
                { "name", entity.Name.ToString() },
                { "entityTypeId", entity.EntityTypeId?.ToString() }
            };
            result.Details = FormUtitities.EntityDetailsToFieldValues <TEntityDetail, TFormDetailViewModel>(localizationFilteredDetails);

            return(result);
        }
Esempio n. 19
0
 /// <summary>
 /// Sets a form value
 /// </summary>
 /// <param name="inputName">Form element name</param>
 /// <param name="inputValue">Form element value</param>
 /// <returns>Boolean indicating if form element was set</returns>
 public bool SetValue(string inputName, string inputValue)
 {
     if (FormValues != null)
     {
         if (FormValues[inputName] != null)
         {
             FormValues[inputName] = inputValue;
         }
         else
         {
             FormValues.Add(inputName, inputValue);
         }
         return(true);
     }
     else
     {
         return(false);
     }
 }
Esempio n. 20
0
        private async Task<HttpResponseMessage> SendRequest(HttpMethod httpMethod, string url, FormValues formValues)
        {
            var request = new HttpRequestMessage(httpMethod, url);
            request.Headers.Add("Accept-Language", "en-US");
            request.Headers.Add("cookie", _cookies.Select(c => c.Key + "=" + c.Value.Value));
            if (formValues != null) request.Content = new FormUrlEncodedContent(formValues);

            if (url.StartsWith("http") && request.RequestUri.Host != "localhost")
            {
                using (var handler = new HttpClientHandler())
                using (var client = new HttpClient(handler))
                {
                        ResponseMsg = await client.GetAsync(request.RequestUri.ToString());
                }
            }
            else
            {
                ResponseMsg = await _client.SendAsync(request);
            }
            if(!url.StartsWith("https://accounts.google.com/o/oauth2/auth"))
                _cookies.Add(ResponseMsg);
            if (ResponseMsg.Headers.Location != null)
            {
                return await Get(ResponseMsg.Headers.Location.OriginalString);
            }
            Html = await ResponseMsg.Content.ReadAsStringAsync();

            try
            {
                HtmlDocument = Html.StartsWith("<!") ? XDocument.Parse(Html) : Html.StartsWith("{") ? new XDocument() : XDocument.Parse("<root>" + Html + "</root>");
            }
            catch (Exception e)
            {
                if (url.StartsWith("http://accounts") || url.StartsWith("/"))
                {
                    Debugger.Launch();
                    throw new Exception("Not a Xhtml Document", e);
                }

            }
            return ResponseMsg;
        }
Esempio n. 21
0
        public ActionResult Index(FormValues model)
        {
            Calculator calc = new Calculator();

            string message = "";
            string opText  = "";

            // Verdien av radio-knappene (InputValues.Operator) blir sendt til Calculator.Operations-metoden, og bestemmer hvilken regneoperasjon som blir gjennomført
            // Verdien av de to input-boksene blir sendt
            double result = calc.Operations(model.Operator, model.Input1, model.Input2, out message, out opText);

            ViewBag.Result  = result;
            ViewBag.Message = message;
            ViewBag.OpText  = opText;

            ViewBag.Input1 = model.Input1;
            ViewBag.Input2 = model.Input2;

            return(View());
        }
Esempio n. 22
0
 public static FormValues FormValues(this XDocument htmlDocument, int formIndex = 1)
 {
     var nodes = htmlDocument.Descendants("form").ElementAt(formIndex - 1).Descendants("input");
     var kv = new FormValues();
     foreach (var node in nodes)
     {
         var name = node.Attribute("name")?.Value;
         if (name != null)
         {
             if (kv.ContainsKey(name))
             {
                 kv[name] = WebUtility.HtmlDecode(node.Attribute("value")?.Value ?? "");
             }
             else
             {
                 kv.Add(name, WebUtility.HtmlDecode(node.Attribute("value")?.Value ?? ""));
             }
         }
     }
     return kv;
 }
Esempio n. 23
0
        public DynamicForm GetFormFor(long taxonomyId)
        {
            var entity = _taxEntityHelper.Entity(taxonomyId);

            var form = GetForm(entity.TaxonomyTypeId);

            form.Meta.Add(new FormField
            {
                Status = FieldStatus.Hidden,
                Name   = "id"
            });

            form.Meta.Add(new FormField
            {
                Status = FieldStatus.Hidden,
                Name   = AppKey.ParentId
            });

            var formValues = new FormValues();

            formValues.Meta = new Dictionary <string, string>()
            {
                { "id", entity.Id.ToString() },
                { AppKey.ParentId, entity.ParentId.ToString() },
                { AppKey.TaxonomyTypeId, entity.TaxonomyTypeId.ToString() },
            };

            var entityDetails = _taxEntityHelper.GetDetails(entity);

            formValues.Details = new Dictionary <string, string>();
            foreach (var item in entityDetails)
            {
                formValues.Details.Add(item.Field, item.Value);
            }

            form.InitialValues = formValues;

            return(form);
        }
Esempio n. 24
0
        public void Save(Stream stream, bool flatten)
        {
            PdfStamper stamper = null;

            try
            {
                PdfReader reader = new PdfReader(FileName);
                if (RemoveUsageRights)
                {
                    reader.RemoveUsageRights();
                }

                stamper = new PdfStamper(reader, stream);

                if (FormValues != null)
                {
                    AcroFields formFields = stamper.AcroFields;
                    foreach (FormField field in FormValues.GetValues())
                    {
                        formFields.SetField(field.Name, field.Value);
                    }
                }

                if (MetaData != null)
                {
                    stamper.MoreInfo    = MetaData.ToHashtable();
                    stamper.XmpMetadata = MetaData.ToByteArray();
                }

                stamper.FormFlattening = flatten;
            }
            finally
            {
                if (stamper != null)
                {
                    stamper.Close();
                }
            }
        }
Esempio n. 25
0
        private FormValues GetFormValueFor(FileEntity entity)
        {
            var formValues = new FormValues();

            formValues.Meta = new Dictionary <string, string>()
            {
                { "id", entity.Id.ToString() }
            };
            formValues.Details = new Dictionary <string, string>();

            var host = $"{_context.HttpContext.Request.Scheme}://{_context.HttpContext.Request.Host}";

            var entityDetails = _entityHelper.GetDetails(entity);
            var details       = entityDetails.ToDictionary(o => o.Field, o => o.Value);

            foreach (var detail in details)
            {
                var value = detail.Value;

                if (detail.Key.StartsWith("url"))
                {
                    value = $"{host}/{detail.Value}";
                }

                formValues.Details.Add(detail.Key, value);
            }

            formValues.TaxonomyTypes = new Dictionary <long, Dictionary <long, bool> >();
            var taxonomyTypesViewModels = _taxonomyHelper.GetTaxonomiesTypeViewModels(entity.EntityTypeId, true);

            foreach (var taxonomyTypeViewModel in taxonomyTypesViewModels)
            {
                var relateTaxonomies = _entityTaxonomyRelationHelper.GetTaxonomiesForEntity(entity.Id, taxonomyTypeViewModel.Id);
                formValues.TaxonomyTypes.Add(taxonomyTypeViewModel.Id, relateTaxonomies.ToDictionary(o => o.TaxonomyId, o => true));
            }

            return(formValues);
        }
        public ActionResult AddMashov(FormValues fTV)
        {
            // check if the momhee has this request
            UserData user = (UserData)this.Session["user"];

            if (!RequestManager.Manager.IsRequestAllowedForMomhee(user.Id, fTV.Values["file_number"]))
            {
                return(RedirectToAction("RequestsManage", "AdminGovExp"));
            }

            // check if submit or save
            var isSubmit = !fTV.Values.ContainsKey("isSave") || fTV.Values["isSave"] == "false" ? true : false;

            if (isSubmit)
            {
                // validate field types
                var           mashovFile = Server.MapPath("~/App_Data/Forms/MashovForm_v_" + fTV.Values["file_version"] + ".xml");
                FormComponent mashovForm = FormManager.Manager.Load(mashovFile);
                if (!ValidateAll(fTV, mashovForm))
                {
                    // incorrect types, don't save mashov
                    return(RedirectToAction("RequestsManage", "AdminGovExp"));
                }
            }

            // save the mashov as Json file
            string jsonPath = isSubmit ? "mashov_" : "temp_";

            jsonPath += fTV.Values["file_number"];
            var    dataFile = Server.MapPath("~/App_Data/Mashovs/" + jsonPath + ".json");
            string json     = fTV.GetJson();

            System.IO.File.WriteAllText(@dataFile, json);
            // link the mashov to the requests data base row of this request
            RequestManager.Manager.UpdateMashov(fTV.Values["file_number"], jsonPath, fTV.Values["file_version"]);
            return(RedirectToAction("RequestsManage", "AdminGovExp"));
        }
Esempio n. 27
0
        public HttpResponseMessage FormPost(FormValues form)
        {
            var host = Request.Headers.Host;

            /*
             * Lite saftey stuff. Rätt host, max 254 läng på email o typ max 70 på namn(?)
             * */
            Session.Store(form);
            Session.SaveChanges();

            var responseObj = new NameValueCollection();

            responseObj.Add("yea", "yea");
            var json = JsonConvert.SerializeObject(responseObj);

            var response = new HttpResponseMessage
            {
                Content    = new StringContent(json),
                StatusCode = HttpStatusCode.OK
            };

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return(response);
        }
 internal ChargeSetLevelResult(int desiredPercent) :
     base(CommandUrls.ChargeSetBatteryLevel)
 {
     FormValues.AddFormValue("percent", desiredPercent.ToString());
 }
 public HvacSetSteeringWheelHeaterResult(int turnOn)
     : base(CommandUrls.HvacSetSteeringWheelHeater)
 {
     FormValues.AddFormValue("on", (turnOn == 0 ? "false" : "true"));
 }
Esempio n. 30
0
 public bool HasValueFor(Metric metric)
 {
     return(FormValues.Select(v => v.Metric).Contains(metric));
 }
 public void Upgrade(FormValues formValues)
 {
 }
 public HvacSetSeatHeaterResult(SeatHeaterPositions position, int level) :
     base(CommandUrls.HvacSetSeatHeater)
 {
     FormValues.AddFormValue("heater", ((int)position).ToString());
     FormValues.AddFormValue("level", level.ToString());
 }