示例#1
0
        private string GetFormRulesViewModel(FormDescription form)
        {
            if (string.IsNullOrWhiteSpace(form.Rules))
            {
                return(form.Rules);
            }

            var actionIndexList = this.FormRuleActionsToEncrypt.ToDictionary(p => p, p => 0);
            var rules           = JToken.Parse(form.Rules) as JArray;

            foreach (var rule in rules)
            {
                foreach (var action in rule["Actions"] as JArray)
                {
                    var ruleAction = action["Action"].ToObject <FormRuleAction>();
                    if (this.FormRuleActionsToEncrypt.Contains(ruleAction))
                    {
                        action["Target"] = string.Concat(string.Format(CultureInfo.InvariantCulture, FormInputValueFormat, ruleAction), actionIndexList[ruleAction]);
                        actionIndexList[ruleAction]++;
                    }
                }
            }

            return(JsonConvert.SerializeObject(rules));
        }
        /// <inheritDoc/>
        public override void Render(StreamWriter writer, FormDescription form)
        {
            var    virtualPath = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend.Forms/Mvc/Views/Form/Index.cshtml";
            string formIndexView;

            using (StreamReader reader = new StreamReader(HostingEnvironment.VirtualPathProvider.GetFile(virtualPath).Open()))
            {
                formIndexView = reader.ReadToEnd();
            }

            var           formControlsArray  = form.Controls.ToArray();
            var           isMultiPageForm    = formControlsArray.Any(c => (c.GetControlType().ImplementsInterface(typeof(IFormPageBreak))));
            StringBuilder formControlsMarkup = new StringBuilder();

            formControlsMarkup.Append(this.GetFieldsMarkup("Body", formControlsArray));

            if (isMultiPageForm)
            {
                this.FormMultipageDecorator.WrapFormPage(formControlsMarkup);
            }

            formControlsMarkup.Insert(0, this.GetFieldsMarkup("Header", formControlsArray));
            formControlsMarkup.Append(this.GetFieldsMarkup("Footer", formControlsArray));

            var result = formIndexView.Replace("@* Fields Markup *@", formControlsMarkup.ToString());

            writer.Write(result);
        }
        public string GetFirstFieldName(FormsManager formManager, FormDescription form)
        {
            var textFieldControlData = form.Controls.Where(c => c.PlaceHolder == "Body" && c.IsLayoutControl == false).FirstOrDefault();
            var mvcfieldProxy        = formManager.LoadControl(textFieldControlData) as MvcWidgetProxy;
            var fieldControl         = mvcfieldProxy.Controller as IFormFieldControl;
            var fieldName            = fieldControl.MetaField.FieldName;

            return(fieldName);
        }
示例#4
0
        private string GetTextFieldName(FormsManager formManager, FormDescription form)
        {
            var textFieldControlData = form.Controls.Where(c => c.PlaceHolder == "Body" && c.IsLayoutControl == false).FirstOrDefault();
            var mvcfieldProxy        = formManager.LoadControl(textFieldControlData) as MvcWidgetProxy;
            var textField            = mvcfieldProxy.Controller as TextFieldController;

            Assert.IsNotNull(textField, "The text field was not found.");

            var textFieldName = textField.MetaField.FieldName;

            return(textFieldName);
        }
        /// <inheritDoc/>
        public override void Render(StreamWriter writer, FormDescription form)
        {
            var virtualPath = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend.Forms/Mvc/Views/Form/Index.cshtml";
            string formIndexView;
            using (StreamReader reader = new StreamReader(HostingEnvironment.VirtualPathProvider.GetFile(virtualPath).Open()))
            {
                formIndexView = reader.ReadToEnd();
            }

            var result = formIndexView.Replace("@* Fields Markup *@", this.GetFieldsMarkup("Body", form.Controls.ToArray()));
            writer.Write(result);
        }
        /// <inheritDoc/>
        public override void Render(StreamWriter writer, FormDescription form)
        {
            var fileStream = typeof(FormRazorRenderer).Assembly.GetManifestResourceStream("Telerik.Sitefinity.Frontend.Forms.Mvc.Views.Form.Index.cshtml");
            string formIndexView;
            using (var streamReader = new StreamReader(fileStream))
            {
                formIndexView = streamReader.ReadToEnd();
            }

            var result = formIndexView.Replace("## Fields Markup ##", this.GetFieldsMarkup("Body", form.Controls.ToArray()));
            writer.Write(result);
        }
        /// <inheritDoc/>
        public override void Render(StreamWriter writer, FormDescription form)
        {
            var    virtualPath = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend.Forms/Mvc/Views/Form/Index.cshtml";
            string formIndexView;

            using (StreamReader reader = new StreamReader(HostingEnvironment.VirtualPathProvider.GetFile(virtualPath).Open()))
            {
                formIndexView = reader.ReadToEnd();
            }

            var result = formIndexView.Replace("@* Fields Markup *@", this.GetFieldsMarkup("Body", form.Controls.ToArray()));

            writer.Write(result);
        }
示例#8
0
        protected void LoadFormControls(FormDescription form, FormCollection collection, HttpFileCollectionBase files, FormsManager manager, out Dictionary <string, IFormFieldController <IFormFieldModel> > formFields, out List <IFormElementController <IFormElementModel> > formElements)
        {
            formFields   = new Dictionary <string, IFormFieldController <IFormFieldModel> >();
            formElements = new List <IFormElementController <IFormElementModel> >();

            this.SanitizeFormCollection(collection);
            var behaviorResolver = ObjectFactory.Resolve <IControlBehaviorResolver>();

            var skipFields   = this.SplitCsv(this.GetFormCollectionItemValue(collection, FormSkipFieldsInputName));
            var hiddenFields = this.SplitCsv(this.GetFormCollectionItemValue(collection, FormHiddenFieldsInputName));

            foreach (var control in form.Controls)
            {
                if (control.IsLayoutControl)
                {
                    continue;
                }

                Type controlType;
                if (control.ObjectType.StartsWith("~/"))
                {
                    controlType = FormsManager.GetControlType(control);
                }
                else
                {
                    controlType = TypeResolutionService.ResolveType(behaviorResolver.GetBehaviorObjectType(control), true);
                }

                if (!controlType.ImplementsGenericInterface(typeof(IFormElementController <>)))
                {
                    continue;
                }

                var controlInstance       = manager.LoadControl(control);
                var controlBehaviorObject = behaviorResolver.GetBehaviorObject(controlInstance);
                var formField             = controlBehaviorObject as IFormFieldController <IFormFieldModel>;

                if (formField != null)
                {
                    formFields.Add(controlInstance.ID, formField);
                }
                else
                {
                    var formElement = (IFormElementController <IFormElementModel>)controlBehaviorObject;
                    formElements.Add(formElement);
                }
            }
        }
示例#9
0
        private bool GetSyncFormFieldsToLeadFields(FormDescription form)
        {
            if (form == null || form.Attributes == null)
            {
                return(false);
            }

            bool result;

            if (!form.Attributes.ContainsKey(FormsHelpers.SyncFormFieldsToLeadFieldsPropertyName) ||
                !bool.TryParse(form.Attributes[FormsHelpers.SyncFormFieldsToLeadFieldsPropertyName], out result))
            {
                result = false;
            }
            return(result);
        }
示例#10
0
        private bool GetDoSpecificWebCalls(FormDescription form)
        {
            if (form == null || form.Attributes == null)
            {
                return(false);
            }

            bool result;

            if (!form.Attributes.ContainsKey(FormsHelpers.DoSpecificWebCallsPropertyName) ||
                !bool.TryParse(form.Attributes[FormsHelpers.DoSpecificWebCallsPropertyName], out result))
            {
                result = false;
            }
            return(result);
        }
示例#11
0
        private static Guid GetLastControlInPlaceHolder(FormDescription form, string placeHolder)
        {
            var         id = Guid.Empty;
            FormControl control;

            var controls = new List <FormControl>(form.Controls.Where(c => c.PlaceHolder == placeHolder));

            while (controls.Count > 0)
            {
                control = controls.Where(c => c.SiblingId == id).SingleOrDefault();
                id      = control.Id;

                controls.Remove(control);
            }

            return(id);
        }
示例#12
0
        private static Guid GetLastControlInPlaceHolder(FormDescription form, string placeHolder)
        {
            var id = Guid.Empty;
            FormControl control;

            var controls = new List<FormControl>(form.Controls.Where(c => c.PlaceHolder == placeHolder));

            while (controls.Count > 0)
            {
                control = controls.Where(c => c.SiblingId == id).SingleOrDefault();
                id = control.Id;

                controls.Remove(control);
            }

            return id;
        }
示例#13
0
        private void TransferResponses(FormDescription originalForm, FormDescription duplicateForm, FormsManager manager)
        {
            // If the original form does not have a type for its entries then there is nothing to transfer.
            if (manager.GetMetadataManager().GetMetaType(manager.Provider.FormsNamespace, originalForm.Name) == null)
            {
                return;
            }

            // Create live versions of the controls that have a true Published property. Still the form should not be published.
            var draft = manager.Lifecycle.Edit(duplicateForm);

            manager.Lifecycle.Publish(draft);
            manager.Lifecycle.Unpublish(duplicateForm);

            // If a type was create while publishing we should delete it. We will use the type of the original form.
            var metaType = manager.GetMetadataManager().GetMetaType(manager.Provider.FormsNamespace, duplicateForm.Name);

            if (metaType != null)
            {
                manager.GetMetadataManager().Delete(metaType);
            }

            // Take the original form name. As a result the new form seizes the original meta type and all its items (the responses).
            duplicateForm.Name = originalForm.Name;

            if (!manager.GetForms().Any(f => f.Name == originalForm.Name + "_legacy"))
            {
                originalForm.Name = originalForm.Name + "_legacy";
            }
            else
            {
                originalForm.Name = originalForm.Name + Guid.NewGuid().ToString("N");
            }

            duplicateForm.FormEntriesSeed = originalForm.FormEntriesSeed;

            // Create a new dynamic type for the old form.
            foreach (var control in originalForm.Controls)
            {
                control.Published = false;
            }

            manager.BuildDynamicType(originalForm);
        }
示例#14
0
        private string GetFormRulesMessage(FormDescription form, string confirmationMessageKey)
        {
            string message = string.Empty;

            if (string.IsNullOrWhiteSpace(form.Rules) || string.IsNullOrWhiteSpace(confirmationMessageKey))
            {
                return(message);
            }

            int submitMessageIndex;

            if (int.TryParse(confirmationMessageKey.Replace(FormMessagePrefix, string.Empty), out submitMessageIndex))
            {
                var deserializedRules = JsonConvert.DeserializeObject <List <FormRule> >(form.Rules);
                var messageIndex      = 0;
                foreach (var rule in deserializedRules)
                {
                    foreach (var action in rule.Actions)
                    {
                        if (action.Action == FormRuleAction.ShowMessage)
                        {
                            if (submitMessageIndex == messageIndex)
                            {
                                message = action.Target;
                                break;
                            }

                            messageIndex++;
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        break;
                    }
                }
            }

            return(message);
        }
示例#15
0
        private void ProcessForm(FormDescription form)
        {
            string str;

            if (form == null)
            {
                return;
            }
            if (!this.ValidateFormSubmissionRestrictions(form, out str))
            {
                this.FormControls.Visible = true;
                this.ErrorsPanel.Visible  = true;
                this.ErrorsPanel.Controls.Add(new Label()
                {
                    Text = str
                });
            }
            else if (this.ValidateFormInput())
            {
                CancelEventArgs cancelEventArg = new CancelEventArgs();

                this.OnBeforeFormSave(cancelEventArg);

                if (!cancelEventArg.Cancel)
                {
                    this.SaveFormEntry(form);
                    this.OnFormSaved(null);

                    CancelEventArgs cancelEventArg1 = new CancelEventArgs();

                    this.OnBeforeFormAction(cancelEventArg1);

                    if (!cancelEventArg1.Cancel)
                    {
                        this.ProcessFromSubmitAction(form);
                        return;
                    }
                }
            }
        }
示例#16
0
        private void UpdateCustomConfirmationMode(FormDescription form, FormCollection collection)
        {
            var confirmationMessageKey = this.GetFormCollectionItemValue(collection, FormMessageKey);

            if (!string.IsNullOrWhiteSpace(confirmationMessageKey))
            {
                var message = this.GetFormRulesMessage(form, confirmationMessageKey);
                this.CustomConfirmationMessage = this.GetEvaledExpression(message);
                this.UseCustomConfirmation     = true;
                this.CustomConfirmationMode    = CustomConfirmationMode.ShowMessageForSuccess;
            }

            var  confirmationPageIdValue = this.GetFormCollectionItemValue(collection, FormRedirectPageKey);
            Guid confirmationPageId;

            if (Guid.TryParse(confirmationPageIdValue, out confirmationPageId) && confirmationPageId != Guid.Empty)
            {
                this.CustomConfirmationPageId = confirmationPageId;
                this.UseCustomConfirmation    = true;
                this.CustomConfirmationMode   = CustomConfirmationMode.RedirectToAPage;
            }
        }
示例#17
0
        private FormDescription Duplicate(FormDescription formDescription, string formName, FormsManager manager)
        {
            var duplicateForm  = manager.CreateForm(formName);
            var thisFormMaster = manager.Lifecycle.GetMaster(formDescription);

            // Form has been unpublished
            if (thisFormMaster == null)
            {
                this.CopyFormCommonData(formDescription, duplicateForm, manager);

                // Get permissions from ParentForm, because FormDraft is no ISecuredObject
                duplicateForm.CopySecurityFrom((ISecuredObject)formDescription, null, null);
            }
            else
            {
                this.CopyFormCommonData(thisFormMaster, duplicateForm, manager);

                // Get permissions from ParentForm, because FormDraft is no ISecuredObject
                duplicateForm.CopySecurityFrom((ISecuredObject)thisFormMaster.ParentForm, null, null);
            }

            return(duplicateForm);
        }
示例#18
0
        private string GetFormRulesViewModel(FormDescription form)
        {
            if (string.IsNullOrWhiteSpace(form.Rules))
            {
                return(form.Rules);
            }

            var messageIndex = 0;
            var rules        = JToken.Parse(form.Rules) as JArray;

            foreach (var rule in rules)
            {
                foreach (var action in rule["Actions"] as JArray)
                {
                    if (action["Action"].ToString() == FormRuleAction.ShowMessage.ToString())
                    {
                        action["Target"] = string.Concat(FormMessagePrefix, messageIndex);
                        messageIndex++;
                    }
                }
            }

            return(JsonConvert.SerializeObject(rules));
        }
示例#19
0
        new private void SaveFormEntry(FormDescription description)
        {
            FormsManager manager         = FormsManager.GetManager();
            FormEntry    userHostAddress = null;

            if (_isProgressiveForm && _priorFormEntry == null)
            {
                FieldControl keyField = this.FieldControls.Where(fc => ((IFormFieldControl)fc).MetaField.FieldName == _progressiveKeyFieldName).FirstOrDefault() as FieldControl;

                if (keyField != null && !String.IsNullOrWhiteSpace((string)keyField.Value))
                {
                    _priorFormEntry = GetPriorFormEntryByKeyField((string)keyField.Value);
                }
            }

            if (_isProgressiveForm && _priorFormEntry != null)
            {
                string entryType = String.Format("{0}.{1}", manager.Provider.FormsNamespace, this.FormData.Name);

                userHostAddress = manager.GetFormEntry(entryType, _priorFormEntry.Id);
            }
            else
            {
                userHostAddress = manager.CreateFormEntry(string.Format("{0}.{1}", manager.Provider.FormsNamespace, description.Name));
            }

            foreach (IFormFieldControl formFieldControl in this.FieldControls)
            {
                FieldControl fieldControl = formFieldControl as FieldControl;
                object       value        = fieldControl.Value;

                if (fieldControl.GetType().Name == "FormFileUpload")
                {
                    typeof(FormsControl)
                    .GetMethod("SaveFiles", BindingFlags.Static | BindingFlags.NonPublic)
                    .Invoke(null, new object[] { value as UploadedFileCollection, manager, description, userHostAddress, formFieldControl.MetaField.FieldName });
                }
                else if (!(value is List <string>))
                {
                    userHostAddress.SetValue(formFieldControl.MetaField.FieldName, value);
                }
                else
                {
                    StringArrayConverter stringArrayConverter = new StringArrayConverter();
                    object obj = stringArrayConverter.ConvertTo((value as List <string>).ToArray(), typeof(string));

                    userHostAddress.SetValue(formFieldControl.MetaField.FieldName, obj);
                }
            }
            userHostAddress.IpAddress   = this.Page.Request.UserHostAddress;
            userHostAddress.SubmittedOn = DateTime.UtcNow;

            Guid userId = ClaimsManager.GetCurrentUserId();

            userHostAddress.UserId = userId == Guid.Empty ? Guid.Parse(_sfTrackingCookie.Value) : userId;

            if (userHostAddress.UserId == userId)
            {
                userHostAddress.Owner = userId;
            }

            if (SystemManager.CurrentContext.AppSettings.Multilingual)
            {
                userHostAddress.Language = CultureInfo.CurrentUICulture.Name;
            }

            FormDescription formData = this.FormData;

            formData.FormEntriesSeed     = formData.FormEntriesSeed + (long)1;
            userHostAddress.ReferralCode = this.FormData.FormEntriesSeed.ToString();

            manager.SaveChanges();
        }
示例#20
0
        /// <summary>
        /// Determines whether a form is valid or not.
        /// </summary>
        /// <param name="form">The form.</param>
        /// <param name="collection">The collection.</param>
        /// <param name="files">The files.</param>
        /// <param name="formFields">The form fields.</param>
        /// <param name="formElements">The form elements.</param>
        /// <param name="fieldControls">The field controls.</param>
        /// <returns>true if form is valid, false otherwise.</returns>
        protected virtual bool IsValidForm(FormDescription form, FormCollection collection, HttpFileCollectionBase files, Dictionary <string, IFormFieldController <IFormFieldModel> > formFields, List <IFormElementController <IFormElementModel> > formElements, out Dictionary <IFormFieldController <IFormFieldModel>, bool> fieldControls)
        {
            fieldControls          = new Dictionary <IFormFieldController <IFormFieldModel>, bool>();
            this.captchaController = null;

            this.ResetInvalidInputMessage();
            this.SanitizeFormCollection(collection);

            var skipFields   = this.SplitCsv(this.GetFormCollectionItemValue(collection, FormSkipFieldsInputName));
            var hiddenFields = this.SplitCsv(this.GetFormCollectionItemValue(collection, FormHiddenFieldsInputName));

            foreach (var formField in formFields)
            {
                if (!this.RaiseFormFieldValidatingEvent(formField.Value))
                {
                    return(false);
                }

                var fieldName = formField.Value.MetaField.FieldName;

                IList <HttpPostedFileBase> multipleFiles = files != null?files.GetMultiple(fieldName) : null;

                object fieldValue;

                if (multipleFiles != null && multipleFiles.Count() > 0)
                {
                    fieldValue = multipleFiles;
                }
                else if (collection.Keys.Contains(fieldName))
                {
                    collection[fieldName] = collection[fieldName] ?? string.Empty;
                    fieldValue            = collection[fieldName];
                }
                else
                {
                    fieldValue = null;
                }

                var hideableModel = formField.Value.Model as IHideable;
                var canSaveField  = hideableModel != null?this.CanSaveField(hiddenFields, skipFields, formField.Key, form.Rules, hideableModel.Hidden) : true;

                fieldControls.Add(formField.Value, canSaveField);

                if (canSaveField && !formField.Value.Model.IsValid(fieldValue))
                {
                    this.SetFormFieldInvalidInputMessage(formField.Value);
                    return(false);
                }
            }

            foreach (var formElement in formElements)
            {
                if (!formElement.IsValid())
                {
                    this.SetFormElementInvalidInputMessage(formElement);
                    return(false);
                }

                if (formElement is Controllers.CaptchaController formElementController)
                {
                    this.captchaController = formElementController;
                }
            }

            return(true);
        }
示例#21
0
        /// <summary>
        /// Determines whether a form is valid or not.
        /// </summary>
        /// <param name="form">The form.</param>
        /// <param name="collection">The collection.</param>
        /// <param name="manager">The manager.</param>
        /// <returns>true if form is valid, false otherwise.</returns>
        protected virtual bool IsValidForm(FormDescription form, FormCollection collection, HttpFileCollectionBase files, FormsManager manager, out Dictionary <IFormFieldController <IFormFieldModel>, bool> fieldControls)
        {
            fieldControls          = new Dictionary <IFormFieldController <IFormFieldModel>, bool>();
            this.captchaController = null;

            this.ResetInvalidInputMessage();
            this.SanitizeFormCollection(collection);
            var behaviorResolver = ObjectFactory.Resolve <IControlBehaviorResolver>();

            var skipFields   = this.SplitCsv(this.GetFormCollectionItemValue(collection, FormSkipFieldsInputName));
            var hiddenFields = this.SplitCsv(this.GetFormCollectionItemValue(collection, FormHiddenFieldsInputName));

            foreach (var control in form.Controls)
            {
                if (control.IsLayoutControl)
                {
                    continue;
                }

                Type controlType;
                if (control.ObjectType.StartsWith("~/"))
                {
                    controlType = FormsManager.GetControlType(control);
                }
                else
                {
                    controlType = TypeResolutionService.ResolveType(behaviorResolver.GetBehaviorObjectType(control), true);
                }

                if (!controlType.ImplementsGenericInterface(typeof(IFormElementController <>)))
                {
                    continue;
                }

                var controlInstance       = manager.LoadControl(control);
                var controlBehaviorObject = behaviorResolver.GetBehaviorObject(controlInstance);
                var formField             = controlBehaviorObject as IFormFieldController <IFormFieldModel>;

                if (formField != null)
                {
                    if (!this.RaiseFormFieldValidatingEvent(formField))
                    {
                        return(false);
                    }

                    var fieldName = formField.MetaField.FieldName;

                    IList <HttpPostedFileBase> multipleFiles = files != null?files.GetMultiple(fieldName) : null;

                    object fieldValue;

                    if (multipleFiles != null && multipleFiles.Count() > 0)
                    {
                        fieldValue = multipleFiles;
                    }
                    else if (collection.Keys.Contains(fieldName))
                    {
                        collection[fieldName] = collection[fieldName] ?? string.Empty;
                        fieldValue            = collection[fieldName];
                    }
                    else
                    {
                        fieldValue = null;
                    }

                    var hideableModel = formField.Model as IHideable;
                    var canSaveField  = hideableModel != null?this.CanSaveField(hiddenFields, skipFields, controlInstance.ID, form.Rules, hideableModel.Hidden) : true;

                    fieldControls.Add(formField, canSaveField);

                    if (canSaveField && !formField.Model.IsValid(fieldValue))
                    {
                        this.SetFormFieldInvalidInputMessage(formField);
                        return(false);
                    }
                }
                else
                {
                    var formElement = (IFormElementController <IFormElementModel>)controlBehaviorObject;
                    if (!formElement.IsValid())
                    {
                        this.SetFormElementInvalidInputMessage(formElement);
                        return(false);
                    }

                    if (formElement is Controllers.CaptchaController formElementController)
                    {
                        this.captchaController = formElementController;
                    }
                }
            }

            return(true);
        }
示例#22
0
        private FormEntry GetPriorFormEntryByKeyField(string keyFieldValue)
        {
            FormDescription form = FManager.GetForms().Where(f => f.Name == this.FormData.Name).SingleOrDefault();

            return(FManager.GetFormEntries(form).Where(e => e.GetValue <string>(_progressiveKeyFieldName) == keyFieldValue).FirstOrDefault());
        }
示例#23
0
        private FormEntry GetFormEntryByUserId(Guid userId)
        {
            FormDescription form = FManager.GetForms().Where(f => f.Name == this.FormData.Name).SingleOrDefault();

            return(FManager.GetFormEntries(form).Where(e => e.UserId == userId).FirstOrDefault());
        }
示例#24
0
        /// <summary>
        /// Determines whether a form is valid or not.
        /// </summary>
        /// <param name="form">The form.</param>
        /// <param name="collection">The collection.</param>
        /// <param name="manager">The manager.</param>
        /// <returns>true if form is valid, false otherwise.</returns>
        protected virtual bool IsValidForm(FormDescription form, FormCollection collection, HttpFileCollectionBase files, FormsManager manager)
        {
            this.SanitizeFormCollection(collection);
            var behaviorResolver = ObjectFactory.Resolve<IControlBehaviorResolver>();
            foreach (var control in form.Controls)
            {
                if (control.IsLayoutControl)
                    continue;

                Type controlType;
                if (control.ObjectType.StartsWith("~/"))
                    controlType = FormsManager.GetControlType(control);
                else
                    controlType = TypeResolutionService.ResolveType(behaviorResolver.GetBehaviorObjectType(control), true);

                if (!controlType.ImplementsGenericInterface(typeof(IFormElementController<>)))
                    continue;

                var controlInstance = manager.LoadControl(control);
                var controlBehaviorObject = behaviorResolver.GetBehaviorObject(controlInstance);

                if (controlBehaviorObject is IFormFieldController<IFormFieldModel>)
                {
                    var formField = (IFormFieldController<IFormFieldModel>)controlBehaviorObject;
                    var multipleFiles = files.GetMultiple(formField.MetaField.FieldName);
                    object fieldValue;
                    if (multipleFiles != null && multipleFiles.Count() > 0)
                    {
                        fieldValue = (object)multipleFiles;
                    }
                    else
                    {
                        collection[formField.MetaField.FieldName] = collection[formField.MetaField.FieldName] ?? string.Empty;
                        fieldValue = (object)collection[formField.MetaField.FieldName];
                    }

                    if (!formField.Model.IsValid(fieldValue))
                        return false;
                }
                else
                {
                    var formElement = (IFormElementController<IFormElementModel>)controlBehaviorObject;
                    if (!formElement.IsValid())
                        return false;
                }
            }

            return true;
        }
示例#25
0
 /// <inheritDoc/>
 public abstract void Render(StreamWriter writer, FormDescription form);
示例#26
0
        /// <summary>
        /// Determines whether a form is valid or not.
        /// </summary>
        /// <param name="form">The form.</param>
        /// <param name="collection">The collection.</param>
        /// <param name="manager">The manager.</param>
        /// <returns>true if form is valid, false otherwise.</returns>
        protected virtual bool IsValidForm(FormDescription form, FormCollection collection, HttpFileCollectionBase files, FormsManager manager)
        {
            this.SanitizeFormCollection(collection);
            var behaviorResolver = ObjectFactory.Resolve <IControlBehaviorResolver>();

            foreach (var control in form.Controls)
            {
                if (control.IsLayoutControl)
                {
                    continue;
                }

                Type controlType;
                if (control.ObjectType.StartsWith("~/"))
                {
                    controlType = FormsManager.GetControlType(control);
                }
                else
                {
                    controlType = TypeResolutionService.ResolveType(behaviorResolver.GetBehaviorObjectType(control), true);
                }

                if (!controlType.ImplementsGenericInterface(typeof(IFormElementController <>)))
                {
                    continue;
                }

                var controlInstance       = manager.LoadControl(control);
                var controlBehaviorObject = behaviorResolver.GetBehaviorObject(controlInstance);
                var formField             = controlBehaviorObject as IFormFieldController <IFormFieldModel>;

                if (formField != null)
                {
                    if (!this.RaiseFormFieldValidatingEvent(formField))
                    {
                        return(false);
                    }

                    IList <HttpPostedFileBase> multipleFiles = files != null?files.GetMultiple(formField.MetaField.FieldName) : null;

                    object fieldValue;

                    if (multipleFiles != null && multipleFiles.Count() > 0)
                    {
                        fieldValue = multipleFiles;
                    }
                    else if (collection.Keys.Contains(formField.MetaField.FieldName))
                    {
                        collection[formField.MetaField.FieldName] = collection[formField.MetaField.FieldName] ?? string.Empty;
                        fieldValue = collection[formField.MetaField.FieldName];
                    }
                    else
                    {
                        fieldValue = null;
                    }

                    if (!formField.Model.IsValid(fieldValue))
                    {
                        return(false);
                    }
                }
                else
                {
                    var formElement = (IFormElementController <IFormElementModel>)controlBehaviorObject;
                    if (!formElement.IsValid())
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
        private void ProcessForm(FormDescription form)
        {
            string str;
            if (form == null)
            {
                return;
            }
            if (!this.ValidateFormSubmissionRestrictions(form, out str))
            {
                this.FormControls.Visible = true;
                this.ErrorsPanel.Visible = true;
                this.ErrorsPanel.Controls.Add(new Label()
                {
                    Text = str
                });
            }
            else if (this.ValidateFormInput())
            {
                CancelEventArgs cancelEventArg = new CancelEventArgs();

                this.OnBeforeFormSave(cancelEventArg);

                if (!cancelEventArg.Cancel)
                {
                    this.SaveFormEntry(form);
                    this.OnFormSaved(null);

                    CancelEventArgs cancelEventArg1 = new CancelEventArgs();

                    this.OnBeforeFormAction(cancelEventArg1);

                    if (!cancelEventArg1.Cancel)
                    {
                        this.ProcessFromSubmitAction(form);
                        return;
                    }
                }
            }
        }
示例#28
0
        protected override void InitializeControls(GenericContainer container)
        {
            IFormFieldControl thisControl     = base.ParentDesigner.PropertyEditor.Control as IFormFieldControl;
            FormDraftControl  thisControlData = base.ParentDesigner.PropertyEditor.ControlData as FormDraftControl;

            FormDescription form = FManager.GetFormByName(thisControlData.Form.Name);

            IControlsContainer cc = GetControlsContainer(form.Id);

            List <ControlData> formControls = (List <ControlData>) typeof(PageHelper)
                                              .GetMethod("SortControls", BindingFlags.Static | BindingFlags.NonPublic)
                                              .Invoke(null, new object[] { new[] { cc }, 1 });

            formControls.RemoveAll(fc => fc.ObjectType == "Telerik.Sitefinity.Modules.Forms.Web.UI.Fields.FormSubmitButton, Telerik.Sitefinity" || fc.IsLayoutControl == true);

            if (formControls.Count > 0)
            {
                List <CriteriaOption> criteriaOptions = new List <CriteriaOption>();

                CultureInfo uiCulture = CultureInfo.GetCultureInfo(this.GetUICulture());

                foreach (var formControl in formControls)
                {
                    FieldControl fieldControl = FManager.LoadControl(formControl, uiCulture) as FieldControl;

                    CriteriaOption co = new CriteriaOption();

                    if (fieldControl is FormChoiceField)
                    {
                        co.FieldType = "ChoiceField";
                        co.FieldName = Helpers.GetFieldName(fieldControl);
                        co.Options   = ((FormChoiceField)fieldControl).Choices
                                       .Select(c => new SimpleChoiceItem()
                        {
                            Text = c.Text, Value = c.Value
                        }).ToList();

                        co.Conditions = new List <SimpleChoiceItem>()
                        {
                            new SimpleChoiceItem()
                            {
                                Text = "=", Value = "=="
                            },
                            new SimpleChoiceItem()
                            {
                                Text = "!=", Value = "!="
                            }
                        };
                    }

                    if (fieldControl is TextField)
                    {
                        co.FieldType = "TextField";
                        co.FieldName = Helpers.GetFieldName(fieldControl);

                        co.Conditions = new List <SimpleChoiceItem>()
                        {
                            new SimpleChoiceItem()
                            {
                                Text = "=", Value = "=="
                            },
                            new SimpleChoiceItem()
                            {
                                Text = "!=", Value = "!="
                            },
                            new SimpleChoiceItem()
                            {
                                Text = "<", Value = "lt"
                            },
                            new SimpleChoiceItem()
                            {
                                Text = ">", Value = "gt"
                            }
                        };
                    }

                    criteriaOptions.Add(co);
                }

                StringBuilder script = new StringBuilder();

                script.Append(@"<script>");
                script.AppendFormat(@"var currentCultureC = ""{0}"";", this.GetUICulture());
                script.AppendFormat(@"var optionFilter = ""{0}"";", Helpers.GetFieldName((FieldControl)thisControl));
                script.AppendFormat(@"var criteriaOptions = {0};", Helpers.SerializeJSON <List <CriteriaOption> >(criteriaOptions));

                string criteriaSetPropertyValue = ((IConditionalFormControl)thisControl).CriteriaSet;

                string criteriaSet = "[]";

                if (!String.IsNullOrWhiteSpace(criteriaSetPropertyValue))
                {
                    criteriaSet = criteriaSetPropertyValue;
                }

                script.AppendFormat("var criteria = {0};", criteriaSet);

                script.Append(@"</script>");

                Script.Text = script.ToString();
            }
        }
        protected override void InitializeControls(GenericContainer container)
        {
            IFormFieldControl thisControl     = base.ParentDesigner.PropertyEditor.Control as IFormFieldControl;
            FormDraftControl  thisControlData = base.ParentDesigner.PropertyEditor.ControlData as FormDraftControl;

            FormDescription form = FManager.GetFormByName(thisControlData.Form.Name);

            IControlsContainer cc = GetControlsContainer(form.Id);

            List <ControlData> formControls = (List <ControlData>) typeof(PageHelper)
                                              .GetMethod("SortControls", BindingFlags.Static | BindingFlags.NonPublic)
                                              .Invoke(null, new object[] { new[] { cc }, 1 });

            formControls.RemoveAll(fc => fc.ObjectType == "Telerik.Sitefinity.Modules.Forms.Web.UI.Fields.FormSubmitButton, Telerik.Sitefinity" || fc.IsLayoutControl == true);

            ControlData progressiveKeyFieldControlData = formControls.Where(c => ((FormDraftControl)c).Properties.Any(p => p.Name == "IsProgressiveKeyField" && p.Value == "True")).FirstOrDefault();

            if (progressiveKeyFieldControlData != null)
            {
                FieldControl progressiveKeyFieldControl = FManager.LoadControl(progressiveKeyFieldControlData, CultureInfo.CurrentUICulture) as FieldControl;

                _progressiveKeyFieldName = Helpers.GetFieldName(progressiveKeyFieldControl);

                if (!String.IsNullOrEmpty(_progressiveKeyFieldName) && _progressiveKeyFieldName != Helpers.GetFieldName(thisControl as FieldControl))
                {
                    _disableKeyFieldSelector = true;
                }
            }

            if (!(thisControl is FormTextBox))
            {
                _disableKeyFieldSelector = true;
                _wrongTypeForKeyField    = true;
            }

            if (formControls.Count > 0)
            {
                List <CriteriaOption> progressiveCriteriaOptions = new List <CriteriaOption>();

                CultureInfo uiCulture = CultureInfo.GetCultureInfo(this.GetUICulture());

                foreach (var formControl in formControls)
                {
                    FieldControl fieldControl = FManager.LoadControl(formControl, uiCulture) as FieldControl;

                    CriteriaOption co = new CriteriaOption();

                    co.FieldName = Helpers.GetFieldName(fieldControl);

                    progressiveCriteriaOptions.Add(co);
                }

                StringBuilder script = new StringBuilder();

                script.Append(@"<script>");
                script.AppendFormat(@"var currentProgressiveCulture = ""{0}"";", this.GetUICulture());
                script.AppendFormat(@"var progressiveOptionFilter = ""{0}"";", Helpers.GetFieldName((FieldControl)thisControl));
                script.AppendFormat(@"var progressiveCriteriaOptions = {0};", Helpers.SerializeJSON <List <CriteriaOption> >(progressiveCriteriaOptions));

                string progressiveCriteriaSetPropertyValue = ((IProgressiveFormControl)thisControl).ProgressiveCriteriaSet;
                string criteriaSet = "[]";

                if (!String.IsNullOrWhiteSpace(progressiveCriteriaSetPropertyValue))
                {
                    criteriaSet = progressiveCriteriaSetPropertyValue;
                }

                script.AppendFormat("var progressiveCriteria = {0};", criteriaSet);
                script.Append(@"</script>");

                Script.Text = script.ToString();
            }
        }
        public string GetFirstFieldName(FormsManager formManager, FormDescription form)
        {
            var textFieldControlData = form.Controls.Where(c => c.PlaceHolder == "Body" && c.IsLayoutControl == false).FirstOrDefault();
            var mvcfieldProxy = formManager.LoadControl(textFieldControlData) as MvcWidgetProxy;
            var fieldControl = mvcfieldProxy.Controller as IFormFieldControl;
            var fieldName = fieldControl.MetaField.FieldName;

            return fieldName;
        }
示例#31
0
        private string GetTextFieldName(FormsManager formManager, FormDescription form)
        {
            var textFieldControlData = form.Controls.Where(c => c.PlaceHolder == "Body" && c.IsLayoutControl == false).FirstOrDefault();
            var mvcfieldProxy = formManager.LoadControl(textFieldControlData) as MvcWidgetProxy;
            var textField = mvcfieldProxy.Controller as TextFieldController;

            Assert.IsNotNull(textField, "The text field was not found.");

            var textFieldName = textField.MetaField.FieldName;
            return textFieldName;
        }
示例#32
0
 /// <inheritdoc />
 public void SetForm(FormDescription form)
 {
     this.hasRules     = !string.IsNullOrWhiteSpace(form.Rules);
     this.hiddenFields = FormsHelpers.GetHiddenFields(form.Controls);
     this.fieldNames   = FormsHelpers.GetFieldNames(form.Controls);
 }
示例#33
0
 /// <inheritDoc/>
 public abstract void Render(StreamWriter writer, FormDescription form);
示例#34
0
        new private void SaveFormEntry(FormDescription description)
        {
            FormsManager manager         = FormsManager.GetManager();
            FormEntry    userHostAddress = null;

            if (_isProgressiveForm && _priorFormEntry == null)
            {
                FieldControl keyField = this.FieldControls.Where(fc => ((IFormFieldControl)fc).MetaField.FieldName == _progressiveKeyFieldName).FirstOrDefault() as FieldControl;

                if (keyField != null && !String.IsNullOrWhiteSpace((string)keyField.Value))
                {
                    _priorFormEntry = GetPriorFormEntryByKeyField((string)keyField.Value);
                }
            }

            if (_isProgressiveForm && _priorFormEntry != null)
            {
                string entryType = String.Format("{0}.{1}", manager.Provider.FormsNamespace, this.FormData.Name);

                userHostAddress = manager.GetFormEntry(entryType, _priorFormEntry.Id);
            }
            else
            {
                userHostAddress = manager.CreateFormEntry(string.Format("{0}.{1}", manager.Provider.FormsNamespace, description.Name));
            }

            foreach (IFormFieldControl formFieldControl in this.FieldControls)
            {
                FieldControl fieldControl = formFieldControl as FieldControl;
                object       value        = fieldControl.Value;

                if (fieldControl.GetType().Name == "FormFileUpload")
                {
                    if (formFieldControl.MetaField.FieldName != "")
                    {
                        var uploadValue = value as UploadedFileCollection;
                        var files       = new Dictionary <string, List <FormHttpPostedFile> >();
                        List <FormHttpPostedFile> formHttpPostedFileList = new List <FormHttpPostedFile>();
                        foreach (UploadedFile uploadedFile in uploadValue)
                        {
                            if (uploadedFile != null)
                            {
                                formHttpPostedFileList.Add(new FormHttpPostedFile()
                                {
                                    FileName      = uploadedFile.FileName,
                                    InputStream   = uploadedFile.InputStream,
                                    ContentType   = uploadedFile.ContentType,
                                    ContentLength = uploadedFile.ContentLength
                                });
                            }
                        }

                        files.Add(formFieldControl.MetaField.FieldName, formHttpPostedFileList);
                        var type       = Type.GetType("Telerik.Sitefinity.Modules.Forms.Web.FormsHelper,Telerik.Sitefinity");
                        var method     = type.GetMethod("SaveFiles", BindingFlags.Static | BindingFlags.NonPublic);
                        var updateMode = _priorFormEntry != null;
                        method.Invoke(null, new object[] { files, description, userHostAddress, updateMode });
                    }
                }
                else if (!(value is List <string>))
                {
                    userHostAddress.SetValue(formFieldControl.MetaField.FieldName, value);
                }
                else
                {
                    StringArrayConverter stringArrayConverter = new StringArrayConverter();
                    object obj = stringArrayConverter.ConvertTo((value as List <string>).ToArray(), typeof(string));

                    userHostAddress.SetValue(formFieldControl.MetaField.FieldName, obj);
                }
            }
            userHostAddress.IpAddress   = this.Page.Request.UserHostAddress;
            userHostAddress.SubmittedOn = DateTime.UtcNow;

            Guid userId = ClaimsManager.GetCurrentUserId();

            userHostAddress.UserId = userId == Guid.Empty ? Guid.Parse(_sfTrackingCookie.Value) : userId;

            if (userHostAddress.UserId == userId)
            {
                userHostAddress.Owner = userId;
            }

            if (SystemManager.CurrentContext.AppSettings.Multilingual)
            {
                userHostAddress.Language = CultureInfo.CurrentUICulture.Name;
            }

            FormDescription formData = this.FormData;

            formData.FormEntriesSeed     = formData.FormEntriesSeed + (long)1;
            userHostAddress.ReferralCode = this.FormData.FormEntriesSeed.ToString();

            manager.SaveChanges();
        }
        new private void SaveFormEntry(FormDescription description)
        {
            FormsManager manager = FormsManager.GetManager();
            FormEntry userHostAddress = null;

            if (_isProgressiveForm && _priorFormEntry == null)
            {
                FieldControl keyField = this.FieldControls.Where(fc => ((IFormFieldControl)fc).MetaField.FieldName == _progressiveKeyFieldName).FirstOrDefault() as FieldControl;

                if (keyField != null && !String.IsNullOrWhiteSpace((string)keyField.Value))
                {
                    _priorFormEntry = GetPriorFormEntryByKeyField((string)keyField.Value);
                }
            }

            if (_isProgressiveForm && _priorFormEntry != null)
            {
                string entryType = String.Format("{0}.{1}", manager.Provider.FormsNamespace, this.FormData.Name);

                userHostAddress = manager.GetFormEntry(entryType, _priorFormEntry.Id);
            }
            else
            {
                userHostAddress = manager.CreateFormEntry(string.Format("{0}.{1}", manager.Provider.FormsNamespace, description.Name));
            }
            
            foreach (IFormFieldControl formFieldControl in this.FieldControls)
            {
                FieldControl fieldControl = formFieldControl as FieldControl;
                object value = fieldControl.Value;

                if (fieldControl.GetType().Name == "FormFileUpload")
                {
                    typeof(FormsControl)
                        .GetMethod("SaveFiles", BindingFlags.Static | BindingFlags.NonPublic)
                        .Invoke(null, new object[] { value as UploadedFileCollection, manager, description, userHostAddress, formFieldControl.MetaField.FieldName });
                }
                else if (!(value is List<string>))
                {
                    userHostAddress.SetValue(formFieldControl.MetaField.FieldName, value);
                }
                else
                {
                    StringArrayConverter stringArrayConverter = new StringArrayConverter();
                    object obj = stringArrayConverter.ConvertTo((value as List<string>).ToArray(), typeof(string));

                    userHostAddress.SetValue(formFieldControl.MetaField.FieldName, obj);
                }
            }
            userHostAddress.IpAddress = this.Page.Request.UserHostAddress;
            userHostAddress.SubmittedOn = DateTime.UtcNow;

            Guid userId = ClaimsManager.GetCurrentUserId();

            userHostAddress.UserId = userId == Guid.Empty ? Guid.Parse(_sfTrackingCookie.Value) : userId;

            if (userHostAddress.UserId == userId)
            {
                userHostAddress.Owner = userId;
            }

            if (SystemManager.CurrentContext.AppSettings.Multilingual)
            {
                userHostAddress.Language = CultureInfo.CurrentUICulture.Name;
            }

            FormDescription formData = this.FormData;
            formData.FormEntriesSeed = formData.FormEntriesSeed + (long)1;
            userHostAddress.ReferralCode = this.FormData.FormEntriesSeed.ToString();

            manager.SaveChanges();
        }