Exemplo n.º 1
0
		/// <summary>
		/// 获取表单字段的html
		/// </summary>
		public string Build(FormField field, Dictionary<string, string> htmlAttributes) {
			var provider = Application.Ioc.Resolve<FormHtmlProvider>();
			var attribute = (CaptchaFieldAttribute)field.Attribute;
			var html = new HtmlTextWriter(new StringWriter());
			// 控件组
			html.AddAttribute("class", "input-group");
			html.RenderBeginTag("div");
			// 输入框
			foreach (var pair in provider.FormControlAttributes) {
				html.AddAttribute(pair.Key, pair.Value);
			}
			html.AddAttribute("name", field.Attribute.Name);
			html.AddAttribute("value", (field.Value ?? "").ToString());
			html.AddAttribute("type", "text");
			html.AddAttribute("placeholder", new T(attribute.PlaceHolder));
			foreach (var pair in htmlAttributes) {
				html.AddAttribute(pair.Key, pair.Value);
			}
			html.RenderBeginTag("input");
			html.RenderEndTag();
			// 验证码图片
			html.AddAttribute("class", "input-group-addon");
			html.RenderBeginTag("span");
			html.AddAttribute("alt", new T("Captcha"));
			html.AddAttribute("class", "captcha");
			html.AddAttribute("src", "/captcha?key=" + attribute.Key);
			html.AddAttribute("title", new T("Click to change captcha image"));
			html.RenderBeginTag("img");
			html.RenderEndTag(); // img
			html.RenderEndTag(); // span
			html.RenderEndTag(); // div
			return provider.FormGroupHtml(
				field, htmlAttributes, html.InnerWriter.ToString());
		}
Exemplo n.º 2
0
		/// <summary>
		/// 添加验证使用的html属性
		/// </summary>
		public void AddHtmlAttributes(
			FormField field, object validatorAttribute, IDictionary<string, string> htmlAttributes) {
			var attribute = (StringLengthAttribute)validatorAttribute;
			htmlAttributes["data-val-length"] = ErrorMessage(field, attribute);
			htmlAttributes["data-val-length-max"] = attribute.MaximumLength.ToString();
			htmlAttributes["data-val-length-min"] = attribute.MinimumLength.ToString();
		}
Exemplo n.º 3
0
		/// <summary>
		/// 验证值是否通过,不通过时抛出例外
		/// </summary>
		public void Validate(FormField field, object validatorAttribute, object value) {
			var str = value == null ? "" : value.ToString();
			var attribute = (StringLengthAttribute)validatorAttribute;
			if (str.Length < attribute.MinimumLength || str.Length > attribute.MaximumLength) {
				throw new HttpException(400, ErrorMessage(field, attribute));
			}
		}
Exemplo n.º 4
0
		/// <summary>
		/// 获取错误消息
		/// </summary>
		private string ErrorMessage(FormField field, StringLengthAttribute attribute) {
			if (attribute.MaximumLength == attribute.MinimumLength) {
				return string.Format(new T("Length of {0} must be {1}"),
					new T(field.Attribute.Name), attribute.MinimumLength);
			}
			return string.Format(new T("Length of {0} must between {1} and {2}"),
				new T(field.Attribute.Name), attribute.MinimumLength, attribute.MaximumLength);
		}
Exemplo n.º 5
0
		/// <summary>
		/// 解析提交的字段的值
		/// </summary>
		public object Parse(FormField field, string value) {
			// 检查验证码
			var attribute = (CaptchaFieldAttribute)field.Attribute;
			var captchaManager = Application.Ioc.Resolve<CaptchaManager>();
			if (!captchaManager.Check(attribute.Key, value)) {
				throw new HttpException(400, new T("Incorrect captcha"));
			}
			return value;
		}
Exemplo n.º 6
0
        public static FieldControl CreateControl(FormField field)
        {
            string typeName = string.Format("AgileEAP.EForm.{0}", field.ControlType);
            FieldControl control = null;
            try
            {
                control = Activator.CreateInstance(Type.GetType(typeName), new object[] { field }) as FieldControl;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            return control;
        }
Exemplo n.º 7
0
    public static void createBinding(FormField ff, ImportingBindingContainer ibc)
    {
        GRASPEntities db = new GRASPEntities();

        BindingContainer bc = new BindingContainer();

        bc.pushed = 0;
        bc.bType = ibc.bType.ToString();
        bc.maxRange = ibc.maxRange;
        bc.minRange = ibc.minRange;
        bc.value = ibc.value;
        bc.FormFieldAndBinding.Add(createFormFieldAndBinding(ff, bc.id));

        db.BindingContainer.Add(bc);
        db.SaveChanges();
    }
Exemplo n.º 8
0
    public static void createConstraints(FormField ff, ImportConstraintContainer icc)
    {
        GRASPEntities db = new GRASPEntities();

        ConstraintContainer cc = new ConstraintContainer();

        cc.pushed = 0;
        cc.cType = icc.cNumber.ToString();
        cc.maxRange = icc.maxRange;
        cc.minRange = icc.minRange;
        cc.value = icc.value;
        db.ConstraintContainer.Add(cc);
        db.SaveChanges();

        createconstraintAssociation(ff.id, cc.id);
    }
Exemplo n.º 9
0
		/// <summary>
		/// 获取表单字段的html
		/// </summary>
		/// <param name="field"></param>
		/// <param name="htmlAttributes"></param>
		/// <returns></returns>
		public string Build(FormField field, Dictionary<string, string> htmlAttributes) {
			var provider = Application.Ioc.Resolve<FormHtmlProvider>();
			var html = new HtmlTextWriter(new StringWriter());
			foreach (var pair in provider.FormControlAttributes) {
				html.AddAttribute(pair.Key, pair.Value);
			}
			html.AddAttribute("name", field.Attribute.Name);
			html.AddAttribute("value", (field.Value ?? "").ToString());
			html.AddAttribute("type", "hidden");
			foreach (var pair in htmlAttributes) {
				html.AddAttribute(pair.Key, pair.Value);
			}
			html.RenderBeginTag("input");
			html.RenderEndTag();
			return html.InnerWriter.ToString();
		}
Exemplo n.º 10
0
		/// <summary>
		/// 获取表单字段的html
		/// </summary>
		/// <param name="field"></param>
		/// <param name="htmlAttributes"></param>
		/// <returns></returns>
		public string Build(FormField field, Dictionary<string, string> htmlAttributes) {
			var provider = Application.Ioc.Resolve<FormHtmlProvider>();
			var attribute = (PasswordFieldAttribute)field.Attribute;
			var html = new HtmlTextWriter(new StringWriter());
			foreach (var pair in provider.FormControlAttributes) {
				html.AddAttribute(pair.Key, pair.Value);
			}
			html.AddAttribute("name", field.Attribute.Name);
			html.AddAttribute("value", (field.Value ?? "").ToString());
			html.AddAttribute("type", "password");
			html.AddAttribute("placeholder", new T(attribute.PlaceHolder));
			foreach (var pair in htmlAttributes) {
				html.AddAttribute(pair.Key, pair.Value);
			}
			html.RenderBeginTag("input");
			html.RenderEndTag();
			return provider.FormGroupHtml(
				field, htmlAttributes, html.InnerWriter.ToString());
		}
Exemplo n.º 11
0
		/// <summary>
		/// 获取表单字段的html
		/// </summary>
		public string Build(FormField field, Dictionary<string, string> htmlAttributes) {
			var provider = Application.Ioc.Resolve<FormHtmlProvider>();
			var html = new HtmlTextWriter(new StringWriter());
			html.AddAttribute("class", "switchery");
			foreach (var pair in provider.FormControlAttributes) {
				html.AddAttribute(pair.Key, pair.Value);
			}
			html.AddAttribute("name", field.Attribute.Name);
			if (field.Value as bool? == true) {
				html.AddAttribute("checked", null);
			}
			html.AddAttribute("type", "checkbox");
			foreach (var pair in htmlAttributes) {
				html.AddAttribute(pair.Key, pair.Value);
			}
			html.RenderBeginTag("input");
			html.RenderEndTag();
			return provider.FormGroupHtml(
				field, htmlAttributes, html.InnerWriter.ToString());
		}
        private static void HandleDateField(FormField formField)
        {
            if (formField.ControlMode == SPControlMode.Display)
            {
                return;
            }

            Control dateFieldControl = formField.Controls[0];
            if (dateFieldControl.Controls.Count > 0)
            {
                DateTimeControl dateTimeControl = (DateTimeControl)dateFieldControl.Controls[0].Controls[1];
                TextBox dateTimeTextBox = dateTimeControl.Controls[0] as TextBox;
                if (dateTimeTextBox != null)
                {
                    if (!string.IsNullOrEmpty(dateTimeTextBox.Text))
                    {
                        formField.Value = DateTime.Parse(dateTimeTextBox.Text, CultureInfo.CurrentCulture);
                    }
                }
            }
        }
Exemplo n.º 13
0
        private void UpdateField()
        {
            //One or more of the fields properties changed so we need to update the field data
            //which is stored in the annotation objects UserData
            FormField currentField = _ocrField;
            string    fieldType    = (currentField is TextFormField) ? "Text" : "Omr";

            switch (fieldType)
            {
            case "Text":
                if (!(currentField is TextFormField))
                {
                    currentField = new TextFormField();
                }

                //set text field options
                (currentField as TextFormField).EnableIcr = _chkEnableIcr.Checked;
                (currentField as TextFormField).EnableOcr = _chkEnableOcr.Checked;
                (currentField as TextFormField).Type      = _rbTextTypeChar.Checked ? TextFieldType.Character : TextFieldType.Numerical;
                break;

            case "Omr":
                if (!(currentField is OmrFormField))
                {
                    currentField = new OmrFormField();
                }

                //set omr field options
                if (_rbOMRWithFrame.Checked)
                {
                    (currentField as OmrFormField).FrameMethod = OcrOmrFrameDetectionMethod.WithFrame;
                }
                else if (_rbOMRWithoutFrame.Checked)
                {
                    (currentField as OmrFormField).FrameMethod = OcrOmrFrameDetectionMethod.WithoutFrame;
                }
                else if (_rbOMRAutoFrame.Checked)
                {
                    (currentField as OmrFormField).FrameMethod = OcrOmrFrameDetectionMethod.Auto;
                }

                if (_rbOMRSensitivityLowest.Checked)
                {
                    (currentField as OmrFormField).Sensitivity = OcrOmrSensitivity.Lowest;
                }
                else if (_rbOMRSensitivityLow.Checked)
                {
                    (currentField as OmrFormField).Sensitivity = OcrOmrSensitivity.Low;
                }
                else if (_rbOMRSensitivityHigh.Checked)
                {
                    (currentField as OmrFormField).Sensitivity = OcrOmrSensitivity.High;
                }
                else if (_rbOMRSensitivityHighest.Checked)
                {
                    (currentField as OmrFormField).Sensitivity = OcrOmrSensitivity.Highest;
                }
                break;
            }

            currentField.Bounds      = new LeadRect(Convert.ToInt32(_nudLeft.Value), Convert.ToInt32(_nudTop.Value), Convert.ToInt32(_nudWidth.Value), Convert.ToInt32(_nudHeight.Value));
            currentField.Name        = _txt_ColumnOptionsFieldName.Text;
            _chkDropoutWords.Checked = (currentField.Dropout & DropoutFlag.WordsDropout) == DropoutFlag.WordsDropout;
            _chkDropoutCells.Checked = (currentField.Dropout & DropoutFlag.CellsDropout) == DropoutFlag.CellsDropout;
        }
Exemplo n.º 14
0
    private static FormFieldAndBinding createFormFieldAndBinding(FormField ff, decimal p)
    {
        GRASPEntities db = new GRASPEntities();

        FormFieldAndBinding ffb = new FormFieldAndBinding();

        ffb.pushed = 0;
        ffb.bContainer_id = p;
        if(ff != null)
            ffb.fField_id = ff.id;

        db.FormFieldAndBinding.Add(ffb);
        db.SaveChanges();

        return ffb;
    }
Exemplo n.º 15
0
 /// <summary>
 /// 获取错误消息
 /// </summary>
 private string ErrorMessage(FormField field)
 {
     return(string.Format(new T("{0} format is incorrect"), new T(field.Attribute.Name)));
 }
Exemplo n.º 16
0
 public KeeFoxFieldForm(FormField ff) : this(ff.Name, ff.Value, ff.Id, ff.Type, ff.Page)
 {
 }
Exemplo n.º 17
0
        /// <summary>
        /// 提交form写入数据库
        /// </summary>
        /// <param name="jsonstr">传入json数据</param>
        /// <param name="context">返回结果</param>
        private void submit(string jsonstr, HttpContext context)
        {
            List<int> FieldID = new List<int>();   //字段ID
            List<int> FormID = new List<int>();  //表单ID
            List<string> FieldDesc = new List<string>(); //字段描述
            List<int> CSSStyleClass=new List<int>();  //样式类型
            List<string> Group = new List<string>();   //对应明细组名称
            List<int> GroupLineDataSetID = new List<int>();  //对应明细行数据集ID
            Dictionary<string, int> groups = new Dictionary<string, int>();  //明细组名称和ID对应字典

            XmlDocument doc = jsonToXML(jsonstr);  //json转换成XML

            XmlNodeList item = doc.SelectNodes("/root/items/item");   //获取字段
            XmlNodeList form = doc.SelectNodes("/root/form/item");  //获取表单
            XmlNodeList options = doc.SelectNodes("/root/options/item");    //获取选项
            XmlNodeList json = doc.SelectNodes("/root/json/item/items/item");  //获取明细组

            if (item.Count > 0)  //如有字段先增加字段
            {
                //增加字段,输出字段ID,字段描述,样式,明细组名称,明细行数据集ID
                FieldID = addFieldDict(out FieldDesc,out CSSStyleClass, out Group,out GroupLineDataSetID,item,options);
            }

            if (item.Count > 0 && options.Count > 0)
            {

            }

            if (form.Count > 0)
            {
                FormID = addFormBase(form);     //增加表单
                string s= addGroup(out groups, json, FormID[0]);  //增加明细组,输出对应字典
            }

            List<string> result = new List<string>();
            if (FieldID.Count() > 0 && FormID.Count() > 0)  //如果存在字段和表单,将字段增加到表单上
            {
                List<int> g = new List<int>();     //将明细行名称转成ID
                foreach (var i in Group)
                {
                    if (i != string.Empty)
                    {
                        g.Add(groups[i]);
                    }
                    else
                    {
                        g.Add(0);
                    }
                }

                FormField f = new FormField();
                f.FieldID = FieldID;
                f.FieldDesc = FieldDesc;
                f.CSSStyleClass = CSSStyleClass;
                f.FormID = FormID[0];
                f.GroupID = 0;
                f.IsDetail = 0;
                f.GroupLineDataSetID = GroupLineDataSetID;
                f.TargetGroupID = g;

                result= addFormField(f); //将元素添加到表单中

                context.Response.Write(result.Count);
            }
            else if (form.Count > 0)
            {
                context.Response.Write(FormID.Count);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Create an x:data form from the given XML form description
        /// </summary>
        /// <param name="x">x:data form to render</param>
        public XDataForm(jabber.protocol.x.Data x) : this()
        {
            if (x == null)
                throw new ArgumentException("x:data form must not be null", "x");

            m_type = x.Type;

            this.SuspendLayout();
            if (x.Title != null)
                this.Text = x.Title;
            if (m_type == XDataType.cancel)
            {
                lblInstructions.Text = "Form canceled.";  // TODO: Localize!
                lblInstructions.Resize += new EventHandler(lblInstructions_Resize);
                lblInstructions_Resize(lblInstructions, null);
            }
            else if (x.Instructions == null)
                lblInstructions.Visible = false;
            else
            {
                lblInstructions.Text = DeWhitespace(x.Instructions);
                lblInstructions.Resize += new EventHandler(lblInstructions_Resize);
                lblInstructions_Resize(lblInstructions, null);
            }

            pnlFields.SuspendLayout();
            Field[] fields = x.GetFields();
            m_fields = new FormField[fields.Length];
            for (int i=fields.Length-1; i>=0; i--)
            {
                m_fields[i] = new FormField(fields[i], this, i);
            }

            panel1.TabIndex = fields.Length;

            if (m_type != XDataType.form)
            {
                btnOK.Location = btnCancel.Location;
                btnCancel.Visible = false;
            }

            pnlFields.ResumeLayout(true);
            this.ResumeLayout(true);

            for (int i=0; i<fields.Length; i++)
            {
                if ((fields[i].Type != FieldType.hidden) &&
                    (fields[i].Type != FieldType.Fixed))
                    m_fields[i].Focus();
            }
        }
Exemplo n.º 19
0
        public Dictionary <string, List <string> > ExportValues(FormField field)
        {
            Dictionary <string, List <string> > values = new Dictionary <string, List <string> >();

            if (field is HtmlField || field is ExternalMediaField)
            {
                return(values); //These fields do not take user inputs.
            }
            if (field is CompositeFormField)
            {
                //exporting values from the header
                foreach (var child in (field as CompositeFormField).Header)
                {
                    Dictionary <string, List <string> > childValues = ExportValues(child);
                    foreach (var obj in childValues)
                    {
                        if (values.ContainsKey(obj.Key))
                        {
                            values[obj.Key].AddRange(obj.Value);
                        }
                        else
                        {
                            values.Add(obj.Key, obj.Value);
                        }
                    }
                }

                //exporting values from the child fields
                foreach (var child in (field as CompositeFormField).Fields)
                {
                    Dictionary <string, List <string> > childValues = ExportValues(child);
                    foreach (var obj in childValues)
                    {
                        if (values.ContainsKey(obj.Key))
                        {
                            values[obj.Key].AddRange(obj.Value);
                        }
                        else
                        {
                            values.Add(obj.Key, obj.Value);
                        }
                    }
                }

                //exporting values from the footer fields
                foreach (var child in (field as CompositeFormField).Footer)
                {
                    Dictionary <string, List <string> > childValues = ExportValues(child);
                    foreach (var obj in childValues)
                    {
                        if (values.ContainsKey(obj.Key))
                        {
                            values[obj.Key].AddRange(obj.Value);
                        }
                        else
                        {
                            values.Add(obj.Key, obj.Value);
                        }
                    }
                }
            }
            else
            {
                var vals = field.GetValues();
                //Melania
                if (typeof(OptionsField).IsAssignableFrom(field.GetType()))
                {
                    vals = field.GetOptionValues();
                }

                if (vals.Count() > 0)
                {
                    foreach (var val in vals)
                    {
                        if (values.ContainsKey(field.ReferenceLabel))
                        {
                            values[field.ReferenceLabel].Add(val.Value);
                        }
                        else
                        {
                            values.Add(field.ReferenceLabel, new List <string>()
                            {
                                val.Value
                            });
                        }
                    }
                }
                else
                {
                    values.Add(field.ReferenceLabel, new List <string>());
                }
            }

            return(values);
        }
Exemplo n.º 20
0
 public void Delete(FormField formField)
 {
     dbContext.Set <FormField>().Remove(formField);
     dbContext.SaveChanges();
 }
Exemplo n.º 21
0
 public void Update(FormField formField)
 {
 }
Exemplo n.º 22
0
 public void Insert(FormField formField)
 {
     dbContext.Set <FormField>().Add(formField);
     dbContext.SaveChanges();
 }
Exemplo n.º 23
0
        public async Task <JsonResult> GetSystemForm(string id)
        {
            string entityKey = "SystemForm_" + id + "_Entity";
            string nameKey   = "SystemForm_" + id + "_Name";
            string xmlKey    = "SystemForm_" + id + "_FormXML";
            string formXml   = await _distributedCache.GetStringAsync(xmlKey);

            ViewModels.Form form = new ViewModels.Form();
            form.id     = id;
            form.entity = await _distributedCache.GetStringAsync(entityKey);

            form.name = await _distributedCache.GetStringAsync(nameKey);

            form.formxml = formXml;
            form.tabs    = new List <ViewModels.FormTab>();

            var tabs = XDocument.Parse(formXml).XPathSelectElements("form/tabs/tab");

            if (tabs != null)
            {
                foreach (var tab in tabs)
                {
                    var     tabLabel     = tab.XPathSelectElement("labels/label");
                    string  description  = tabLabel.Attribute("description").Value;
                    string  tabId        = tabLabel.Attribute("id") == null ? "" : tabLabel.Attribute("id").Value;
                    Boolean tabShowLabel = tab.Attribute("showlabel").DynamicsAttributeToBoolean();
                    Boolean tabVisible   = tab.Attribute("visible").DynamicsAttributeToBoolean();

                    FormTab formTab = new FormTab();
                    formTab.id        = tabId;
                    formTab.name      = description;
                    formTab.sections  = new List <FormSection>();
                    formTab.showlabel = tabShowLabel;
                    formTab.visible   = tabVisible;

                    // get the sections
                    var sections = tab.XPathSelectElements("columns/column/sections/section");
                    foreach (var section in sections)
                    {
                        Boolean sectionShowLabel = section.Attribute("showlabel").DynamicsAttributeToBoolean();
                        Boolean sectionVisible   = section.Attribute("visible").DynamicsAttributeToBoolean();

                        FormSection formSection = new FormSection();
                        formSection.fields    = new List <FormField>();
                        formSection.id        = section.Attribute("id").Value;
                        formSection.showlabel = sectionShowLabel;
                        formSection.visible   = sectionVisible;

                        // get the fields.
                        var sectionLabels = section.XPathSelectElements("labels/label");

                        // the section label is the section name.
                        foreach (var sectionLabel in sectionLabels)
                        {
                            formSection.name = sectionLabel.Attribute("description").Value;
                        }
                        // get the cells.
                        var cells = section.XPathSelectElements("rows/row/cell");

                        foreach (var cell in cells)
                        {
                            FormField formField = new FormField();
                            // get cell visibility and showlabel
                            Boolean cellShowLabel = cell.Attribute("showlabel").DynamicsAttributeToBoolean();
                            Boolean cellVisible   = cell.Attribute("visible").DynamicsAttributeToBoolean();


                            formField.showlabel = cellShowLabel;
                            formField.visible   = cellVisible;

                            // get the cell label.


                            var cellLabels = cell.XPathSelectElements("labels/label");
                            foreach (var cellLabel in cellLabels)
                            {
                                formField.name = cellLabel.Attribute("description").Value;
                            }
                            // get the form field name.
                            var control = cell.XPathSelectElement("control");
                            if (!string.IsNullOrEmpty(formField.name) && control != null && control.Attribute("datafieldname") != null)
                            {
                                formField.classid       = control.Attribute("classid").Value;
                                formField.controltype   = formField.classid.DynamicsControlClassidToName();
                                formField.datafieldname = control.Attribute("datafieldname").Value;
                                formField.required      = control.Attribute("isrequired").DynamicsAttributeToBoolean();
                                formSection.fields.Add(formField);
                            }
                        }

                        formTab.sections.Add(formSection);
                    }

                    form.tabs.Add(formTab);
                }
            }
            else // single tab form.
            {
                FormTab formTab = new FormTab();
                formTab.name = "";
                form.tabs.Add(formTab);
            }

            return(Json(form));
        }
Exemplo n.º 24
0
 public SubmitRejestration(string name, FormField imie, FormField nazwisko, FormField email, FormField pass, FormField passRep)
 {
     this.Name     = name;
     this.imie     = imie;
     this.nazwisko = nazwisko;
     this.email    = email;
     this.pass     = pass;
     this.passRep  = passRep;
 }
Exemplo n.º 25
0
        public async Task <JsonResult> GetSystemForm(string formid)
        {
            // get the picklists.

            List <MicrosoftDynamicsCRMpicklistAttributeMetadata> picklistMetadata = null;

            try
            {
                picklistMetadata = _dynamicsClient.Entitydefinitions.GetEntityPicklists("adoxio_application").Value;
            }
            catch (Exception e)
            {
                _logger.LogError(e, "ERROR getting accounts picklist metadata");
            }

            // get the application mapping.

            ApplicationMapping applicationMapping = new ApplicationMapping();
            var systemForm = _dynamicsClient.Systemforms.GetByKey(formid);

            /*
             * string entityKey = "SystemForm_" + id + "_Entity";
             * string nameKey = "SystemForm_" + id + "_Name";
             * string xmlKey = "SystemForm_" + id + "_FormXML";
             * string formXml = await _distributedCache.GetStringAsync(xmlKey);
             */

            string formXml = systemForm.Formxml;

            ViewModels.Form form = new ViewModels.Form();
            form.id       = formid;
            form.tabs     = new List <ViewModels.FormTab>();
            form.sections = new List <ViewModels.FormSection>();

            var tabs = XDocument.Parse(formXml).XPathSelectElements("form/tabs/tab");

            if (tabs != null)
            {
                foreach (var tab in tabs)
                {
                    var     tabLabel     = tab.XPathSelectElement("labels/label");
                    string  description  = tabLabel.Attribute("description").Value;
                    string  tabId        = tabLabel.Attribute("id") == null ? "" : tabLabel.Attribute("id").Value;
                    Boolean tabShowLabel = tab.Attribute("showlabel").DynamicsAttributeToBoolean();
                    Boolean tabVisible   = tab.Attribute("visible").DynamicsAttributeToBoolean();

                    FormTab formTab = new FormTab();
                    formTab.id        = tabId;
                    formTab.name      = description;
                    formTab.sections  = new List <FormSection>();
                    formTab.showlabel = tabShowLabel;
                    formTab.visible   = tabVisible;

                    // get the sections
                    var sections = tab.XPathSelectElements("columns/column/sections/section");
                    foreach (var section in sections)
                    {
                        Boolean sectionShowLabel = section.Attribute("showlabel").DynamicsAttributeToBoolean();
                        Boolean sectionVisible   = section.Attribute("visible").DynamicsAttributeToBoolean();
                        if (section.Attribute("visible") == null)
                        {
                            sectionVisible = true; // default visibility to true if it is not specified.
                        }


                        FormSection formSection = new FormSection();
                        formSection.fields    = new List <FormField>();
                        formSection.id        = section.Attribute("id").Value;
                        formSection.showlabel = sectionShowLabel;
                        formSection.visible   = sectionVisible;

                        // get the fields.
                        var sectionLabels = section.XPathSelectElements("labels/label");

                        // the section label is the section name.
                        foreach (var sectionLabel in sectionLabels)
                        {
                            formSection.name = sectionLabel.Attribute("description").Value;
                        }
                        // get the cells.
                        var cells = section.XPathSelectElements("rows/row/cell");

                        foreach (var cell in cells)
                        {
                            FormField formField = new FormField();
                            // get cell visibility and showlabel
                            bool cellShowLabel = cell.Attribute("showlabel").DynamicsAttributeToBoolean();
                            bool cellVisible   = cell.Attribute("visible").DynamicsAttributeToBoolean();

                            // set the cell to visible if it is not hidden.
                            if (cell.Attribute("visible") == null)
                            {
                                cellVisible = true;
                            }

                            formField.showlabel = cellShowLabel;
                            formField.visible   = cellVisible;

                            // get the cell label.

                            if (formField.showlabel)
                            {
                                var cellLabels = cell.XPathSelectElements("labels/label");
                                foreach (var cellLabel in cellLabels)
                                {
                                    formField.name = cellLabel.Attribute("description").Value;
                                }
                            }
                            else
                            {
                                // use the section name.
                                formField.name   = formSection.name;
                                formSection.name = "";
                            }


                            // get the form field name.
                            var control = cell.XPathSelectElement("control");
                            if (!string.IsNullOrEmpty(formField.name) && control != null && control.Attribute("datafieldname") != null)
                            {
                                formField.classid     = control.Attribute("classid").Value;
                                formField.controltype = formField.classid.DynamicsControlClassidToName();
                                string datafieldname = control.Attribute("datafieldname").Value;
                                // translate the data field name
                                formField.datafieldname = applicationMapping.GetViewModelKey(datafieldname);

                                formField.required = control.Attribute("isrequired").DynamicsAttributeToBoolean();

                                if (formField.controltype.Equals("PicklistControl"))
                                {
                                    // get the options.
                                    var metadata = picklistMetadata.FirstOrDefault(x => x.LogicalName == datafieldname);

                                    formField.options = new List <OptionMetadata>();

                                    if (metadata == null)
                                    {
                                        formField.options.Add(new OptionMetadata()
                                        {
                                            label = "INVALID PICKLIST", value = 0
                                        });
                                    }
                                    else
                                    {
                                        MicrosoftDynamicsCRMoptionSet optionSet = null;
                                        // could be an OptionSet or a globalOptionSet.
                                        if (metadata.OptionSet != null)
                                        {
                                            optionSet = metadata.OptionSet;
                                        }
                                        else
                                        {
                                            optionSet = metadata.GlobalOptionSet;
                                        }
                                        if (optionSet != null)
                                        {
                                            foreach (var option in optionSet.Options)
                                            {
                                                int?   value = option.Value;
                                                string label = option.Label?.UserLocalizedLabel?.Label;
                                                if (value == null || label == null)
                                                {
                                                    formField.options.Add(new OptionMetadata()
                                                    {
                                                        label = "INVALID PICKLIST", value = 0
                                                    });
                                                }
                                                else
                                                {
                                                    formField.options.Add(new OptionMetadata()
                                                    {
                                                        label = label, value = value.Value
                                                    });
                                                }
                                            }
                                        }
                                    }
                                }
                                if (formField.datafieldname != null)
                                {
                                    formSection.fields.Add(formField);
                                }
                            }
                        }

                        formTab.sections.Add(formSection);
                        form.sections.Add(formSection);
                    }

                    form.tabs.Add(formTab);
                }
            }
            else // single tab form.
            {
                FormTab formTab = new FormTab();
                formTab.name = "";
                form.tabs.Add(formTab);
            }

            return(new JsonResult(form));
        }
Exemplo n.º 26
0
 protected internal virtual bool isBoolean(FormField formField)
 {
     return(BooleanFormType.TYPE_NAME.Equals(formField.TypeName));
 }
Exemplo n.º 27
0
        public void CreateWord_CreateFieldDropDownWindow_SetFieldDropDownWindow_Unprotect_Protect()
        {
            object path;                                               //文件路径变量
            string strContent;                                         //文本内容变量

            Microsoft.Office.Interop.Word.Application wordApp;         //Word应用程序变量
            Microsoft.Office.Interop.Word.Document    wordDoc;         //Word文档变量

            path    = directory + @"\MyWord.doc";                      //路径
            wordApp = new Microsoft.Office.Interop.Word.Application(); //初始化
                                                                       //如果已存在,则删除
            if (File.Exists((string)path))
            {
                File.Delete((string)path);
            }

            //由于使用的是COM库,因此有许多变量需要用Missing.Value代替
            Object Nothing = Missing.Value;

            wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //WdSaveFormat为Word文档的保存格式
            object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;


            wordApp.Selection.ParagraphFormat.LineSpacing = 12f;//设置文档的行间距

            //写入普通文本
            strContent = "                                                         \r\n";
            wordDoc.Paragraphs.Last.Range.Text = strContent;



            object unite = Microsoft.Office.Interop.Word.WdUnits.wdStory;

            wordApp.Selection.EndKey(ref unite, ref Nothing);

            Range currentLastRange = wordDoc.Paragraphs.Last.Range;

            currentLastRange.SetRange(1, 2);
            //Add dropDowmWindow
            wordDoc.Paragraphs.Last.Range.Text = "\r\n";
            FormField formField = wordApp.ActiveDocument.FormFields.Add(currentLastRange, WdFieldType.wdFieldFormDropDown);

            formField.DropDown.ListEntries.Add("Item0", 0);
            formField.DropDown.ListEntries.Add("Item1", 1);
            formField.DropDown.ListEntries.Add("Item2", 2);
            //Set dropDownWindow
            for (int i = 1; i <= formField.DropDown.ListEntries.Count; i++)
            {
                Regex regex = new Regex("Item2");

                regex.IsMatch(formField.DropDown.ListEntries[i].Name);

                if (regex.IsMatch(formField.DropDown.ListEntries[i].Name))
                {
                    formField.DropDown.Value = formField.DropDown.ListEntries[i].Index;
                }
            }

            //add 文字型窗体域
            wordDoc.Paragraphs.Last.Range.Paragraphs.Add();

            FormField textFormField = wordDoc.Paragraphs.Last.Range.FormFields.Add(wordDoc.Paragraphs.Last.Range, WdFieldType.wdFieldFormTextInput);

            textFormField.Result = "text form field";

            //add checkbox
            wordDoc.Paragraphs.Last.Range.Paragraphs.Add();
            currentLastRange.SetRange(12, 16);
            FormField checkboxFormField = wordDoc.Paragraphs.Last.Range.FormFields.Add(wordDoc.Paragraphs.Last.Range, WdFieldType.wdFieldFormCheckBox);

            checkboxFormField.CheckBox.Default = true;

            wordDoc.Protect(WdProtectionType.wdAllowOnlyFormFields, false, "", Type.Missing, Type.Missing);

            wordDoc.Unprotect(string.Empty);
            //将wordDoc文档对象的内容保存为DOC文档
            wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //关闭wordDoc文档对象
            wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            //关闭wordApp组件对象
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
        }
        public async Task StartRecognizeCustomFormsWithoutLabelsCanParseMultipageFormWithBlankPage(bool useStream)
        {
            var client  = CreateFormRecognizerClient();
            var options = new RecognizeCustomFormsOptions()
            {
                IncludeFieldElements = true
            };
            RecognizeCustomFormsOperation operation;

            await using var trainedModel = await CreateDisposableTrainedModelAsync(useTrainingLabels : false);

            if (useStream)
            {
                using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceMultipageBlank);
                using (Recording.DisableRequestBodyRecording())
                {
                    operation = await client.StartRecognizeCustomFormsAsync(trainedModel.ModelId, stream, options);
                }
            }
            else
            {
                var uri = FormRecognizerTestEnvironment.CreateUri(TestFile.InvoiceMultipageBlank);
                operation = await client.StartRecognizeCustomFormsFromUriAsync(trainedModel.ModelId, uri, options);
            }

            RecognizedFormCollection recognizedForms = await operation.WaitForCompletionAsync();

            Assert.AreEqual(3, recognizedForms.Count);

            for (int formIndex = 0; formIndex < recognizedForms.Count; formIndex++)
            {
                var recognizedForm     = recognizedForms[formIndex];
                var expectedPageNumber = formIndex + 1;

                ValidateModelWithNoLabelsForm(
                    recognizedForm,
                    trainedModel.ModelId,
                    includeFieldElements: true,
                    expectedFirstPageNumber: expectedPageNumber,
                    expectedLastPageNumber: expectedPageNumber);

                // Basic sanity test to make sure pages are ordered correctly.

                if (formIndex == 0 || formIndex == 2)
                {
                    var expectedValueData = formIndex == 0 ? "300.00" : "3000.00";

                    FormField fieldInPage = recognizedForm.Fields.Values.Where(field => field.LabelData.Text.Contains("Subtotal:")).FirstOrDefault();
                    Assert.IsNotNull(fieldInPage);
                    Assert.IsNotNull(fieldInPage.ValueData);
                    Assert.AreEqual(expectedValueData, fieldInPage.ValueData.Text);
                }
            }

            var blankForm = recognizedForms[1];

            Assert.AreEqual(0, blankForm.Fields.Count);

            var blankPage = blankForm.Pages.Single();

            Assert.AreEqual(0, blankPage.Lines.Count);
            Assert.AreEqual(0, blankPage.Tables.Count);
        }
Exemplo n.º 29
0
        void rptFilterCriteria_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
            {
                SPField field = e.Item.DataItem as SPField;

                Literal ltrFieldName = e.Item.FindControl("ltrFieldName") as Literal;
                DropDownList ddlQUeryOpt = e.Item.FindControl("ddlQUeryOpt") as DropDownList;
                PlaceHolder plhControl = e.Item.FindControl("plhControl") as PlaceHolder;
                HiddenField fieldId = e.Item.FindControl("fieldId") as HiddenField;
                ltrFieldName.Text = field.Title;
                fieldId.Value = field.Id.ToString();

                //var fieldControl = field.FieldRenderingControl;
                //fieldControl.ControlMode = Microsoft.SharePoint.WebControls.SPControlMode.New;
                var fieldControl = ControlHelper.BuildValueSelectorControl(field, "");

                FormField formField = new FormField();
                formField.ControlMode = SPControlMode.New;
                formField.ListId = field.ParentList.ID;
                formField.FieldName = field.InternalName;
                switch (field.Type)
                {

                    case SPFieldType.Calculated:
                        plhControl.Controls.Add(new TextBox() {
                            CssClass="ms-long",
                            ID= field.InternalName,
                        });
                        break;
                    case SPFieldType.Computed:
                        if (field.InternalName == "ContentType")
                        {
                            var ddlCt = new DropDownList()
                            {

                                ID = field.InternalName,
                            };

                            foreach (SPContentType item in field.ParentList.ContentTypes)
                            {
                                if (!item.Hidden)
                                {
                                    ddlCt.Items.Add(new ListItem() { Text = item.Name, Value = item.Name.ToString() });
                                }
                            }
                            plhControl.Controls.Add(ddlCt);
                        }

                        break;
                    default:
                        plhControl.Controls.Add(formField);
                        break;
                }
                //fieldControl.ListId = SPContext.Current.List.ID;

                ControlHelper.LoadOperatorDropdown(field, ddlQUeryOpt);
            }
        }
Exemplo n.º 30
0
 public virtual FormValidationRule CreateRule(FormField field)
 {
     return(CreateRule(field, () => true));
 }
Exemplo n.º 31
0
        public DynaForms.DynaForm AddHtml(string html)
        {
            var f = new FormField();
            f.Html = html;
            f.Type = InputType.html;
            Fields.Add(f);

            return this;
        }
Exemplo n.º 32
0
 protected FormValidationRule CreateRule(FormField field, Func <bool> rule)
 {
     return(CreateRule(field, new[] { field.Name }, rule));
 }
Exemplo n.º 33
0
        protected async override Task <int> OnExecuteAsync(CommandLineApplication app)
        {
            Log.Information("User: {username}", Username);
            Log.Information("School: {school}", SchoolName);

            CpdailyCore   cpdaily       = new CpdailyCore();
            string        cookies       = null;
            SchoolDetails schoolDetails = null;

            try
            {
                Log.Information("正在获取 {info} ...", "SecretKey");
                var secretKeyTask = cpdaily.GetSecretKeyAsync();
                Log.Information("正在获取 {info} ...", "学校列表");
                var schools = await cpdaily.GetSchoolsAsync();

                Log.Information("正在获取 {info} ...", "学校ID");
                var school            = schools.Where(x => x.Name == SchoolName).FirstOrDefault();
                var schoolDetailsTask = cpdaily.GetSchoolDetailsAsync(school, await secretKeyTask);

                Type         loginWorkerType = Utils.GetLoginWorkerByName(SchoolName);
                ILoginWorker loginWorker     = null;
                if (loginWorkerType != null)
                {
                    Log.Information("使用专门登录适配器 <{LoginWorkerTypeName}>", loginWorkerType.Name);
                    loginWorker = (ILoginWorker)Activator.CreateInstance(loginWorkerType);
                }
                else
                {
                    Log.Information("使用通用登录适配器 <{LoginWorkerTypeName}>", "DefaultLoginWorker");
                    loginWorker = new DefaultLoginWorker();
                }

                Log.Information("正在获取登录所需参数...");
                schoolDetails = await schoolDetailsTask;
                var parameter = await loginWorker.GetLoginParameter(Username, Password, schoolDetails.GetIdsLoginUrl());

                if (parameter.NeedCaptcha)
                {
                    Log.Information("需要验证码!");
                    throw new Exception("需要验证码!暂时无法处理!");
                }

                Log.Information("正在登录...");
                cookies = await loginWorker.IdsLogin(parameter);

                Log.Information("登录成功, Cookie: {cookie}", cookies);

                // remove before adding to avoid duplication.
                AppConfig.Users.RemoveAll(x => x.Username == Username);
                AppConfig.Users.Add(new User()
                {
                    Username = Username, Password = Password
                });
                AppConfig.SchoolName = SchoolName;
                SaveAppConfig();
            }
            catch (Exception ex)
            {
                Log.Error("登录过程中出现异常!");
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return(1);
            }

            try
            {
                Log.Warning("下面进行表单向导,模拟完成一次历史表单,让程序学习如何填写表单。");
                Log.Information("获取历史表单...");
                var forms = await cpdaily.GetFormItemsHistoryAsync(schoolDetails.GetAmpUrl(), cookies);

                if (forms.Length == 0)
                {
                    throw new Exception("没有获取到历史表单,表单向导无法继续!");
                }
                Log.Information("获取到 {count} 条历史表单记录,请选择其中一条(输入序号):", forms.Length);
                for (int i = 0; i < forms.Length; i++)
                {
                    Log.Information("{No}. {Title}", i + 1, forms[i].Title);
                }
                int      index      = Convert.ToInt32(Console.ReadLine()) - 1;
                FormItem form       = forms[index];
                var      formFields = await cpdaily.GetFormFieldsAsync(schoolDetails.GetAmpUrl(), cookies, form.WId, form.FormWId);

                var requiredFields = formFields.Where(x => x.IsRequired == true).ToArray();
                Log.Information("获取到 {count} 条必填字段", requiredFields.Length);
                List <FormFieldChange> result = new List <FormFieldChange>();
                for (int i = 0; i < requiredFields.Length; i++)
                {
                    FormField field      = requiredFields[i];
                    var       typeString = field.FieldType switch
                    {
                        1 => "填空",
                        2 => "单选",
                        3 => "多选",
                        4 => "图片",
                        _ => "未知",
                    };
                    Log.Information("{No}. {Title} ({type}):", i + 1, field.Title, typeString);
                    Log.Information("描述: {Description}", string.IsNullOrEmpty(field.Description) ? "无" : field.Description);
                    if (field.FieldType == 1)
                    {
                        Log.Information("请输入文本:");
                        string value = Console.ReadLine();
                        var    c     = new FormFieldChange()
                        {
                            FieldType = field.FieldType,
                            Title     = field.Title,
                            Value     = value
                        };
                        result.Add(c);
                    }
                    else if (field.FieldType == 2)
                    {
                        for (int t = 0; t < field.FieldItems.Count; t++)
                        {
                            FieldItem item = field.FieldItems[t];
                            Log.Information("\t{No}.{Title}", t + 1, item.Content);
                        }
                        Log.Information("请输入选项序号:");
                        int value = Convert.ToInt32(Console.ReadLine()) - 1;
                        var c     = new FormFieldChange()
                        {
                            FieldType = field.FieldType,
                            Title     = field.Title,
                            Value     = field.FieldItems[value].Content
                        };
                        result.Add(c);
                    }
                    else
                    {
                        throw new Exception("暂不支持这种类型,请到 Github 提出 issues!");
                    }
                }
                Log.Information("表单向导完成!");

                AppConfig.FormFields = result;
                SaveAppConfig();
            }
            catch (Exception ex)
            {
                Log.Error("表单向导过程中出现异常!");
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return(1);
            }

            return(await base.OnExecuteAsync(app));
        }
Exemplo n.º 34
0
 protected FormValidationRule CreateRule(FormField field, string[] affectedFields, Func <bool> rule)
 {
     return(new FormValidationRule(affectedFields, GetValidationMessage(field.Model), rule));
 }
        public override VisitorAction VisitFormField(FormField formField)
        {
            this.structureBuilder.AppendLine("<FormField />");

            return VisitorAction.Continue;
        }
Exemplo n.º 36
0
        public DetailedCharacterResults(FormField field)
        {
            InitializeComponent();

            if (field is TextFormField)
            {
                for (int i = 0; i < ((field as TextFormField).Result as TextFormFieldResult).Characters.Count; i++)
                {
                    string[] row = new string[5];
                    row[0] = ((field as TextFormField).Result as TextFormFieldResult).Characters[i].Code.ToString();
                    row[1] = ((field as TextFormField).Result as TextFormFieldResult).Characters[i].GuessCode2.ToString();
                    row[2] = ((field as TextFormField).Result as TextFormFieldResult).Characters[i].FontStyle.ToString();
                    row[3] = ((field as TextFormField).Result as TextFormFieldResult).Characters[i].FontSize.ToString();
                    row[4] = ((field as TextFormField).Result as TextFormFieldResult).Characters[i].Bounds.ToString();
                    _charResults.Rows.Add(row);
                }
            }
            else if (field is UnStructuredTextFormField)
            {
                for (int i = 0; i < ((field as UnStructuredTextFormField).Result as TextFormFieldResult).Characters.Count; i++)
                {
                    string[] row = new string[5];
                    row[0] = ((field as UnStructuredTextFormField).Result as TextFormFieldResult).Characters[i].Code.ToString();
                    row[1] = ((field as UnStructuredTextFormField).Result as TextFormFieldResult).Characters[i].GuessCode2.ToString();
                    row[2] = ((field as UnStructuredTextFormField).Result as TextFormFieldResult).Characters[i].FontStyle.ToString();
                    row[3] = ((field as UnStructuredTextFormField).Result as TextFormFieldResult).Characters[i].FontSize.ToString();
                    row[4] = ((field as UnStructuredTextFormField).Result as TextFormFieldResult).Characters[i].Bounds.ToString();
                    _charResults.Rows.Add(row);
                }
            }
            else if (field is OmrFormField)
            {
                for (int i = 0; i < ((field as OmrFormField).Result as OmrFormFieldResult).Characters.Count; i++)
                {
                    string[] row = new string[5];
                    row[0] = ((field as OmrFormField).Result as OmrFormFieldResult).Characters[i].Code.ToString();
                    row[1] = ((field as OmrFormField).Result as OmrFormFieldResult).Characters[i].GuessCode2.ToString();
                    row[2] = ((field as OmrFormField).Result as OmrFormFieldResult).Characters[i].FontStyle.ToString();
                    row[3] = ((field as OmrFormField).Result as OmrFormFieldResult).Characters[i].FontSize.ToString();
                    row[4] = ((field as OmrFormField).Result as OmrFormFieldResult).Characters[i].Bounds.ToString();
                    _charResults.Rows.Add(row);
                }
            }
#if LEADTOOLS_V20_OR_LATER
            else if (field is OmrAnswerAreaField)
            {
                if (_charResults.Columns.Count == 5)
                {
                    _charResults.Columns[0].HeaderText = "Field";
                    _charResults.Columns[1].HeaderText = "Type";
                    _charResults.Columns[2].HeaderText = "Result";
                    _charResults.Columns[3].HeaderText = "Confidence";
                    _charResults.Columns[4].HeaderText = "Bounding Rectangle";
                }


                for (int i = 0; i < (field as OmrAnswerAreaField).Answers.Count; i++)
                {
                    string[] row = new string[5];
                    row[0] = ((field as OmrAnswerAreaField).Answers[i] as SingleSelectionField).Name;
                    row[1] = "SingleSelectionField";
                    row[2] = ((field as OmrAnswerAreaField).Answers[i].Result as OmrFormFieldResult).Text;
                    row[3] = ((field as OmrAnswerAreaField).Answers[i].Result as OmrFormFieldResult).AverageConfidence.ToString();
                    row[4] = (field as OmrAnswerAreaField).Answers[i].Bounds.ToString();
                    _charResults.Rows.Add(row);
                }
            }
#endif //#if LEADTOOLS_V20_OR_LATER
        }
Exemplo n.º 37
0
        public override IHtmlString GetHtmlString(BaseFormBuilderRequestContext context, FormField field, IDictionary <string, string> htmlAttributes)
        {
            var sb              = new StringBuilder();
            var renderer        = context.FormRenderer;
            var placeholderText = field.PlaceholderText;

            if (String.IsNullOrEmpty(placeholderText) && renderer.HideLabels)
            {
                placeholderText = field.Label;
            }

            sb.AppendFormat(Markup,
                            "password",
                            HttpUtility.HtmlAttributeEncode(field.Name),
                            HttpUtility.HtmlAttributeEncode(field.Id),
                            HttpUtility.HtmlAttributeEncode(field.Label),
                            HttpUtility.HtmlAttributeEncode(placeholderText));

            AddHtmlAttribute("class", renderer.FormControlClass, htmlAttributes);

            AddReadOnlyAttribute(field, htmlAttributes);
            AddMaxLengthAttribute(field, htmlAttributes);
            RenderExtraHtmlTags(sb, field, htmlAttributes);

            sb.Append(" />");

            return(new HtmlString(sb.ToString()));
        }
Exemplo n.º 38
0
 /// <summary>
 /// 解析提交的字段的值
 /// </summary>
 public object Parse(FormField field, IList <string> values)
 {
     return(JsonConvert.DeserializeObject <List <ProductToPropertyValueForEdit> >(values[0]) ??
            new List <ProductToPropertyValueForEdit>());
 }
Exemplo n.º 39
0
    public static FormField createFormField(ImportingElement element, int id)
    {
        GRASPEntities db = new GRASPEntities();

        var formField = new FormField();

        if(element.fieldType != FormFieldType.SEPARATOR)
        {
            if(!element.isRepItem)
            {
                element = cutIndexFromName(element);
            }
            formField.type = element.fieldType.ToString();
            formField.label = element.label;
            formField.name = element.name;
            formField.required = element.bindReference.required ? (byte)1 : (byte)0;
            formField.bindingsPolicy = element.bindingsPolicy;
            formField.constraintPolicy = element.constraintPolicy;
            formField.isReadOnly = element.bindReference.readOnly ? (byte)1 : (byte)0;

            if(element.calculated != null)
            {
                formField.calculated = 1;
                formField.formula = element.calculated;
            }
            else formField.calculated = 0;
        }
        else
        {
            formField.type = element.fieldType.ToString();
            formField.label = element.label;
            formField.name = element.name;
            formField.required = 0;
        }
        if((element.fieldType == FormFieldType.DROP_DOWN_LIST) || (element.fieldType == FormFieldType.RADIO_BUTTON))
        {
            Survey s = Survey.createSurvey(element, id, "select1");
            formField.survey_id = s.id;
        }
        if(element.fieldType == FormFieldType.REPEATABLES_BASIC)
        {
            formField.type = element.fieldType.ToString();
            formField.label = element.label;
            formField.name = element.name;
            formField.required = 0;
            foreach(ImportingElement reps in element.repElements)
            {
                createFormField(reps, id);
            }
            formField.numberOfRep = element.numberOfReps;
        }
        if(element.fieldType == FormFieldType.REPEATABLES)
        {
            formField.type = element.fieldType.ToString();
            formField.label = element.label;
            formField.name = element.name;
            formField.required = 0;
            foreach(ImportingElement reps in element.repElements)
            {
                createFormField(reps, id);
            }
            Survey s = Survey.createSurvey(element, id, "survey");
            formField.survey_id = s.id;
        }

        formField.pushed = 0;
        formField.form_id = id;
        formField.FFCreateDate = DateTime.Now;
        db.FormField.Add(formField);
        db.SaveChanges();

        return formField;
    }
 private static string GetSingleStringValue(FormField formField)
 {
     return(formField.ValueList != null?string.Join(", ", formField.ValueList.Select(x => x.Name)) : formField.Value.Name);
 }
Exemplo n.º 41
0
 protected internal virtual bool isDate(FormField formField)
 {
     return(DateFormType.TYPE_NAME.Equals(formField.TypeName));
 }
Exemplo n.º 42
0
		/// <summary>
		/// 获取错误消息
		/// </summary>
		/// <param name="field"></param>
		/// <returns></returns>
		private string ErrorMessage(FormField field) {
			return string.Format(new T("{0} is required"), new T(field.Attribute.Name));
		}
        public override IHtmlString GetHtmlString(BaseFormBuilderRequestContext context, FormField field, IDictionary <string, string> htmlAttributes)
        {
            var function = FunctionFacade.GetFunction(_c1FunctionName);

            if (function == null)
            {
                throw new InvalidOperationException("C1 function " + _c1FunctionName + " not recognized");
            }

            var parameters = new Dictionary <string, object>
            {
                { "Name", field.Name },
                { "HtmlAttributes", htmlAttributes },
                { "IsRequired", field.IsRequired },
                { "Label", field.Label },
                { "Placeholder", field.PlaceholderText }
            };

            var result = FunctionFacade.Execute <XhtmlDocument>(function, parameters);

            return(new HtmlString(result.ToString()));
        }
Exemplo n.º 44
0
		/// <summary>
		/// 添加验证使用的html属性
		/// </summary>
		public void AddHtmlAttributes(
			FormField field, object validatorAttribute, IDictionary<string, string> htmlAttributes) {
			htmlAttributes.Add(Key, ErrorMessage(field));
		}
Exemplo n.º 45
0
        public List <FormField> GetAllByFormDocumentId(int FormDocumentId)
        {
            FormFieldDAC     _formFieldComponent = new FormFieldDAC();
            IDataReader      reader         = _formFieldComponent.GetAllFormField("FormDocumentId = " + FormDocumentId).CreateDataReader();
            List <FormField> _formFieldList = new List <FormField>();

            while (reader.Read())
            {
                if (_formFieldList == null)
                {
                    _formFieldList = new List <FormField>();
                }
                FormField _formField = new FormField();
                if (reader["FormFieldId"] != DBNull.Value)
                {
                    _formField.FormFieldId = Convert.ToInt32(reader["FormFieldId"]);
                }
                if (reader["FormDocumentId"] != DBNull.Value)
                {
                    _formField.FormDocumentId = Convert.ToInt32(reader["FormDocumentId"]);
                }
                if (reader["FormFieldTypeId"] != DBNull.Value)
                {
                    _formField.FormFieldTypeId = Convert.ToInt32(reader["FormFieldTypeId"]);
                }
                if (reader["FieldParentId"] != DBNull.Value)
                {
                    _formField.FieldParentId = Convert.ToInt32(reader["FieldParentId"]);
                }
                if (reader["Title"] != DBNull.Value)
                {
                    _formField.Title = Convert.ToString(reader["Title"]);
                }
                if (reader["HelpText"] != DBNull.Value)
                {
                    _formField.HelpText = Convert.ToString(reader["HelpText"]);
                }
                if (reader["FormFieldOrder"] != DBNull.Value)
                {
                    _formField.FormFieldOrder = Convert.ToInt32(reader["FormFieldOrder"]);
                }
                if (reader["FieldDegree"] != DBNull.Value)
                {
                    _formField.FieldDegree = Convert.ToInt32(reader["FieldDegree"]);
                }
                if (reader["HasOther"] != DBNull.Value)
                {
                    _formField.HasOther = Convert.ToBoolean(reader["HasOther"]);
                }
                if (reader["DefaultValue"] != DBNull.Value)
                {
                    _formField.DefaultValue = Convert.ToString(reader["DefaultValue"]);
                }
                if (reader["IsRequired"] != DBNull.Value)
                {
                    _formField.IsRequired = Convert.ToBoolean(reader["IsRequired"]);
                }
                if (reader["RegularExpValidation"] != DBNull.Value)
                {
                    _formField.RegularExpValidation = Convert.ToString(reader["RegularExpValidation"]);
                }
                if (reader["ErrorText"] != DBNull.Value)
                {
                    _formField.ErrorText = Convert.ToString(reader["ErrorText"]);
                }
                if (reader["IsContactEmail"] != DBNull.Value)
                {
                    _formField.IsContactEmail = Convert.ToBoolean(reader["IsContactEmail"]);
                }
                if (reader["IsContactMobile"] != DBNull.Value)
                {
                    _formField.IsContactMobile = Convert.ToBoolean(reader["IsContactMobile"]);
                }
                if (reader["ColumnCount"] != DBNull.Value)
                {
                    _formField.ColumnCount = Convert.ToInt32(reader["ColumnCount"]);
                }
                if (reader["IsSection"] != DBNull.Value)
                {
                    _formField.IsSection = Convert.ToBoolean(reader["IsSection"]);
                }
                if (reader["IsPageBreak"] != DBNull.Value)
                {
                    _formField.IsPageBreak = Convert.ToBoolean(reader["IsPageBreak"]);
                }
                _formField.NewRecord = false;
                _formFieldList.Add(_formField);
            }
            reader.Close();
            return(_formFieldList);
        }
Exemplo n.º 46
0
        private static List<string> addFormField(FormField f)
        {
            List<string> result = new List<string>();
            DateTime dt = new DateTime();
            string txtFieldID = "";

            DataTable dtFormField = DbHelper.GetInstance().GetDBRecords("*", "Workflow_FormField", "FormID="+f.FormID, "DisplayOrder");

            for (int i = 0; i < f.FieldID.Count(); i++)
            {
                txtFieldID +=f.FieldID[i];
                if (i <f.FieldID.Count - 1) txtFieldID += ",";
                GPRP.Entity.Workflow_FormFieldEntity wff = new GPRP.Entity.Workflow_FormFieldEntity();
                wff.FormID =f.FormID;
                wff.FieldID =f.FieldID[i];
                wff.GroupID = Convert.ToBoolean(f.GroupID) ?f.GroupID : 0;              //明细组ID,0不是明细组
                wff.FieldLabel = f.FieldDesc[i];  //描述
                if (f.CSSStyleClass == null)
                {
                    wff.CSSStyle = 0;
                }
                else if (f.CSSStyleClass[i] != -1)
                {
                    wff.CSSStyle =f.CSSStyleClass[i];     //样式
                }

                wff.DisplayOrder = 10 + (i * 10);   //顺序
                wff.IsDetail = Convert.ToBoolean(f.IsDetail) ? f.IsDetail : 0;    //是否是明细组,1是明细组,0不是明细组
                wff.CreateDate = dt;  //创建日期
                wff.GroupLineDataSetID = f.GroupLineDataSetID[i];   //对应数据集
                wff.TargetGroupID = f.TargetGroupID[i];    //对应明细组

                int isflage = 0;
                for(int k=0;k<dtFormField.Rows.Count;k++)
                {
                    DataRow dr = dtFormField.Rows[k];

                    if (wff.FieldID == Convert.ToInt32(dr["FieldID"]))
                    {
                        isflage = 1;
                        result.Add(DbHelper.GetInstance().UpdateWorkflow_FormField(wff));  //更新
                        dtFormField.Rows.Remove(dr);
                        break;
                    }
                }

                if (isflage == 0)
                {
                    result.Add(DbHelper.GetInstance().AddWorkflow_FormField2(wff));   //新增

                }
            }

            foreach (DataRow dr in dtFormField.Rows)  //删除
            {
                  DbHelper.GetInstance().DeleteWorkflow_FormField(dr["FormID"].ToString(), dr["FieldID"].ToString(), dr["GroupID"].ToString());
            }

            ArrayList arlst = new ArrayList();
            arlst.Add("Workflow_FormField");
            arlst.Add(f.FormID);
            arlst.Add(f.GroupID);
            string a = DbHelper.GetInstance().sp_ReDisplayOrder(arlst);
            if (txtFieldID != string.Empty)
            {
                string r = DbHelper.GetInstance().sp_AlterWork_form_TableColumn(txtFieldID,f.GroupID == 0 ? "1" : "2");
            }

            return result;
        }
Exemplo n.º 47
0
		/// <summary>
		/// 解析提交的字段的值
		/// </summary>
		/// <param name="field"></param>
		/// <param name="value"></param>
		/// <returns></returns>
		public object Parse(FormField field, string value) {
			return value;
		}
Exemplo n.º 48
0
 public override bool Validate()
 {
     return(!CheckIsBlackListed(blackListedWords, FormField.GetStringValue(), ignoreCase));
 }
Exemplo n.º 49
0
    private void editRow(string keySet, string keyName)
    {
        LblOk.Text = "";
        LblErr.Text = "";

        var man = new AppSettingsManager2();
        var obj = new AppSetting();

        clearForm();
        this.currentXmlType = null;
        this.CurrentKey = keySet + "|" + keyName;
        if (keyName != string.Empty)
        {
            obj = man.GetByKey(keySet, keyName);
            DropKeySet.Enabled = false;
            TxtKeyName.Enabled = false;
        }
        else
        {
            DropKeySet.Enabled = true;
            TxtKeyName.Enabled = true;
        }
        obj2form(obj);

        MultiView1.ActiveViewIndex = 1;
    }
Exemplo n.º 50
0
 public void CreateFormField(FormField formField)
 {
     formFieldRepository.Add(formField);
 }
Exemplo n.º 51
0
        public DynaForm UpdateFormField(FormField f, string labelText = null, InputType type = InputType.undefined, string cssName = null, bool? required = null, bool? email = null, bool? isNumeric = null, int? maxLength = null, int? minLength = null, int? max = null, int? min = null, string regEx = null, Dictionary<string, string> dropDownValues = null, string template = null, string errorMessage = null, object defaultValue = null, bool? updateModel = null)
        {
            if (labelText != null) f.LabelText = labelText;
            if (type != InputType.undefined) f.Type = type;
            if (cssName != null) f.CssName = cssName;
            if (required != null) f.Required = required.GetValueOrDefault();
            if (email != null) f.Email = email.GetValueOrDefault();
            if (minLength != null) f.MinLength = minLength.GetValueOrDefault();
            if (maxLength != null) f.MaxLength = maxLength.GetValueOrDefault();
            if (regEx != null) f.RegEx = regEx ?? "";
            if (min != null) f.Min = min;
            if (max != null) f.Max = max;
            if (template != null) f.Template = template ?? "";
            if (dropDownValues != null) f.DropDownValueList = dropDownValues;
            if (defaultValue != null) f.DefaultValue = defaultValue;
            if (errorMessage != null) f.ErrorMessage = errorMessage ?? "";

            if (this.AutoPopulateModel && this.Model.GetType() == typeof(ExpandoObject) && ModelDictionary.ContainsKey(f.FieldName))
            {
                if (f.Type == InputType.checkbox)
                {
                    defaultValue = defaultValue ?? false;
                }
                else if (min != null || max != null)
                {
                    defaultValue = defaultValue ?? 0;
                }
                else if (type == InputType.select && f.DropDownValueList != null)
                {
                    var ddl = (Dictionary<string, string>)f.DropDownValueList;
                    defaultValue = ddl.FirstOrDefault().Value;
                }
                else
                {
                    defaultValue = defaultValue ?? "";
                }
                ModelDictionary[f.FieldName] = defaultValue;
            }

            return this;
        }
Exemplo n.º 52
0
 /// <summary>
 /// Constructor
 /// </summary>
 public ModelReferenceResponseTemplate(Project project, Screen screen, FormField formField)
 {
     Project   = project;
     Screen    = screen;
     FormField = formField;
 }
Exemplo n.º 53
0
        public DynaForms.DynaForm AddFormField(string fieldName, string labelText = "", InputType type = InputType.text, string cssName = "", bool required = false, bool email = false, bool numeric = false, int maxLength = 0, int minLength = 0, int? max = null, int? min = null, string regEx = "", Dictionary<string, string> dropDownValues = null, string template = "", string errorMessage = "", object defaultValue = null, bool updateModel = false, string labelCssName="")
        {
            var f = new FormField();
            f.FieldName = fieldName;
            f.LabelText = labelText;
            f.Type = type;
            f.CssName = cssName;
            f.Required = required;
            f.Email = email;
            f.MinLength = minLength;
            f.MaxLength = maxLength;
            f.RegEx = regEx;
            f.Min = min;
            f.Max = max;
            f.Numeric = numeric;
            f.Template = template;
            f.DropDownValueList = dropDownValues;
            f.ErrorMessage = errorMessage;
            f.LabelCssName = labelCssName;

            if ((updateModel || this.AutoPopulateModel) && this.Model.GetType() == typeof(ExpandoObject))
            {
                //if (this.Model == null) this.Model = new ExpandoObject();
                //var d = this.Model as IDictionary<string, object>;

                if (f.Type == InputType.checkbox)
                {
                    defaultValue = defaultValue ?? false;
                }
                else if (min != null || max != null)
                {
                    defaultValue = defaultValue ?? 0;
                }
                else if (type == InputType.select && f.DropDownValueList != null)
                {
                    var ddl = (Dictionary<string, string>)f.DropDownValueList;
                    defaultValue = ddl.FirstOrDefault().Value;
                }
                else
                {
                    defaultValue = defaultValue ?? "";
                }
                ModelDictionary.Add(f.FieldName, defaultValue);
            }

            f.DefaultValue = defaultValue;
            Fields.Add(f);

            return this;
        }
Exemplo n.º 54
0
        [Test] //ExSkip
        public void FormField()
        {
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            // Use a document builder to insert a combo box
            FormField comboBox = builder.InsertComboBox("MyComboBox", new[] { "One", "Two", "Three" }, 0);

            comboBox.CalculateOnExit = true;
            Assert.AreEqual(3, comboBox.DropDownItems.Count);
            Assert.AreEqual(0, comboBox.DropDownSelectedIndex);
            Assert.True(comboBox.Enabled);

            // Use a document builder to insert a check box
            FormField checkBox = builder.InsertCheckBox("MyCheckBox", false, 50);

            checkBox.IsCheckBoxExactSize = true;
            checkBox.HelpText            = "Right click to check this box";
            checkBox.OwnHelp             = true;
            checkBox.StatusText          = "Checkbox status text";
            checkBox.OwnStatus           = true;
            Assert.AreEqual(50.0d, checkBox.CheckBoxSize);
            Assert.False(checkBox.Checked);
            Assert.False(checkBox.Default);

            builder.Writeln();

            // Use a document builder to insert text input form field
            FormField textInput = builder.InsertTextInput("MyTextInput", TextFormFieldType.Regular, "", "Your text goes here", 50);

            textInput.EntryMacro       = "EntryMacro";
            textInput.ExitMacro        = "ExitMacro";
            textInput.TextInputDefault = "Regular";
            textInput.TextInputFormat  = "FIRST CAPITAL";
            textInput.SetTextInputValue("This value overrides the one we set during initialization");
            Assert.AreEqual(TextFormFieldType.Regular, textInput.TextInputType);
            Assert.AreEqual(50, textInput.MaxLength);

            // Get the collection of form fields that has accumulated in our document
            FormFieldCollection formFields = doc.Range.FormFields;

            Assert.AreEqual(3, formFields.Count);

            // Our form fields are represented as fields, with field codes FORMDROPDOWN, FORMCHECKBOX and FORMTEXT respectively,
            // made visible by pressing Alt + F9 in Microsoft Word
            // These fields have no switches and the content of their form fields is fully governed by members of the FormField object
            Assert.AreEqual(3, doc.Range.Fields.Count);

            // Iterate over the collection with an enumerator, accepting a visitor with each form field
            FormFieldVisitor formFieldVisitor = new FormFieldVisitor();

            using (IEnumerator <FormField> fieldEnumerator = formFields.GetEnumerator())
                while (fieldEnumerator.MoveNext())
                {
                    fieldEnumerator.Current.Accept(formFieldVisitor);
                }

            Console.WriteLine(formFieldVisitor.GetText());

            doc.UpdateFields();
            doc.Save(ArtifactsDir + "Field.FormField.docx");
            TestFormField(doc); //ExSkip
        }
Exemplo n.º 55
0
		/// <summary>
		/// 验证值是否通过,不通过时抛出例外
		/// </summary>
		public void Validate(FormField field, object validatorAttribute, object value) {
			if (value == null || value.ToString() == "") {
				throw new HttpException(400, ErrorMessage(field));
			}
		}
Exemplo n.º 56
0
 public void UpdateFormField(FormField formField)
 {
     formFieldRepository.Update(formField);
 }
Exemplo n.º 57
0
            /// <summary>
            /// Called when a FormField is encountered in the document.
            /// </summary>
            public override VisitorAction VisitFormField(FormField field)
            {
                if (isHidden(field))
                    field.Remove();

                return VisitorAction.Continue;
            }
Exemplo n.º 58
0
 /// <summary>
 /// 解析提交的字段的值
 /// </summary>
 public object Parse(FormField field, IList <string> values)
 {
     return(values[0]);
 }