Пример #1
0
 private void FormModelOnBeforeAddToIndex(FormModel sender, FormEditorCancelEventArgs formEditorCancelEventArgs)
 {
     if (sender.AllValueFields().Any(f => f.HasSubmittedValue && f.SubmittedValue.Equals("bad", StringComparison.InvariantCultureIgnoreCase)))
     {
         formEditorCancelEventArgs.Cancel       = true;
         formEditorCancelEventArgs.ErrorMessage = "Bad values are not accepted.";
     }
 }
Пример #2
0
 private void FormModelOnBeforeAddToIndex(FormModel sender, FormEditorCancelEventArgs formEditorCancelEventArgs)
 {
     if (sender.AllValueFields().Any(f => f.HasSubmittedValue && f.SubmittedValue.Equals("bad", StringComparison.InvariantCultureIgnoreCase)))
     {
         formEditorCancelEventArgs.Cancel = true;
         // you can supply multiple error messages by using the FormEditorCancelEventArgs.ErrorMessages array,
         // or if you only have one message message, you can simply use the FormEditorCancelEventArgs.ErrorMessage property
         //formEditorCancelEventArgs.ErrorMessage ="Bad values are not accepted.";
         formEditorCancelEventArgs.ErrorMessages = new[] { "Bad values are not accepted.", "Even worse ones aren't either." };
     }
 }
Пример #3
0
        internal static List <FieldWithValue> GetAllFieldsForDisplay(FormModel model, IContent document)
        {
            var allFields = model.AllValueFields().ToList();

            // show logged IPs?
            if (ContentHelper.IpDisplayEnabled(document) && ContentHelper.IpLoggingEnabled(document))
            {
                // IPs are being logged, add a single line text field to retrieve IPs as a string
                allFields.Add(new TextBoxField {
                    Name = "IP", FormSafeName = "_ip"
                });
            }
            return(allFields);
        }
        internal static List <FieldWithValue> GetAllFieldsForDisplay(FormModel model, IContent document, IDictionary <string, PreValue> preValues = null)
        {
            var allFields = model.AllValueFields().ToList();

            preValues = preValues ?? ContentHelper.GetPreValues(document, FormModel.PropertyEditorAlias);

            // show logged IPs?
            if (ContentHelper.IpDisplayEnabled(preValues) && ContentHelper.IpLoggingEnabled(preValues))
            {
                // IPs are being logged, add a single line text field to retrieve IPs as a string
                allFields.Add(new TextBoxField {
                    Name = "IP", FormSafeName = "_ip"
                });
            }
            return(allFields);
        }
Пример #5
0
        public HttpResponseMessage SubmitEntry()
        {
            int id;

            if (int.TryParse(HttpContext.Current.Request.Form["_id"], out id) == false)
            {
                return(ValidationErrorResponse("Could not find _id in the request data"));
            }

            var content = Umbraco.TypedContent(id);

            if (content == null)
            {
                return(ValidationErrorResponse("Could not any content with id {0}", id));
            }

            // set the correct culture for this request
            var domain = Services.DomainService.GetAssignedDomains(content.AncestorOrSelf(1).Id, true).FirstOrDefault();

            if (domain != null && string.IsNullOrEmpty(domain.LanguageIsoCode) == false)
            {
                var culture = new CultureInfo(domain.LanguageIsoCode);
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;
            }

            if (Umbraco.MemberHasAccess(content.Path) == false)
            {
                return(Request.CreateUserNoAccessResponse());
            }

            var property = content.ContentType.PropertyTypes.FirstOrDefault(p => p.PropertyEditorAlias == FormModel.PropertyEditorAlias);

            if (property == null)
            {
                return(ValidationErrorResponse("Could not find any form property on content with id {0}", id));
            }

            FormModel formModel = null;

            try
            {
                formModel = content.GetPropertyValue <FormModel>(property.PropertyTypeAlias);
            }
            catch (Exception ex)
            {
                return(ValidationErrorResponse("Could not extract the form property on content with id {0}: {1}", id, ex.Message));
            }

            var result = formModel.CollectSubmittedValues(content, false);

            if (result == false)
            {
                var errorData = new ValidationErrorData
                {
                    InvalidFields     = formModel.AllValueFields().Where(f => f.Invalid).ForClientSide(),
                    FailedValidations = formModel.Validations.Where(v => v.Invalid).ForClientSide()
                };
                return(ValidationErrorResponse(errorData));
            }

            var successData = new SubmissionSuccessData();

            if (formModel.SuccessPageId <= 0)
            {
                return(SubmissionSuccessResponse(successData));
            }

            var successPage = Umbraco.TypedContent(formModel.SuccessPageId);

            if (successPage == null || !Umbraco.MemberHasAccess(successPage.Path))
            {
                return(SubmissionSuccessResponse(successData));
            }

            successData.RedirectUrl           = Umbraco.NiceUrl(formModel.SuccessPageId);
            successData.RedirectUrlWithDomain = Umbraco.NiceUrlWithDomain(formModel.SuccessPageId);
            return(SubmissionSuccessResponse(successData));
        }
Пример #6
0
        public bool Submit(FormModel formModel, IPublishedContent content)
        {
            if (_configuration.Url == null)
            {
                Log.Warning("Could not submit form data to the web service - the web service endpoint URL was not configured correctly.");
                return(false);
            }

            var client = new WebClient
            {
                Encoding = Encoding.UTF8
            };

            // set content type
            client.Headers[HttpRequestHeader.ContentType] = "application/json";

            if (string.IsNullOrEmpty(_configuration.UserName) == false && string.IsNullOrEmpty(_configuration.Password) == false)
            {
                // basic auth, base64 encode of username:password
                var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", _configuration.UserName, _configuration.Password)));
                client.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
            }

            try
            {
                var webServiceData = new WebServiceData
                {
                    UmbracoContentName = content.Name,
                    UmbracoContentId   = content.Id,
                    IndexRowId         = formModel.RowId.ToString(),
                    FormData           = formModel.AllValueFields().Select(field => new FormFieldData
                    {
                        Name           = field.Name,
                        FormSafeName   = field.FormSafeName,
                        Type           = field.Type,
                        SubmittedValue = field.SubmittedValue
                    }).ToArray(),
                    SubmittedValues = formModel.AllValueFields().ToDictionary(
                        field => field.FormSafeName,
                        field => field.SubmittedValue
                        )
                };

                // serialize to JSON using camel casing
                var data = JsonConvert.SerializeObject(webServiceData, new JsonSerializerSettings {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

                // set content type
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                // POST the JSON and log the response
                var response = client.UploadString(_configuration.Url, "POST", data);
                Log.Info(string.Format("Form data was submitted to endpoint: {0} - response received was: {1}", _configuration.Url, string.IsNullOrEmpty(response) ? "(none)" : response));

                return(true);
            }
            catch (WebException wex)
            {
                using (var reader = new StreamReader(wex.Response.GetResponseStream()))
                {
                    var response = reader.ReadToEnd();
                    Log.Error(wex, string.Format("An error occurred while trying to submit form data to: {0}. Error details: {1}", _configuration.Url, response), null);
                }
                return(false);
            }
            catch (Exception ex)
            {
                Log.Error(ex, string.Format("An error occurred while trying to submit form data to: {0}.", _configuration.Url));
                return(false);
            }
        }