Ejemplo n.º 1
0
        /// <summary> Parses a single FormPost object from json. </summary>
        public static FormPost FromJson(JToken json)
        {
            if (json == null)
            {
                return(null);
            }

            try
            {
                FormPost obj = new FormPost();

                obj.RequestVerificationToken = json[key_token] != null ? json[key_token].Value <string>() : null;

                JEnumerable <JProperty> properties = json.Children <JProperty>();

                obj.Metadata = new Metadata();
                foreach (JProperty prop in properties.Where(x => x.Name.StartsWith(prefix_metadata)))
                {
                    obj.Metadata[prop.Name.Substring(prefix_metadata.Length + 1)] = prop.Value.Value <object>();
                }

                obj.Data = new Dictionary <string, string>();
                foreach (JProperty prop in properties.Where(x => x.Name.StartsWith(prefix_data)))
                {
                    obj.Data[prop.Name.Substring(prefix_data.Length + 1)] = prop.Value.Value <string>();
                }

                return(obj);
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 2
0
        public JsonResult PostData(FormPost formPost)
        {
            var parent = new Parent
            {
                FatherName = formPost.FirstName,
                ContactNo  = formPost.ContactNo,
                EmailID    = formPost.Email
            };

            this.recordDbContext.parents.Add(parent);
            this.recordDbContext.SaveChanges();
            if (parent.ParentID > 0)
            {
                var children = new List <Child>();
                for (int i = 0; i < formPost.childNames.Length; i++)
                {
                    children.Add(new Child
                    {
                        ChildName = formPost.childNames[i],
                        Dob       = Convert.ToDateTime(formPost.childDobs[i]),
                        ParentID  = parent.ParentID
                    });
                }
                this.recordDbContext.children.AddRange(children);
                this.recordDbContext.SaveChanges();
            }
            return(Json(new {
                Msg = "Record Inserted successfully",
                Status = HttpStatusCode.Created
            }));
        }
        private static void PostToHW(object j, object i)
        {
            string ip        = i as string;
            string json      = j as string;
            var    formDatas = new List <FormItemModel>();

            //添加文本
            formDatas.Add(new FormItemModel()
            {
                Key   = "BlackCell-Position",
                Value = json // "id-test-id-test-id-test-id-test-id-test-"
            });

            //提交表单
            try
            {
                AIThermometerAPP.Instance().blackcell_pos_error = true;
                var result = FormPost.PostForm("http://" + ip + ":9300/config", formDatas);
                AIThermometerAPP.Instance().ResetBlackCell();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("post to hw error", ex);
            }
        }
Ejemplo n.º 4
0
        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            string ip        = e.Argument as string;
            var    formDatas = new List <FormItemModel>();

            // 文件名
            formDatas.Add(new FormItemModel()
            {
                Key   = "",
                Value = "",
            });

            try
            {
                //提交表单
                var result = FormPost.PostForm("http://" + ip + ":9300/config", null);
                //cameraInfo.IP = ip.Text;
                CameraResponse cr = JsonHelper.FromJSON <CameraResponse>(result);

                Console.WriteLine(result);
                LogHelper.WriteLog(result);
                e.Result = cr;
            }
            catch (Exception)
            {
                e.Result = null;
            }
        }
Ejemplo n.º 5
0
        public ActionResult SavePersonForm(FormPost postData)
        {
            Form form = this.GetCreatePeopleForm();

            form.InjectFormData(postData.Data);

            FormValidator fv = new FormValidator();

            if (!fv.Validate(form))
            {
                return(Json(new { success = false, message = string.Join("<br/>", fv.Results.Select(x => x.Message)) }));
            }

            People person = new People();

            if (postData.Metadata.HasKey("edit") && postData.Metadata.Value <bool>("edit"))
            {
                int personId = postData.Metadata.Value <int>("personId");
                person = pMan.GetPerson(personId);
            }

            person.FirstName    = form.Element <Input>(1).Value;
            person.LastName     = form.Element <Input>(2).Value;
            person.EmailAddress = form.Element <Input>(3).Value;
            person.DateOfBirth  = DateTime.Parse(form.Element <Input>(4).Value);

            pMan.SavePerson(person);

            return(Json(new { success = true, message = "saved person" }));
        }
        public ActionResult SaveForm([FromBody] FormPost formBody)
        {
            if (formBody is null)
            {
                throw new ArgumentNullException(nameof(formBody));
            }

            JsonForm toSave;

            using (IWriteContext context = this.FormRepository.WriteContext())
            {
                if (formBody.Id != 0)
                {
                    toSave = this.FormRepository.Find(formBody.Id) ?? throw new NullReferenceException($"Can not find form with Id {formBody.Id}");
                }
                else
                {
                    toSave = new JsonForm();
                }

                toSave.FormData = formBody.Formhtml;

                this.FormRepository.AddOrUpdate(toSave);
            }

            JsonForm SavedForm = this.FormRepository.Find(toSave.Guid);

            return(new JsonResult(new { Id = SavedForm._Id }));
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Constructs a list item to be added to a list
 /// </summary>
 /// <param name="label">The text to be displayed within the LI tags</param>
 public NavItem(FormPost formPost) : base(formPost)
 {
     this.className = "NAVITEM";
     this.label     = "NAVITEM";
     this.attributes.Add("href", "#");
     this.anchor = new ANCHOR(this, "NAVITEM");
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Create a FORMPOST using the given posted values
        /// https://stackoverflow.com/questions/114983/given-a-datetime-object-how-do-i-get-an-iso-8601-date-in-string-format
        /// </summary>
        /// <param name="formPost"></param>
        /// <returns></returns>
        public override async Task <ActionResult> Create(FormPost formPost)
        {
            // Set formPost attributes where applicable
            formPost.formId           = formPost.id;
            formPost.id               = 0; // Id will be appended
            formPost.authorId         = User.Identity.Name;
            formPost.dateCreated      = DateTime.UtcNow.ToLocalTime();
            formPost.dateLastModified = DateTime.UtcNow.ToLocalTime();
            formPost.resultsToXml();

            // Attempt to save the form to the database
            try {
                // Save the object
                getObjectDbContext().FormPosts.Add(formPost);
                int success = getObjectDbContext().SaveChanges();
                // Return the success response
                return(Json(new Payload(
                                1, "FORMPOST", formPost,
                                formPost.getMessage()
                                )));
            } catch (Exception e) {
                var message = e.Message;
                return(Json(new Payload(0, e, "FormPostController.submit(" + e.GetType() + ")" + formPost.getMessage() + "\n\n" + e.Message)));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Attempt to add the given Word to the Dictionary via FormPost
        /// </summary>
        /// <param name="word"></param>
        /// <returns>A Payload containing server response</returns>
        private Payload addWordFormPost(string word)
        {
            try {
                FormPost formPost = new FormPost();
                formPost.id       = 2; //
                formPost.formId   = 2;
                formPost.authorId = User.Identity.Name;
                //formPost.label = "Word";
                formPost.status           = 1;
                formPost.dateCreated      = DateTime.UtcNow.ToLocalTime();
                formPost.dateLastModified = DateTime.UtcNow.ToLocalTime();
                formPost.results          = new List <FormValue>();
                formPost.results.Add(new FormValue("value", word));
                formPost.resultsToXml();

                getObjectDbContext().FormPosts.Add(formPost);
                int success = getObjectDbContext().SaveChanges();

                return(new Payload(formPost.id, "Successfully added Word '" + word + "' as a FormPost (FormId:2, new WordId: " + formPost.id + ")"));
            } catch (Exception e) {
                return(new Payload(
                           0, e
                           , "Unknown exception for Word '" + word + "'<br><br>" + e.Message.ToString()));
            }
        }
        public async Task <ActionResult <FormPost> > Create([FromBody] FormPost model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(model));
            }
            Form form = new Form();
            await db.Form.AddAsync(AssignsControllers.AssigForm(model, form));

            try
            {
                await db.SaveChangesAsync();
            }
            catch (System.Exception err)
            {
                return(BadRequest(new {
                    ok = false,
                    err = err.InnerException.Message
                }));
            }

            return(Ok(new {
                ok = true,
                form
            }));
        }
Ejemplo n.º 11
0
        private bool UpdateCameraFW(string file_name, string update_fpath)
        {
            if (ci.state == CamContectingState.ONLINE)
            {
                var formDatas = new List <FormItemModel>();

                // 文件名
                formDatas.Add(new FormItemModel()
                {
                    Key         = "File",
                    Value       = "",
                    FileName    = file_name,
                    FileContent = File.OpenRead(update_fpath)
                });

                try
                {
                    //提交表单
                    var result = FormPost.PostForm("http://" + ci.IP + ":9301/Update", formDatas);
                    //cameraInfo.IP = ip.Text;
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
            return(true);
        }
        public async Task <ActionResult <FormPost> > Update([FromBody] FormPost model, int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(model));
            }
            Form form = await db.Form
                        .Where(k => k.id_form == id)
                        .FirstOrDefaultAsync();

            AssignsControllers.AssigForm(model, form);
            if (form == null)
            {
                return(NotFound(new {
                    ok = false,
                    err = "The id " + id + " does not exist in the records"
                }));
            }
            try
            {
                await db.SaveChangesAsync();
            }
            catch (System.Exception err)
            {
                return(BadRequest(new {
                    ok = false,
                    err = err.InnerException.Message
                }));
            }

            return(Ok(new {
                ok = true,
                form
            }));
        }
Ejemplo n.º 13
0
        public async Task <ActionResult> ResetPassword(FormPost model)
        {
            try {
                var formResults = model.resultsToDictionary();
                var code        = formResults["Code"].ToString();
                var password    = formResults["Password"].ToString();
                var email       = formResults["Email"].ToString();

                var user = await UserManager.FindByNameAsync(email);

                if (user == null)
                {
                    // Don't reveal that the user does not exist
                    //return RedirectToAction("ResetPasswordConfirmation", "Account");
                    return(Json(new Payload(5, "InvalidResetPasswordAttempt", model), JsonRequestBehavior.AllowGet));
                }
                var result = await UserManager.ResetPasswordAsync(user.Id, code, password);

                if (result.Succeeded)
                {
                    //return RedirectToAction("ResetPasswordConfirmation", "Account");
                    return(Json(new Payload(1, "MODEL", "Password reset success")));
                }
                else
                {
                    return(Json(new Payload(2, "MODEL", "Password reset failed")));
                }
            } catch (Exception e) {
                return(Json(new Payload(2, e, "An exception occurred trying to reset a password")));
            }
            //AddErrors(result);
            //return View();
        }
Ejemplo n.º 14
0
        public async Task <ActionResult> ForgotPassword(FormPost model, string returnUrl)
        {
            try {
                var formResults = model.resultsToDictionary();
                var email       = formResults["Email"].ToString();
                var user        = await UserManager.FindByNameAsync(email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    //return View("ForgotPasswordConfirmation");
                    return(Json(new Payload(5, "InvalidForgotPasswordAttempt", model), JsonRequestBehavior.AllowGet));
                }
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code, email = user.Email, resetpassword = 1 }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                //return RedirectToAction("ForgotPasswordConfirmation", "Account");
                return(Json(new Payload(1, "MODEL", "Forgot Password notification sent")));
            } catch (Exception e) {
                return(Json(new Payload(2, e, "An exception occurred trying to validate a forgotten password")));
            }
        }
Ejemplo n.º 15
0
 private void должностьToolStripMenuItem_Click(object sender, EventArgs e)
 {
     using (var form = new FormPost())
     {
         form.ShowDialog();
     }
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Constructs an ARTICLE with the given id and label attributes already set
 /// </summary>
 /// <param name="element"></param>
 /// <param name="formPost"></param>
 public Container(string element, FormPost formPost) : base(
         element, new MODEL()
         )
 {
     this.dateCreated      = DateTime.UtcNow.ToLocalTime();
     this.dateLastModified = DateTime.UtcNow.ToLocalTime();
     this.updateContainerModel(formPost);
 }
Ejemplo n.º 17
0
            /// <summary>
            /// Custom implementation of ChallengeResult for SPA
            /// </summary>
            /// <param name="formPost"></param>
            public ChallengeResult(FormPost formPost)
            {
                Dictionary <string, object> results = formPost.resultsToDictionary();

                LoginProvider = results["provider"].ToString();
                RedirectUri   = results["redirectUri"].ToString();
                UserId        = results["userId"].ToString();
            }
Ejemplo n.º 18
0
        public ActionResult DeleteConfirmed(string id)
        {
            FormPost formPost = db.FormPosts.Find(id);

            db.FormPosts.Remove(formPost);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 创建Http访问类
        /// </summary>
        /// <returns></returns>
        public FormPost GetFormPost()
        {
            FormPost post = new FormPost();

            post.RequestHead.Timeout = 10000;

            return(post);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Instantiate a Container using List defaults
        /// </summary>
        /// <returns></returns>
        public override Container make(FormPost formPost = null)
        {
            var obj = (formPost == null)
                ? new THUMBNAIL()
                : new THUMBNAIL(formPost);

            obj.setAuthorId(User.Identity.Name);
            return(obj);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Instantiate a Container using Main defaults
        /// </summary>
        /// <returns></returns>
        public override Container make(FormPost formPost = null)
        {
            var obj = (formPost == null)
                ? new FORMELEMENTGROUP()
                : new FORMELEMENTGROUP(formPost);

            obj.setAuthorId(User.Identity.Name);
            return(obj);
        }
Ejemplo n.º 22
0
 public ActionResult Edit([Bind(Include = "IdFormPost,Form")] FormPost formPost)
 {
     if (ModelState.IsValid)
     {
         db.Entry(formPost).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(formPost));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Sets the value of the target object based on the given formPost values
        /// </summary>
        /// <param name="formPost">FormPost</param>
        /// <returns>A Json Object</returns>
        public override async Task <ActionResult> Set(FormPost formPost)
        {
            try {
                // Extract values from FormPost
                formPost.resultsToXml();
                int id = formPost.parseInt("id", -1);

                // Retrieve the record from the database
                ObjectDBContext ctx   = getObjectDbContext();
                var             model = select(ctx, id);

                // Set new values
                int result = 0;
                if (model != null)
                {
                    if (model.authorId == User.Identity.Name || model.shared == 1)
                    {
                        model.status = 1;

                        model.updateContainerModel(formPost);
                        model.dateLastModified = DateTime.UtcNow.ToLocalTime();

                        // Save the object
                        db.dbSets[this.className].Add(model);                             // ctx.Containers.Add(model);
                        ctx.Entry(model).State = System.Data.Entity.EntityState.Modified; // Critical
                        result = ctx.SaveChanges();

                        // Return the success response along with the message body
                        return(Json(new Payload(
                                        1, this.className, model
                                        //"Successfully set " + this.className + " (" + model.id + "," + id + ")"
                                        ), JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        return(Json(new Payload(
                                        0, "You are not authorized to modify this " + this.className + "(" + id + ")"
                                        ), JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    return(Json(new Payload(
                                    0, "Failed to retrieve " + this.className + "(" + id + ").  The request returned null."
                                    ), JsonRequestBehavior.AllowGet));
                }
            } catch (Exception e) {
                return(Json(new Payload(
                                0, e,
                                "Unknown exception for " + this.className + "<br><br>"
                                + e.Message.ToString()), JsonRequestBehavior.AllowGet
                            ));
            }
        }
Ejemplo n.º 24
0
        public void Authenticate()
        {
            //baseUrl = "http://localhost:5000/NbicDocumentStoreApi/api/DataDelivery";

            var post = new FormPost($"{baseUrl}/Authenticate");

            post.Add("username", "");
            post.Add("password", "");

            post.Execute();
        }
Ejemplo n.º 25
0
        public ActionResult Create([Bind(Include = "IdFormPost,Form")] FormPost formPost)
        {
            if (ModelState.IsValid)
            {
                db.FormPosts.Add(formPost);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(formPost));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Instantiate a Container using Main defaults
        /// </summary>
        /// <returns></returns>
        public override Container make(FormPost formPost = null)
        {
            var obj = (formPost == null)
                ? new MAIN()
                : new MAIN(formPost);

            obj.dateCreated      = DateTime.UtcNow.ToLocalTime();
            obj.dateLastModified = DateTime.UtcNow.ToLocalTime();

            obj.setAuthorId(User.Identity.Name);
            return(obj);
        }
Ejemplo n.º 27
0
        public void UploadGrid()
        {
            //baseUrl = "http://*****:*****@"AreaLayer\AdministrativtOmraadeKartTest.xml"));
            post.Execute();
        }
Ejemplo n.º 28
0
 public async Task <ActionResult> Submit(FormPost formPost)
 {
     try { // @see https://stackoverflow.com/a/32098348/722785
         var ct = DependencyResolver.Current.GetService <FormPostController>();
         ct.ControllerContext = new ControllerContext(this.Request.RequestContext, ct);
         return(await ct.Create(formPost));
     } catch (Exception e) {
         return(Json(new Payload(0, e,
                                 "FormController.Submit(): Unable to create FormPost\n" + e.ToString() + "\n\n" +
                                 e.Message.ToString()))); //, JsonRequestBehavior.AllowGet
     }
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Sets Container Model values based on the given FormPost
 /// </summary>
 /// <param name="formPost"></param>
 public void updateContainerModel(FormPost formPost)
 {
     formPost.resultsToXml();
     this.subsections      = formPost.parseString("subsections", "0");
     this.label            = formPost.parseString("label");
     this.id               = formPost.parseInt("id", -1);
     this.attributesId     = formPost.parseInt("attributesId");
     this.dataId           = formPost.parseInt("dataId");
     this.metaId           = formPost.parseInt("metaId");
     this.shared           = formPost.parseInt("shared");
     this.isPublic         = formPost.parseInt("isPublic");
     this.dateLastModified = DateTime.UtcNow.ToLocalTime();
 }
Ejemplo n.º 30
0
        /// <summary>
        /// 使用get来调用Web
        /// </summary>
        /// <returns></returns>
        public string GetData()
        {
            FormPost   post = GetFormPost();
            APIResault ret  = null;


            string rurl = GetFullGetUrl();
            string res  = post.GetData(rurl);



            return(res);
        }