Exemplo n.º 1
0
        protected override DriverResult Editor(ArchivedLinkPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (updater.TryUpdateModel(part, Prefix, null, null))
            {
                try
                {
                    var uri = UriBuilderHelper.TryCreateUri(part.OriginalUrl);
                    _snapshotManager.SaveSnapshot(uri);
                }
                catch (UriFormatException)
                {
                    updater.AddModelError("UriFormatException", T("There was a problem with the given url: {0}", part.OriginalUrl));
                }
                catch (Exception ex)
                {
                    if (ex.IsFatal())
                    {
                        throw;
                    }

                    updater.AddModelError("Exception", T("Unknown problem while saving your url."));
                }
            }

            return(Editor(part, shapeHelper));
        }
        protected override DriverResult Editor(PackagePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var included = _orchardServices.Authorizer.Authorize(Permissions.ManageGallery)
                ? new string[] { "PackageId", "Summary", "ExtensionType", "License", "LicenseUrl", "ProjectUrl", "DownloadCount" }
                : new string[] { "PackageId", "Summary", "ExtensionType", "License", "LicenseUrl", "ProjectUrl" }
            ;

            updater.TryUpdateModel(part, Prefix, included, null);

            // Ensure the package id is unique and valid.

            if (!Regex.IsMatch(part.PackageId, @"^[A-Za-z0-9][A-Za-z0-9\.]+$"))
            {
                updater.AddModelError("PackageId", T("The package id can only contain alpha-numeric characters and dots."));
            }

            // Ensure a package with the same title doesn't already exist.
            else
            {
                var existingPackage = _orchardServices.ContentManager
                                      .Query <PackagePart, PackagePartRecord>(VersionOptions.Published)
                                      .Where(x => x.PackageId == part.PackageId && x.Id != part.Id)
                                      .Slice(0, 1)
                                      .FirstOrDefault();

                if (existingPackage != null)
                {
                    updater.AddModelError("title", T("A package with the same package id already exists."));
                }
            }

            return(Editor(part, shapeHelper));
        }
Exemplo n.º 3
0
        protected override DriverResult Editor(ImageProfilePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var currentName = part.Name;
            var viewModel   = new ImageProfileViewModel();

            // It would be nice if IUpdateModel provided access to the IsValid property of the Controller, instead of having to track a local flag.
            var isValid = updater.TryUpdateModel(viewModel, Prefix, null, null);

            if (String.IsNullOrWhiteSpace(viewModel.Name))
            {
                updater.AddModelError("Name", T("The Name can't be empty."));
                isValid = false;
            }
            if (currentName != viewModel.Name && _imageProfileService.GetImageProfileByName(viewModel.Name) != null)
            {
                updater.AddModelError("Name", T("A profile with the same Name already exists."));
                isValid = false;
            }
            if (viewModel.Name != viewModel.Name.ToSafeName())
            {
                updater.AddModelError("Name", T("The Name can only contain letters and numbers without spaces"));
                isValid = false;
            }

            if (isValid)
            {
                part.Name = viewModel.Name;
            }

            return(Editor(part, shapeHelper));
        }
Exemplo n.º 4
0
        protected override DriverResult Editor(ContentPart part, DateTimeField field, IUpdateModel updater, dynamic shapeHelper)
        {
            var viewModel = new DateTimeFieldViewModel();

            if (updater.TryUpdateModel(viewModel, GetPrefix(field, part), null, null))
            {
                var settings = field.PartFieldDefinition.Settings.GetModel <DateTimeFieldSettings>();
                if (settings.Required && (((settings.Display == DateTimeFieldDisplays.DateAndTime || settings.Display == DateTimeFieldDisplays.DateOnly) && String.IsNullOrWhiteSpace(viewModel.Editor.Date)) || ((settings.Display == DateTimeFieldDisplays.DateAndTime || settings.Display == DateTimeFieldDisplays.TimeOnly) && String.IsNullOrWhiteSpace(viewModel.Editor.Time))))
                {
                    updater.AddModelError(GetPrefix(field, part), T("{0} is required.", field.DisplayName));
                }
                else
                {
                    try {
                        var utcDateTime = DateServices.ConvertFromLocalString(viewModel.Editor.Date, viewModel.Editor.Time);
                        if (utcDateTime.HasValue)
                        {
                            field.DateTime = utcDateTime.Value;
                        }
                        else
                        {
                            field.DateTime = DateTime.MinValue;
                        }
                    }
                    catch (FormatException) {
                        updater.AddModelError(GetPrefix(field, part), T("{0} could not be parsed as a valid date and time.", field.DisplayName));
                    }
                }
            }

            return(Editor(part, field, shapeHelper));
        }
        protected override DriverResult Editor(WidgetPart widgetPart, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(widgetPart, Prefix, null, null);

            if (string.IsNullOrWhiteSpace(widgetPart.Title))
            {
                updater.AddModelError("Title", T("Title can't be empty."));
            }

            // if there is a name, ensure it's unique
            if (!string.IsNullOrWhiteSpace(widgetPart.Name))
            {
                widgetPart.Name = widgetPart.Name.ToHtmlName();

                var widgets = _contentManager.Query <WidgetPart, WidgetPartRecord>().Where(x => x.Name == widgetPart.Name && x.Id != widgetPart.Id).Count();
                if (widgets > 0)
                {
                    updater.AddModelError("Name", T("A Widget with the same Name already exists."));
                }
            }

            _widgetsService.MakeRoomForWidgetPosition(widgetPart);

            return(Editor(widgetPart, shapeHelper));
        }
        protected override DriverResult Editor(NewsletterEditionPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            int newsId = 0;

            int.TryParse(_requestContext.HttpContext.Request.RequestContext.RouteData.Values["newsletterId"].ToString(), out newsId);
            int[] selectedAnnouncementsIds = !String.IsNullOrWhiteSpace(part.AnnouncementIds) ? part.AnnouncementIds.Split(',').Select(s => Convert.ToInt32(s)).ToArray() : null;
            var   model = new NewsletterEditionViewModel {
                NewsletterEditionPart = part,
                AnnouncementToAttach  = part.Dispatched ? null : _newslServices.GetNextAnnouncements((int)newsId, selectedAnnouncementsIds)
            };

            if (!updater.TryUpdateModel(model, Prefix, null, null))
            {
                updater.AddModelError("NewsletterEditionPartError", T("NewsletterEdition Error"));
            }
            if (!part.Dispatched)
            {
                part.AnnouncementIds = String.Join(",", model.AnnouncementToAttach.Where(w => w.Selected).Select(s => s.Id));
            }
            else
            {
                updater.AddModelError("NewsletterEditionPartError", T("Dispatched newsletter can't be updated!"));
            }

            return(Editor(part, shapeHelper));
        }
Exemplo n.º 7
0
        protected override DriverResult Editor(UserPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var editModel = new UserEditPasswordViewModel {
                User = part
            };

            if (updater != null)
            {
                if (updater.TryUpdateModel(editModel, Prefix, null, null))
                {
                    if (!(string.IsNullOrEmpty(editModel.Password) && string.IsNullOrEmpty(editModel.ConfirmPassword)))
                    {
                        if (string.IsNullOrEmpty(editModel.Password) || string.IsNullOrEmpty(editModel.ConfirmPassword))
                        {
                            updater.AddModelError("MissingPassword", T("Password or Confirm Password field is empty."));
                        }
                        else
                        {
                            if (editModel.Password != editModel.ConfirmPassword)
                            {
                                updater.AddModelError("ConfirmPassword", T("Password confirmation must match."));
                            }
                            var actUser = _membershipService.GetUser(part.UserName);
                            _membershipService.SetPassword(actUser, editModel.Password);
                        }
                    }
                }
            }
            return(Editor(part, shapeHelper));
        }
Exemplo n.º 8
0
        protected override DriverResult Editor(ContentPart part, Fields.MediaPickerField field, IUpdateModel updater, dynamic shapeHelper)
        {
            // if the model could not be bound, don't try to validate its properties
            if (updater.TryUpdateModel(field, GetPrefix(field, part), null, null))
            {
                var settings = field.PartFieldDefinition.Settings.GetModel <MediaPickerFieldSettings>();

                var extensions = String.IsNullOrWhiteSpace(settings.AllowedExtensions)
                        ? new string[0]
                        : settings.AllowedExtensions.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (extensions.Any() && field.Url != null && !extensions.Any(x => field.Url.EndsWith(x, StringComparison.OrdinalIgnoreCase)))
                {
                    updater.AddModelError("Url", T("The field {0} must be have one of these extensions: {1}", field.Name.CamelFriendly(), settings.AllowedExtensions));
                }

                if (settings.Required && String.IsNullOrWhiteSpace(field.Url))
                {
                    updater.AddModelError("Url", T("The field {0} is mandatory", field.Name.CamelFriendly()));
                }

                if (!String.IsNullOrWhiteSpace(field.Url) && !_webSiteFolder.FileExists(field.Url))
                {
                    updater.AddModelError("Url", T("The media in {0} could not be found", field.Name.CamelFriendly()));
                }
            }

            return(Editor(part, field, shapeHelper));
        }
 protected override DriverResult Editor(ArticlePermissionPart part, IUpdateModel updater, dynamic shapeHelper)
 {
     updater.TryUpdateModel(part, Prefix, null, null);
     if (part.IsEnabled)
     {
         if (string.IsNullOrWhiteSpace(part.Permissions))
         {
             updater.AddModelError(Prefix, T("Please choose positions which have right to view this content."));
         }
         else
         {
             try
             {
                 var permissionSplited = part.Permissions.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToArray();
                 if (_departmentService.CheckPositionsDepartment(permissionSplited))
                 {
                     part.Permissions = string.Join(",", permissionSplited);
                 }
                 else
                 {
                     updater.AddModelError(Prefix, T("Tempar data."));
                 }
             }
             catch
             {
                 updater.AddModelError(Prefix, T("Invalid contents in permissions string."));
             }
         }
     }
     else
     {
         part.Permissions = string.Empty;
     }
     return(Editor(part, shapeHelper));
 }
Exemplo n.º 10
0
 protected override DriverResult Editor(ContentPart part, NumberField field, IUpdateModel updater, dynamic shapeHelper)
 {
     if (updater.TryUpdateModel(field, GetPrefix(field, part), null, null))
     {
         var settings = field.PartFieldDefinition.Settings.GetModel <NumberFieldSettings>();
         if (settings.Required && !field.Value.HasValue)
         {
             updater.AddModelError(field.Name, T("The field {0} is required.", T(field.DisplayName)));
         }
         if (field.Value.HasValue)
         {
             var intPart = Math.Floor(field.Value.Value);
             var decPart = field.Value.Value - intPart;
             if (intPart.ToString().Length > settings.Length)
             {
                 updater.AddModelError(GetPrefix(field, part), T("The integer part of field {0} is overlength.", T(field.DisplayName)));
             }
             if (decPart.ToString().Length > settings.DecimalPlaces + 2)
             {
                 updater.AddModelError(GetPrefix(field, part), T("The decimal part of field {0} is overlength.", T(field.DisplayName)));
             }
         }
     }
     return(Editor(part, field, shapeHelper));
 }
Exemplo n.º 11
0
        protected override DriverResult Editor(KeepAliveSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part.Record, Prefix, null, null);

            // ensure the url is well formed
            if (part.Record.Enabled && !part.Record.Url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                updater.AddModelError("Url", T("The Keep Alive url must begin with http://"));
            }
            else
            {
                // try a request
                try {
                    var url = VirtualPathUtility.AppendTrailingSlash(part.Record.Url) + "keepalive";

                    var request = WebRequest.Create(url) as HttpWebRequest;
                    if (request != null)
                    {
                        using (request.GetResponse() as HttpWebResponse) { }
                    }
                }
                catch (Exception e) {
                    updater.AddModelError("Url", T("There was an error when querying the Keep Alive url: {0}", e.Message));
                }
            }

            return(Editor(part, shapeHelper));
        }
        protected override DriverResult Editor(ObjectiveResultPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var viewModel = new ObjectiveResultEditorViewModel();

            if (updater.TryUpdateModel(viewModel, Prefix, null, new string[] { "Presets" }))
            {
                var objective = _objectiveService.Get(viewModel.ObjectiveId, VersionOptions.Latest);
                if (objective == null)
                {
                    updater.AddModelError("ObjectiveId", T("Objective not found"));
                }
                var team = _teamService.Get(viewModel.TeamId, VersionOptions.Latest);
                if (team == null)
                {
                    updater.AddModelError("TeamId", T("Team not found"));
                }

                if (objective != null && team != null)
                {
                    part.Points      = viewModel.Points;
                    part.DisplayName = viewModel.DisplayName;
                    part.Team        = team.Record;
                    part.Objective   = objective.Record;
                }
            }

            return(Editor(part, (object)shapeHelper));
        }
Exemplo n.º 13
0
        protected override DriverResult Editor(ProductPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, this.Prefix, null, null);

            if (part.FromUrl)
            {
                if (String.IsNullOrEmpty(part.CatalogCodeUrlParameterKey))
                {
                    updater.AddModelError("CatalogCodeUrlParameterKeyRequired", this._localizer("Catalog code url parameter key is required"));
                }
                if (String.IsNullOrEmpty(part.SKUUrlParameterKey))
                {
                    updater.AddModelError("SKUUrlParameterKeyRequired", this._localizer("SKU url parameter key is required"));
                }
            }
            else
            {
                if (String.IsNullOrEmpty(part.CatalogCode))
                {
                    updater.AddModelError("CatalogCodeRequired", this._localizer("Catalog code is required"));
                }
                if (String.IsNullOrEmpty(part.SKU))
                {
                    updater.AddModelError("SKUUrlParameterKeyRequired", this._localizer("SKU is required"));
                }
            }
            return(this.Editor(part, shapeHelper));
        }
Exemplo n.º 14
0
 protected override DriverResult Editor(TeacherPart part, IUpdateModel updater, dynamic shapeHelper)
 {
     if (updater.TryUpdateModel(part, Prefix, null, null))
     {
         if (string.IsNullOrWhiteSpace(part.PositionsDepartments))
         {
             updater.AddModelError(Prefix, T("Please choose positions which this teacher belongs to."));
         }
         else
         {
             try
             {
                 var positionsSplited = part.PositionsDepartments.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToArray();
                 if (_departmentService.CheckPositionsDepartment(positionsSplited))
                 {
                     part.PositionsDepartments = string.Join(",", positionsSplited);
                 }
                 else
                 {
                     updater.AddModelError(Prefix, T("Tempar data."));
                 }
             }
             catch
             {
                 updater.AddModelError(Prefix, T("Invalid contents in string."));
             }
         }
     }
     return(Editor(part, shapeHelper));
 }
Exemplo n.º 15
0
        protected override DriverResult Editor(PublishLaterPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var model = new PublishLaterViewModel(part);

            updater.TryUpdateModel(model, Prefix, null, null);

            if (Services.WorkContext.Resolve <IHttpContextAccessor>().Current().Request.Form["submit.Save"] == "submit.PublishLater")
            {
                if (!string.IsNullOrWhiteSpace(model.ScheduledPublishDate) && !string.IsNullOrWhiteSpace(model.ScheduledPublishTime))
                {
                    DateTime scheduled;
                    string   parseDateTime = String.Concat(model.ScheduledPublishDate, " ", model.ScheduledPublishTime);

                    // use an english culture as it is the one used by jQuery.datepicker by default
                    if (DateTime.TryParse(parseDateTime, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AssumeLocal, out scheduled))
                    {
                        model.ScheduledPublishUtc = part.ScheduledPublishUtc.Value = scheduled.ToUniversalTime();
                        _publishLaterService.Publish(model.ContentItem, model.ScheduledPublishUtc.Value);
                    }
                    else
                    {
                        updater.AddModelError(Prefix, T("{0} is an invalid date and time", parseDateTime));
                    }
                }
                else if (!string.IsNullOrWhiteSpace(model.ScheduledPublishDate) || !string.IsNullOrWhiteSpace(model.ScheduledPublishTime))
                {
                    updater.AddModelError(Prefix, T("Both the date and time need to be specified for when this is to be published. If you don't want to schedule publishing then click Save or Publish Now."));
                }
            }

            return(ContentShape("Parts_PublishLater_Edit",
                                () => shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: model, Prefix: Prefix)));
        }
        protected override DriverResult Editor(SubscriberRegistrationPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (!updater.TryUpdateModel(part, Prefix, null, null))
            {
                updater.AddModelError("SubscriberRegistrationPartError", T("SubscriberRegistration Error"));
            }
            var selectedNews = HttpContext.Current.Request.Form[Prefix + ".Subscription_Newsletters_Ids"];

            if (selectedNews == null)
            {
                updater.AddModelError("SubscriberRegistrationPartNewsletterError", T("Subscription for newsletters not found"));
            }
            else
            {
                selectedNews = String.Join(",", selectedNews.Split(',').Where(w => w != "false"));

                if (string.IsNullOrEmpty(selectedNews))
                {
                    updater.AddModelError("SubscriberRegistrationPartValidationError", T("Subscription for newsletters is mandatory"));
                }
                else
                {
                    part.NewsletterDefinitionIds = selectedNews;
                }
            }

            return(Editor(part, shapeHelper));
        }
Exemplo n.º 17
0
        // POST
        protected override DriverResult Editor(CustomerAddressPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var httpContext = Services.WorkContext.HttpContext;

            if (updater.TryUpdateModel(part, Prefix, null, null))
            {
                if (part.CountryId <= 0)
                {
                    updater.AddModelError("CountryId", T("Please select your country."));
                }
                else
                {
                    var states = _locationService.GetStates(part.CountryId);
                    if (states.Any())
                    {
                        if (part.StateId <= 0 || !states.Where(s => s.Id == part.StateId).Any())
                        {
                            updater.AddModelError("StateId", T("Please select your state."));
                        }
                    }
                }

                int customerId;
                if (Int32.TryParse(httpContext.Request.Form[Prefix + ".CustomerId"], out customerId) && Services.Authorizer.Authorize(Permissions.CustomersPermissions.ManageCustomerAccounts))
                {
                    part.Customer = _customersService.GetCustomer(customerId);
                }
                else if (part.Customer == null)
                {
                    part.Customer = _customersService.GetCustomer();
                }
            }

            return(Editor(part, shapeHelper));
        }
Exemplo n.º 18
0
        protected override DriverResult Editor(ContentPart part, MultiDateField field, IUpdateModel updater, dynamic shapeHelper)
        {
            var viewModel = new MultiDateFieldViewModel();

            if (updater.TryUpdateModel(viewModel, GetPrefix(field, part), null, null))
            {
                var settings = field.PartFieldDefinition.Settings.GetModel <MultiDateFieldSettings>();

                if (settings.Required && string.IsNullOrEmpty(viewModel.DatesString))
                {
                    updater.AddModelError(GetPrefix(field, part), T("{0} is required.", field.DisplayName));
                }
                else
                {
                    try {
                        _multiDateService.ParseMultiDates(viewModel.DatesString);
                        field.Value = viewModel.DatesString;
                    }
                    catch {
                        updater.AddModelError(GetPrefix(field, part), T("{0} could not be parsed as a valid date.", field.DisplayName));
                    }
                }
            }

            return(Editor(part, field, shapeHelper));
        }
        protected override DriverResult Editor(ContentPart part, MediaGalleryField field, IUpdateModel updater, dynamic shapeHelper)
        {
            var model = new MediaGalleryFieldViewModel();

            updater.TryUpdateModel(model, GetPrefix(field, part), null, null);

            var settings = field.PartFieldDefinition.Settings.GetModel <MediaGalleryFieldSettings>();

            if (String.IsNullOrEmpty(model.SelectedItems))
            {
                field.SelectedItems = "[]";
            }
            else
            {
                field.SelectedItems = model.SelectedItems;
            }

            var allItems = _jsonConverter.Deserialize <MediaGalleryItem[]>(field.SelectedItems);

            if (settings.Required && allItems.Length == 0)
            {
                updater.AddModelError("SelectedItems", T("The field {0} is mandatory", field.Name.CamelFriendly()));
            }

            if (!settings.Multiple && allItems.Length > 1)
            {
                updater.AddModelError("SelectedItems", T("The field {0} doesn't accept multiple media items", field.Name.CamelFriendly()));
            }

            return(Editor(part, field, shapeHelper));
        }
Exemplo n.º 20
0
        protected override DriverResult Editor(LayerPart layerPart, IUpdateModel updater, dynamic shapeHelper)
        {
            if (updater.TryUpdateModel(layerPart, Prefix, null, null))
            {
                if (String.IsNullOrWhiteSpace(layerPart.LayerRule))
                {
                    layerPart.LayerRule = "true";
                }

                if (_widgetsService.GetLayers()
                    .Any(l =>
                         l.Id != layerPart.Id &&
                         String.Equals(l.Name, layerPart.Name, StringComparison.InvariantCultureIgnoreCase)))
                {
                    updater.AddModelError("Name", T("A Layer with the same name already exists"));
                }

                try {
                    _ruleManager.Matches(layerPart.LayerRule);
                }
                catch (Exception e) {
                    updater.AddModelError("Description", T("The rule is not valid: {0}", e.Message));
                }
            }

            return(Editor(layerPart, shapeHelper));
        }
        protected override DriverResult Editor(PackageVersionPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var model = new EditPackageVersionViewModel {
            };

            updater.TryUpdateModel(model, Prefix, new string[] { "PackageId" }, null);

            // Ensure the use owns the package for this package version
            var packagesForUser = GetPackagePartsForUser();

            if (!packagesForUser.Any(x => x.Id == model.PackageId))
            {
                updater.AddModelError("", T("You are not allowed to add a version to this package."));
            }

            model.PackageVersionPart = part;
            model.PackageVersionPart.CommonPart.Container = _orchardServices.ContentManager.Get(model.PackageId);

            var exclude = _orchardServices.Authorizer.Authorize(Permissions.ManageGallery)
                ? null
                : new string[] { "PackageVersionPart.DownloadCount" }
            ;

            updater.TryUpdateModel(model, Prefix, null, exclude);

            Version version;

            if (!Version.TryParse(model.PackageVersionPart.Version, out version))
            {
                updater.AddModelError("PackageVersionPart.Version", T("Invalid version."));
            }

            return(Editor(part, shapeHelper));
        }
        protected override DriverResult Editor(DynamicProjectionPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            //if (!_authorizationService.TryCheckAccess(DynamicProjectionPermission.ManageContentMenus, _orchardServices.WorkContext.CurrentUser, part))
            //    return null;
            var newmodel = new DynamicProjectionVM();

            updater.TryUpdateModel(newmodel, Prefix, null, null);

            if (newmodel.Part.OnAdminMenu)
            {
                if (string.IsNullOrEmpty(newmodel.Part.AdminMenuText))
                {
                    updater.AddModelError("AdminMenuText", T("The AdminMenuText field is required"));
                }

                if (string.IsNullOrEmpty(newmodel.Part.AdminMenuPosition))
                {
                    newmodel.Part.AdminMenuPosition = "2";// GetDefaultPosition(part);
                }
            }
            else
            {
                newmodel.Part.AdminMenuPosition = "";
            }
            Mapper.Initialize(cfg => {
                cfg.CreateMap <DynamicProjectionPartVM, DynamicProjectionPart>();
            });
            Mapper.Map <DynamicProjectionPartVM, DynamicProjectionPart>(newmodel.Part, part);
            //           part.FormFile = newmodel.FormFile;
            // projection
            var model = newmodel.Projection;



            part.Record.DisplayPager = model.DisplayPager;
            part.Record.Items        = model.Items;
            part.Record.ItemsPerPage = model.ItemsPerPage;
            part.Record.Skip         = model.Skip;
            part.Record.MaxItems     = model.MaxItems;
            part.Record.PagerSuffix  = (model.PagerSuffix ?? String.Empty).Trim();

            if (model.QueryLayoutRecordId != null)
            {
                var queryLayoutIds = model.QueryLayoutRecordId.Split(new[] { ';' });
                part.Record.QueryPartRecord = _queryRepository.Get(Int32.Parse(queryLayoutIds[0]));
                part.Record.LayoutRecord    = part.Record.QueryPartRecord.Layouts.FirstOrDefault(x => x.Id == Int32.Parse(queryLayoutIds[1]));
            }
            if (!String.IsNullOrWhiteSpace(part.Record.PagerSuffix) && !String.Equals(part.Record.PagerSuffix.ToSafeName(), part.Record.PagerSuffix, StringComparison.OrdinalIgnoreCase))
            {
                updater.AddModelError("PagerSuffix", T("Suffix should not contain special characters."));
            }

            //


            return(Editor(part, shapeHelper));
        }
Exemplo n.º 23
0
        protected override DriverResult Editor(ContentPart part, DateTimeField field, IUpdateModel updater, dynamic shapeHelper)
        {
            var viewModel = new DateTimeFieldViewModel();

            if (updater.TryUpdateModel(viewModel, GetPrefix(field, part), null, null))
            {
                var settings = field.PartFieldDefinition.Settings.GetModel <DateTimeFieldSettings>();

                var options = new DateLocalizationOptions();

                // Don't do any time zone conversion if field is semantically a date-only field, because that might mutate the date component.
                if (settings.Display == DateTimeFieldDisplays.DateOnly)
                {
                    options.EnableTimeZoneConversion = false;
                }

                // Don't do any calendar conversion if field is semantically a time-only field, because the date component might we out of allowed boundaries for the current calendar.
                if (settings.Display == DateTimeFieldDisplays.TimeOnly)
                {
                    options.EnableCalendarConversion = false;
                    options.IgnoreDate = true;
                }

                var showDate = settings.Display == DateTimeFieldDisplays.DateAndTime || settings.Display == DateTimeFieldDisplays.DateOnly;
                var showTime = settings.Display == DateTimeFieldDisplays.DateAndTime || settings.Display == DateTimeFieldDisplays.TimeOnly;

                DateTime?value = null;

                // Try to parse data if not required or if there are no missing fields.
                if (!settings.Required || ((!showDate || !String.IsNullOrWhiteSpace(viewModel.Editor.Date)) && (!showTime || !String.IsNullOrWhiteSpace(viewModel.Editor.Time))))
                {
                    try {
                        value = DateLocalizationServices.ConvertFromLocalizedString(viewModel.Editor.Date, viewModel.Editor.Time, options);
                    }
                    catch {
                        updater.AddModelError(GetPrefix(field, part), T("{0} could not be parsed as a valid date and time.", T(field.DisplayName)));
                    }
                }

                // Hackish workaround to make sure a time-only field with an entered time equivalent to
                // 00:00 UTC doesn't get stored as a full DateTime.MinValue in the database, resulting
                // in it being interpreted as an empty value when subsequently retrieved.
                if (value.HasValue && settings.Display == DateTimeFieldDisplays.TimeOnly && value == DateTime.MinValue)
                {
                    value = value.Value.AddDays(1);
                }

                if (settings.Required && (!value.HasValue || (settings.Display != DateTimeFieldDisplays.TimeOnly && value.Value.Date == DateTime.MinValue)))
                {
                    updater.AddModelError(GetPrefix(field, part), T("{0} is required.", T(field.DisplayName)));
                }

                field.DateTime = value.HasValue ? value.Value : DateTime.MinValue;
            }

            return(Editor(part, field, shapeHelper));
        }
Exemplo n.º 24
0
        protected override DriverResult Editor(SiteSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var site  = _siteService.GetSiteSettings().As <SiteSettingsPart>();
            var model = new SiteSettingsPartViewModel {
                Site         = site,
                SiteCultures = _cultureManager.ListCultures(),
                TimeZones    = TimeZoneInfo.GetSystemTimeZones()
            };

            var previousBaseUrl = model.Site.BaseUrl;

            updater.TryUpdateModel(model, Prefix, null, null);

            // ensures the super user is fully empty
            if (String.IsNullOrEmpty(model.SuperUser))
            {
                model.SuperUser = String.Empty;
            }
            // otherwise the super user must be a valid user, to prevent an external account to impersonate as this name
            //the user management module ensures the super user can't be deleted, but it can be disabled
            else
            {
                if (_membershipService.GetUser(model.SuperUser) == null)
                {
                    updater.AddModelError("SuperUser", T("The user {0} was not found", model.SuperUser));
                }
            }


            // ensure the base url is absolute if provided
            if (!String.IsNullOrWhiteSpace(model.Site.BaseUrl))
            {
                if (!Uri.IsWellFormedUriString(model.Site.BaseUrl, UriKind.Absolute))
                {
                    updater.AddModelError("BaseUrl", T("The base url must be absolute."));
                }
                // if the base url has been modified, try to ping it
                else if (!String.Equals(previousBaseUrl, model.Site.BaseUrl, StringComparison.OrdinalIgnoreCase))
                {
                    try {
                        var request = WebRequest.Create(model.Site.BaseUrl) as HttpWebRequest;
                        if (request != null)
                        {
                            using (request.GetResponse() as HttpWebResponse) {}
                        }
                    }
                    catch (Exception e) {
                        _notifier.Warning(T("The base url you entered could not be requested from current location."));
                        Logger.Warning(e, "Could not query base url: {0}", model.Site.BaseUrl);
                    }
                }
            }

            return(ContentShape("Parts_Settings_SiteSettingsPart",
                                () => shapeHelper.EditorTemplate(TemplateName: "Parts.Settings.SiteSettingsPart", Model: model, Prefix: Prefix)));
        }
Exemplo n.º 25
0
        protected override DriverResult Editor(FolderPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (!this.contentOwnershipService.CurrentUserCanEditContent(part.ContentItem))
            {
                throw new Security.OrchardSecurityException(T("You don't have permission to create/edit the item"));
            }

            PostedEditFolderViewModel model = new PostedEditFolderViewModel();

            updater.TryUpdateModel(model, Prefix, null, null);

            EditAttachToViewModel attachToProjectModel = new EditAttachToViewModel();

            updater.TryUpdateModel(attachToProjectModel, "AttachToProjectPart", null, null);

            // not valid
            if (attachToProjectModel.SelectedId == null)
            {
                updater.AddModelError("AttachToProjectPart.ProjectId", T("No project is selected"));
                return(this.Editor(part, shapeHelper));
            }

            var project = this.projectService.GetProject(attachToProjectModel.SelectedId.Value);

            if (project == null)
            {
                throw new OrchardCoreException(T("There is no project with the given Id"));
            }

            // check user has access to the project
            if (!this.contentOwnershipService.CurrentUserCanEditContent(project))
            {
                throw new Security.OrchardSecurityException(T("You don't have permission to create/edit the item"));
            }

            // A folder can not be parent of himself or a sub-folder can not be parent of his parents
            if (model.ParentId != null)
            {
                var folders   = this.folderService.GetFolders(attachToProjectModel.SelectedId.Value).Select(c => c.As <FolderPart>());
                var ancestors = this.folderService.GetAncestors(folders, model.ParentId.Value).Select(c => c.Id).ToList();
                ancestors.Add(part.Id);

                if (ancestors.Any(c => c == model.ParentId.Value))
                {
                    updater.AddModelError("FolderPart.ParentId", T("A Folder can not be parent of himself. Please select another folder."));
                    return(this.Editor(part, shapeHelper));
                }
            }

            part.Record.Title     = model.Title;
            part.Record.Parent_Id = model.ParentId;


            return(this.Editor(part, shapeHelper));
        }
        protected override DriverResult Editor(ReCaptchaPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var workContext = _workContextAccessor.GetContext();
            var settings    = workContext.CurrentSite.As <ReCaptchaSettingsPart>();

            // don't display the part in the admin
            if (AdminFilter.IsApplied(workContext.HttpContext.Request.RequestContext))
            {
                return(null);
            }

            if (settings.TrustAuthenticatedUsers && workContext.CurrentUser != null)
            {
                return(null);
            }

            var context = workContext.HttpContext;

            try {
                var result = ExecuteValidateRequest(
                    settings.PrivateKey,
                    context.Request.ServerVariables["REMOTE_ADDR"],
                    context.Request.Form["g-recaptcha-response"]
                    );

                ReCaptchaPartResponseModel responseModel = _jsonConverter.Deserialize <ReCaptchaPartResponseModel>(result);

                if (!responseModel.Success)
                {
                    foreach (var errorCode in responseModel.ErrorCodes)
                    {
                        if (errorCode == "missing-input-response")
                        {
                            updater.AddModelError("", T("Please prove that you are not a bot."));
                            _notifier.Error(T("Please prove that you are not a bot."));
                        }
                        else
                        {
                            Logger.Information("An error occurred while submitting a reCaptcha: " + errorCode);
                            updater.AddModelError("", T("An error occurred while submitting a reCaptcha."));
                            _notifier.Error(T("An error occurred while submitting a reCaptcha."));
                        }
                    }
                }
            }
            catch (Exception e) {
                Logger.Error(e, "An unexcepted error occurred while submitting a reCaptcha.");
                updater.AddModelError("", T("There was an error while validating the Captcha."));
                _notifier.Error(T("There was an error while validating the Captcha."));
            }

            return(Editor(part, shapeHelper));
        }
Exemplo n.º 27
0
        protected override DriverResult Editor(QuestionnairePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            QuestionnaireEditModel editModel = new QuestionnaireEditModel();

            editModel = _questServices.BuildEditModelForQuestionnairePart(part);
            try {
                if (updater.TryUpdateModel(editModel, Prefix, null, null))
                {
                    if (part.ContentItem.Id != 0)
                    {
                        // se per caso part.Id è diversa dall'Id registrato nei record relazionati, arrivo da una traduzione, quindi devo trattare tutto come se fosse questions e answers nuove
                        foreach (var q in editModel.Questions)
                        {
                            if (part.Id != q.QuestionnairePartRecord_Id)
                            {
                                q.QuestionnairePartRecord_Id = part.Id;
                                q.Id = 0;
                            }

                            foreach (var a in q.Answers)
                            {
                                if (q.Id == 0)
                                {
                                    a.Id = 0;
                                }
                            }
                        }
                        try {
                            _questServices.UpdateForContentItem(
                                part.ContentItem, editModel);
                        }
                        catch (Exception ex) {
                            updater.AddModelError("QuestionnaireUpdateError", T("Cannot update questionnaire. " + ex.Message));
                            _controllerContextAccessor.Context.Controller.TempData[Prefix + "ModelWithErrors"] = editModel;
                        }
                    }
                }
                else
                {
                    updater.AddModelError("QuestionnaireUpdateError", T("Cannot update questionnaire"));
                    _controllerContextAccessor.Context.Controller.TempData[Prefix + "ModelWithErrors"] = editModel;
                }
            }
            catch (Exception ex) {
                updater.AddModelError("QuestionnaireUpdateError", T("Cannot update questionnaire....... " + ex.Message + ex.StackTrace));
                _controllerContextAccessor.Context.Controller.TempData[Prefix + "ModelWithErrors"] = editModel;
            }
            return(Editor(part, shapeHelper));
        }
Exemplo n.º 28
0
        protected override DriverResult Editor(ContentPart part, Fields.SecureFileField field, IUpdateModel updater, dynamic shapeHelper)
        {
            WorkContext wc   = _workContextAccessor.GetContext();
            var         file = wc.HttpContext.Request.Files["FileField-" + field.Name];

            // if the model could not be bound, don't try to validate its properties
            if (updater.TryUpdateModel(field, GetPrefix(field, part), null, null))
            {
                var settings = field.PartFieldDefinition.Settings.GetModel <SecureFileFieldSettings>();

                var extensions = String.IsNullOrWhiteSpace(settings.AllowedExtensions)
                        ? new string[0]
                        : settings.AllowedExtensions.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                try {
                    if (file != null && file.ContentLength > 0)
                    {
                        string fname = Path.GetFileName(file.FileName);
                        field.Url = fname;
                        IStorageProvider provider;

                        provider = new SecureFileStorageProvider(settings.SecureDirectoryName);

                        int    length = (int)file.ContentLength;
                        byte[] buffer = new byte[length];
                        using (Stream stream = file.InputStream) {
                            stream.Read(buffer, 0, length);
                        }

                        provider.Insert(fname, buffer, file.ContentType, length, true);
                    }
                }
                catch (Exception) {
                    throw;
                }

                if (extensions.Any() && field.Url != null && !extensions.Any(x => field.Url.EndsWith(x, StringComparison.OrdinalIgnoreCase)))
                {
                    updater.AddModelError("Url", T("The field {0} must have one of these extensions: {1}", field.Name.CamelFriendly(), settings.AllowedExtensions));
                }

                if (settings.Required && String.IsNullOrWhiteSpace(field.Url))
                {
                    updater.AddModelError("Url", T("The field {0} is mandatory", field.Name.CamelFriendly()));
                }
            }

            return(Editor(part, field, shapeHelper));
        }
Exemplo n.º 29
0
        protected override DriverResult Editor(OpenGraphMetaTagsPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (updater.TryUpdateModel(part, Prefix, null, null))
            {
                part.OpenGraphTagsSettings = _wca.GetContext().CurrentSite.As <OpenGraphMetaTagsSettingsPart>();
                part.DefaultSettings       = part.TypePartDefinition.Settings.GetModel <OpenGraphMetaTagsPartSettings>();

                //Validation as per selections
                if (part.OpenGraphTagsSettings.OgTitleTagEnabled && part.OpenGraphTagsSettings.OgTitleTagRequired &&
                    String.IsNullOrWhiteSpace(part.OgTitle))
                {
                    updater.AddModelError("_FORM", T("Open Graph Title field is required"));
                }

                if (part.OpenGraphTagsSettings.OgTypeTagEnabled && part.OpenGraphTagsSettings.OgTypeTagRequired &&
                    part.OgType == "select")
                {
                    updater.AddModelError("_FORM", T("Open Graph Type field is required"));
                }

                if (part.OpenGraphTagsSettings.OgImageTagEnabled && part.OpenGraphTagsSettings.OgImageTagRequired &&
                    String.IsNullOrWhiteSpace(part.OgImage))
                {
                    updater.AddModelError("_FORM", T("Open Graph Image field is required"));
                }

                if (part.OpenGraphTagsSettings.OgUrlTagEnabled && part.OpenGraphTagsSettings.OgUrlTagRequired &&
                    String.IsNullOrWhiteSpace(part.OgUrl))
                {
                    updater.AddModelError("_FORM", T("Open Graph Url field is required"));
                }

                if (part.OpenGraphTagsSettings.OgDescriptionTagEnabled && part.OpenGraphTagsSettings.OgDescriptionTagRequired &&
                    String.IsNullOrWhiteSpace(part.OgDescription))
                {
                    updater.AddModelError("_FORM", T("Open Graph Description field is required"));
                }

                if (part.OpenGraphTagsSettings.OgLocaleTagEnabled && part.OpenGraphTagsSettings.OgLocaleTagRequired &&
                    String.IsNullOrWhiteSpace(part.OgLocale))
                {
                    updater.AddModelError("_FORM", T("Open Graph Locale field is required"));
                }

                if (part.OpenGraphTagsSettings.OgSiteNameTagEnabled && part.OpenGraphTagsSettings.OgSiteNameTagRequired &&
                    String.IsNullOrWhiteSpace(part.OgSiteName))
                {
                    updater.AddModelError("_FORM", T("Open Graph Site Name field is required"));
                }

                if (part.OpenGraphTagsSettings.FbAdminTagEnabled && part.OpenGraphTagsSettings.FbAdminTagRequired &&
                    String.IsNullOrWhiteSpace(part.FBAdmins))
                {
                    updater.AddModelError("_FORM", T("FB Admins field is required"));
                }
            }
            return(Editor(part, shapeHelper));
        }
Exemplo n.º 30
0
        public override IEnumerable<TemplateViewModel> PartFieldEditorUpdate(ContentPartFieldDefinitionBuilder builder, IUpdateModel updateModel) {
            if (builder.FieldType != "ReferenceField") {
                yield break;
            }
            var model = new ReferenceFieldSettings();
            if (updateModel.TryUpdateModel(model, "ReferenceFieldSettings", null, null)) {
                UpdateSettings(model, builder, "ReferenceFieldSettings");

                if (model.QueryId <= 0) {
                    model.QueryId = CreateQuery(model.ContentTypeName.ToString(CultureInfo.InvariantCulture));
                }

                if (model.RelationshipId <= 0) {
                    var httpContext = _httpContextAccessor.Current();
                    var routeValues = httpContext.Request.RequestContext.RouteData.Values;
                    var entityName = routeValues["id"].ToString();
                    model.RelationshipId = _relationshipService.CreateOneToManyRelationship(builder.Name, model.RelationshipName, model.ContentTypeName, entityName);
                }

                if (model.QueryId <= 0 || model.RelationshipId <= 0) {
                    updateModel.AddModelError("QueryOrRelation", T("Invalid Query or Relationship Id"));
                    yield break;
                }

                UpdateSettings(model, builder, "ReferenceFieldSettings");
                builder.WithSetting("ReferenceFieldSettings.DisplayAsLink", model.DisplayAsLink.ToString(CultureInfo.InvariantCulture));
                builder.WithSetting("ReferenceFieldSettings.ContentTypeName", model.ContentTypeName.ToString(CultureInfo.InvariantCulture));
                builder.WithSetting("ReferenceFieldSettings.RelationshipName", model.RelationshipName.ToString(CultureInfo.InvariantCulture));
                builder.WithSetting("ReferenceFieldSettings.RelationshipId", model.RelationshipId.ToString(CultureInfo.InvariantCulture));
                builder.WithSetting("ReferenceFieldSettings.QueryId", model.QueryId.ToString(CultureInfo.InvariantCulture));
            }
            yield return DefinitionTemplate(model);
        }
        public override IEnumerable<TemplateViewModel> PartFieldEditorUpdate(ContentPartFieldDefinitionBuilder builder, IUpdateModel updateModel)
        {
            if (!builder.FieldType.Equals(typeof(MoneyField).Name)) yield break;

            var model = new MoneyFieldSettings();

            if (updateModel.TryUpdateModel(model, typeof(MoneyFieldSettings).Name, null, null))
            {
                if (string.IsNullOrEmpty(model.DefaultCurrency))
                {
                    builder.WithSetting("MoneyFieldSettings.DefaultCurrency", Currency.FromCurrentCulture().Iso3LetterCode);
                }
                else
                {
                    Currency parsedCurrency;
                    if (Currency.TryParse(model.DefaultCurrency, out parsedCurrency))
                    {
                        builder.WithSetting("MoneyFieldSettings.DefaultCurrency", model.DefaultCurrency);
                    }
                    else
                    {
                        updateModel.AddModelError("InvalidCurrencyIsoCode", T("MoneyField - Invalid currency iso code was given."));
                    }
                }

                builder.WithSetting("MoneyFieldSettings.IsCurrencyReadOnly", model.IsCurrencyReadOnly.ToString(CultureInfo.InvariantCulture));
                builder.WithSetting("MoneyFieldSettings.Hint", model.Hint);
                builder.WithSetting("MoneyFieldSettings.Required", model.Required.ToString(CultureInfo.InvariantCulture));
            }
            yield return DefinitionTemplate(model);
        }
Exemplo n.º 32
0
        protected override DriverResult Editor(MenuPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var model = new MenuPartViewModel();

            if (updater.TryUpdateModel(model, Prefix, null, null))
            {
                var menu = model.OnMenu ? _orchardServices.ContentManager.Get(model.CurrentMenuId) : null;

                if (!_authorizationService.TryCheckAccess(Permissions.ManageMenus, _orchardServices.WorkContext.CurrentUser, menu))
                {
                    return(null);
                }

                part.MenuText = model.MenuText;
                part.Menu     = menu;

                if (string.IsNullOrEmpty(part.MenuPosition) && menu != null)
                {
                    part.MenuPosition = Position.GetNext(_navigationManager.BuildMenu(menu));

                    if (string.IsNullOrEmpty(part.MenuText))
                    {
                        updater.AddModelError("MenuText", T("The MenuText field is required"));
                    }
                }
            }

            return(Editor(part, shapeHelper));
        }
Exemplo n.º 33
0
 public override void UpdateFieldSettings(string fieldType, string fieldName, SettingsDictionary settingsDictionary, IUpdateModel updateModel) {
     if (fieldType != "OptionSetField") {
         return;
     }
     var model = new OptionSetFieldSettings();
     if (updateModel.TryUpdateModel(model, "OptionSetFieldSettings", null, null)) {
         UpdateSettings(model, settingsDictionary, "OptionSetFieldSettings");
         if (model.OptionSetId == 0) {
             model.OptionSetId = CreateOptionSetPart(fieldName, model);
             if (model.OptionSetId <= 0) {
                 updateModel.AddModelError("OptionSet", T("No items inputted"));
                 return;
             }
         }
         settingsDictionary["OptionSetFieldSettings.OptionSetId"] = model.OptionSetId.ToString("D");
         settingsDictionary["OptionSetFieldSettings.ListMode"] = model.ListMode.ToString();
     }
 }
Exemplo n.º 34
0
        public override IEnumerable<TemplateViewModel> PartFieldEditorUpdate(ContentPartFieldDefinitionBuilder builder, IUpdateModel updateModel) {
            if (builder.FieldType != "OptionSetField") {
                yield break;
            }

            var model = new OptionSetFieldSettings();

            if (updateModel.TryUpdateModel(model, "OptionSetFieldSettings", null, null)) {
                UpdateSettings(model, builder, "OptionSetFieldSettings");

                if (model.OptionSetId == 0) {
                    string[] options = (!String.IsNullOrWhiteSpace(model.Options)) ?
                        model.Options.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) : null;

                    if (options == null) {
                        updateModel.AddModelError("OptionSet",T("No items inputted"));
                        yield break;
                    }

                    var optionSetPart = _contentManager.New<OptionSetPart>("OptionSet");
                    optionSetPart.As<TitlePart>().Title = builder.Name;

                    _contentManager.Create(optionSetPart, VersionOptions.Published);

                    foreach (var option in options) {
                        var term = _contentManager.New<OptionItemPart>("OptionItem");
                        term.OptionSetId = optionSetPart.Id;
                        term.Name = option;
                        _contentManager.Create(term, VersionOptions.Published);
                    }
                    model.OptionSetId = optionSetPart.Id;
                }

                builder
                    .WithSetting("OptionSetFieldSettings.OptionSetId", model.OptionSetId.ToString())
                    .WithSetting("OptionSetFieldSettings.ListMode", model.ListMode.ToString());
            }

            yield return DefinitionTemplate(model);
        }
Exemplo n.º 35
0
        public bool PopulateAddressFromViewModel(AddressPart part, ViewModels.AddressEditViewModel viewModel, IUpdateModel updater, string prefix)
        {
            var ok = true;

            // Copy normal fields from view model
            if (String.IsNullOrWhiteSpace(viewModel.PostalCode))
            {
                updater.AddModelError(prefix + ".PostalCode", T("Please enter a post code."));
                ok = false;
            }
            else
            {
                // Strip any spaces
                part.PostalCode = viewModel.PostalCode = viewModel.PostalCode.Replace(" ", "");
            }
 
            part.AddressType = viewModel.AddressType;
            if (String.IsNullOrWhiteSpace(viewModel.Address1))
            {
                updater.AddModelError(prefix + ".Address1", T("Please enter at least the first line of the street address."));
                ok = false;
            }
            part.Address1 = viewModel.Address1;
            part.Address2 = viewModel.Address2;
            part.Address3 = viewModel.Address3;

            // Attempt to create inputted country name
            if (!String.IsNullOrWhiteSpace(viewModel.CountryName))
            {
                try
                {
                    var country = GetOrCreateCountryByName(viewModel.CountryName);
                    if (country != null)
                    {
                        viewModel.CountryId = country.Id;
                    }
                }
                catch (Exception e)
                {
                    Logger.Error(e, "Couldn't create country");
                }
            }
            // Attempt to create inputted region name
            if (!viewModel.CountryId.HasValue)
            {
                updater.AddModelError(prefix + ".CountryName", T("Error saving country. Enter a valid country name or select from the list."));
                ok = false;
            }
            if (viewModel.CountryId.HasValue && !String.IsNullOrWhiteSpace(viewModel.TownName))
            {
                var region = GetOrCreateTownByName(viewModel.CountryId.Value, viewModel.TownName);
                if (region != null)
                {
                    viewModel.TownId = region.Id;
                }
            }
            if (!viewModel.TownId.HasValue){
                updater.AddModelError(prefix + ".TownName", T("Enter a valid town name or select from the list."));
                ok = false;
            }
            return ok;
        }
Exemplo n.º 36
0
        public override dynamic UpdateEditor(dynamic shapeFactory, IUpdateModel updater)
        {
            var builderSteps = _recipeBuilderSteps.OrderBy(x => x.Position).Select(x => new ExportStepViewModel {
                Name = x.Name,
                DisplayName = x.DisplayName,
                Description = x.Description,
                Editor = x.BuildEditor(shapeFactory),
                IsVisible = x.IsVisible
            });

            var viewModel = new RecipeBuilderViewModel {
                Steps = builderSteps.ToList()
            };

            if (updater != null) {
                if (updater.TryUpdateModel(viewModel, Prefix, null, null)) {
                    if (viewModel.UploadConfigurationFile) {
                        var configurationFile = _orchardServices.WorkContext.HttpContext.Request.Files["ConfigurationFile"];

                        if (configurationFile.ContentLength == 0)
                            updater.AddModelError("ConfigurationFile", T("No configuration file was specified."));
                        else {
                            var configurationDocument = XDocument.Parse(new StreamReader(configurationFile.InputStream).ReadToEnd());
                            Configure(new ExportActionConfigurationContext(configurationDocument.Root.Element(Name)));
                        }
                    }
                    else {
                        var exportStepNames = viewModel.Steps.Where(x => x.IsSelected).Select(x => x.Name);
                        var stepsQuery = from name in exportStepNames
                            let provider = _recipeBuilderSteps.SingleOrDefault(x => x.Name == name)
                            where provider != null
                            select provider;
                        var steps = stepsQuery.ToArray();
                        var stepUpdater = new Updater(updater, secondHalf => String.Format("{0}.{1}", Prefix, secondHalf));
                        foreach (var exportStep in steps) {
                            exportStep.UpdateEditor(shapeFactory, stepUpdater);
                        }

                        RecipeBuilderSteps = steps;
                    }
                }
            }

            return shapeFactory.EditorTemplate(TemplateName: "ExportActions/BuildRecipe", Model: viewModel, Prefix: Prefix);
        }
Exemplo n.º 37
0
        public override dynamic UpdateEditor(dynamic shapeFactory, IUpdateModel updater)
        {
            var viewModel = new UploadRecipeViewModel {
                SuperUserName = _orchardServices.WorkContext.CurrentSite.SuperUser,
                RecipeExecutionSteps = _recipeExecutionSteps.Select(x => new RecipeExecutionStepViewModel {
                    Name = x.Name,
                    DisplayName = x.DisplayName,
                    Description = x.Description,
                    Editor = x.BuildEditor(shapeFactory)
                }).Where(x => x.Editor != null).ToList()
            };

            if (updater != null) {
                if (updater.TryUpdateModel(viewModel, Prefix, null, null)) {
                    // Validate and read uploaded recipe file.
                    var request = _orchardServices.WorkContext.HttpContext.Request;
                    var file = request.Files["RecipeFile"];
                    var isValid = true;

                    ResetSite = viewModel.ResetSite;
                    SuperUserPassword = viewModel.SuperUserPassword;

                    if (file == null || file.ContentLength == 0) {
                        updater.AddModelError("RecipeFile", T("No recipe file selected."));
                        isValid = false;
                    }

                    if (ResetSite) {
                        if (String.IsNullOrWhiteSpace(viewModel.SuperUserPassword)) {
                            updater.AddModelError("SuperUserPassword", T("Please specify a new password for the super user."));
                            isValid = false;
                        }
                        else if (!String.Equals(viewModel.SuperUserPassword, viewModel.SuperUserPasswordConfirmation)) {
                            updater.AddModelError("SuperUserPassword", T("The passwords do not match."));
                            isValid = false;
                        }
                    }

                    var stepUpdater = new Updater(updater, secondHalf => String.Format("{0}.{1}", Prefix, secondHalf));

                    // Update the view model with non-roundtripped values.
                    viewModel.SuperUserName = _orchardServices.WorkContext.CurrentSite.SuperUser;
                    foreach (var stepViewModel in viewModel.RecipeExecutionSteps) {
                        var step = _recipeExecutionSteps.Single(x => x.Name == stepViewModel.Name);
                        stepViewModel.DisplayName = step.DisplayName;
                        stepViewModel.Description = step.Description;

                        // Update the step with posted values.
                        stepViewModel.Editor = step.UpdateEditor(shapeFactory, stepUpdater);
                    }

                    if (isValid) {
                        // Read recipe file.
                        RecipeDocument = XDocument.Parse(new StreamReader(file.InputStream).ReadToEnd());
                    }
                }
            }

            return shapeFactory.EditorTemplate(TemplateName: "ImportActions/ExecuteRecipe", Model: viewModel, Prefix: Prefix);
        }
Exemplo n.º 38
0
 public IContent CreateAddress(ViewModels.AddressEditViewModel viewModel,IUpdateModel updater, string prefix)
 {
     var address = _services.ContentManager.New(AddressesContentType);
     var part = address.As<AddressPart>();
     if (part != null)
     {
         if (PopulateAddressFromViewModel(part, viewModel, updater, prefix))
         {
             // Publish
             _services.ContentManager.Create(address);
             if (!LinkAddressToTown(part, viewModel.TownId.Value))
             {
                 updater.AddModelError(prefix + ".TownName", T("Error saving town. Enter a valid town name or select from the list."));
                 _services.ContentManager.Remove(address);
             }
             return address;
         }
     }
     return null;
 }