public void OnLocalization(LocalizationService localization) { if (localization == null) return; var label = GetComponent<Text>(); GetComponent<Text>().text = localization.GetFromFile(File, Key, label.text); }
private void OnLocalization(LocalizationService localization) { if (localization == null) return; var label = GetComponent<TextBinder>(); var data = localization.GetFromFile(File, Key); label.FormatString = data; label.OnBindingRefresh(); }
public override void OnInspectorGUI() { base.OnInspectorGUI(); LocalizationInitializer.Startup(); Target = target as LocalizationService; if (Application.isPlaying) return; EditorGUILayout.LabelField("Default Language"); var di = Array.IndexOf(Target.Languages, Target.DefaultLanguage); var di2 = EditorGUILayout.Popup(di, Target.Languages.Select(o => o.Name).ToArray()); if (di != di2) { Target.DefaultLanguage = Target.Languages[di2]; EditorUtility.SetDirty(target); } EditorGUILayout.LabelField("Cached Language"); EditorGUILayout.LabelField(Target.Language.Name, EditorStyles.boldLabel); GUILayout.Space(16); if (GUILayout.Button("Reset Cached Language")) { Target.Language = Target.DefaultLanguage; EditorUtility.SetDirty(target); } if (GUILayout.Button("Reset Language List")) { Target.Languages = LanguageInfo.All; EditorUtility.SetDirty(target); } }
public ActionResult LatestRss() { using (UnitOfWorkManager.NewUnitOfWork()) { // Allowed Categories for a guest - As that's all we want latest RSS to show var guestRole = RoleService.GetRole(AppConstants.GuestRoleName); var allowedCategories = _categoryService.GetAllowedCategories(guestRole); // get an rss lit ready var rssTopics = new List <RssItem>(); // Get the latest topics var topics = _topicService.GetRecentRssTopics(50, allowedCategories); // Get all the categories for this topic collection var categories = topics.Select(x => x.Category).Distinct(); // create permissions var permissions = new Dictionary <Category, PermissionSet>(); // loop through the categories and get the permissions foreach (var category in categories) { var permissionSet = RoleService.GetPermissions(category, UsersRole); permissions.Add(category, permissionSet); } // Now loop through the topics and remove any that user does not have permission for foreach (var topic in topics) { // Get the permissions for this topic via its parent category var permission = permissions[topic.Category]; // Add only topics user has permission to if (!permission[SiteConstants.Instance.PermissionDenyAccess].IsTicked) { if (topic.Posts.Any()) { var firstOrDefault = topic.Posts.FirstOrDefault(x => x.IsTopicStarter); if (firstOrDefault != null) { rssTopics.Add(new RssItem { Description = firstOrDefault.PostContent, Link = topic.NiceUrl, Title = topic.Name, PublishedDate = topic.CreateDate }); } } } } return(new RssResult(rssTopics, LocalizationService.GetResourceString("Rss.LatestActivity.Title"), LocalizationService.GetResourceString("Rss.LatestActivity.Description"))); } }
public override void DeployModel(object modelHost, DefinitionBase model) { var definition = model.WithAssertAndCast <WebDefinition>("model", value => value.RequireNotNull()); SPWeb parentWeb = null; if (modelHost is SiteModelHost) { parentWeb = (modelHost as SiteModelHost).HostSite.RootWeb; } if (modelHost is WebModelHost) { parentWeb = (modelHost as WebModelHost).HostWeb; } var spObject = GetWeb(parentWeb, definition); var assert = ServiceFactory.AssertService .NewAssert(definition, spObject) .ShouldBeEqual(m => m.LCID, o => o.GetLCID()); //.ShouldBeEqual(m => m.WebTemplate, o => o.GetWebTemplate()) // temporarily switch culture to allow setting of the properties Title and Description for multi-language scenarios CultureUtils.WithCulture(spObject.UICulture, () => { assert.ShouldBeEqual(m => m.Title, o => o.Title) .ShouldBeEqual(m => m.UseUniquePermission, o => o.HasUniqueRoleAssignments); }); if (!string.IsNullOrEmpty(definition.WebTemplate)) { assert.ShouldBeEqual(m => m.WebTemplate, o => o.GetWebTemplate()); assert.SkipProperty(m => m.CustomWebTemplate); } else { // no sense to chek custom web template assert.SkipProperty(m => m.WebTemplate); assert.SkipProperty(m => m.CustomWebTemplate); } if (!string.IsNullOrEmpty(definition.AlternateCssUrl)) { assert.ShouldBeEndOf(m => m.AlternateCssUrl, o => o.AlternateCssUrl); } else { assert.SkipProperty(m => m.AlternateCssUrl); } if (!string.IsNullOrEmpty(definition.SiteLogoUrl)) { assert.ShouldBeEndOf(m => m.SiteLogoUrl, o => o.SiteLogoUrl); } else { assert.SkipProperty(m => m.SiteLogoUrl); } if (!string.IsNullOrEmpty(definition.Description)) { assert.ShouldBeEqual(m => m.Description, o => o.Description); } else { assert.SkipProperty(m => m.Description); } assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Url); var dstProp = d.GetExpressionValue(ct => ct.Url); var srcUrl = s.Url; var dstUrl = d.Url; srcUrl = UrlUtility.RemoveStartingSlash(srcUrl); var dstSubUrl = dstUrl.Replace(parentWeb.Url + "/", string.Empty); var isValid = srcUrl.ToUpper() == dstSubUrl.ToUpper(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); // localization if (definition.TitleResource.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.TitleResource); var isValid = true; foreach (var userResource in s.TitleResource) { var culture = LocalizationService.GetUserResourceCultureInfo(userResource); var value = d.TitleResource.GetValueForUICulture(culture); isValid = userResource.Value == value; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping."); } if (definition.DescriptionResource.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.DescriptionResource); var isValid = true; foreach (var userResource in s.DescriptionResource) { var culture = LocalizationService.GetUserResourceCultureInfo(userResource); var value = d.DescriptionResource.GetValueForUICulture(culture); isValid = userResource.Value == value; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.DescriptionResource, "DescriptionResource is NULL or empty. Skipping."); } if (definition.IndexedPropertyKeys.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.IndexedPropertyKeys); // Search if any indexPropertyKey from definition is not in WebModel var differentKeys = s.IndexedPropertyKeys.Select(o => o.Name) .Except(d.IndexedPropertyKeys); var isValid = !differentKeys.Any(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.IndexedPropertyKeys, "IndexedPropertyKeys is NULL or empty. Skipping."); } }
public async Task <IActionResult> UpdateProductAttribute( [ModelBinder(typeof(JsonModelBinder <ProductAttributeDto>))] Delta <ProductAttributeDto> productAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } var productAttribute = await _productAttributesApiService.GetByIdAsync(productAttributeDelta.Dto.Id); if (productAttribute == null) { return(Error(HttpStatusCode.NotFound, "product attribute", "not found")); } productAttributeDelta.Merge(productAttribute); await _productAttributeService.UpdateProductAttributeAsync(productAttribute); await CustomerActivityService.InsertActivityAsync("EditProductAttribute", await LocalizationService.GetResourceAsync("ActivityLog.EditProductAttribute"), productAttribute); // Preparing the result dto of the new product attribute var productAttributeDto = _dtoHelper.PrepareProductAttributeDTO(productAttribute); var productAttributesRootObjectDto = new ProductAttributesRootObjectDto(); productAttributesRootObjectDto.ProductAttributes.Add(productAttributeDto); var json = JsonFieldsSerializer.Serialize(productAttributesRootObjectDto, string.Empty); return(new RawJsonActionResult(json)); }
public virtual async Task <ActionResult> Show(string slug, int?p) { // Set the page index var pageIndex = p ?? 1; var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnUsersRole = loggedOnReadOnlyUser.GetRole(RoleService); // Get the topic var topic = _topicService.GetTopicBySlug(slug); if (topic != null) { var settings = SettingsService.GetSettings(); // Note: Don't use topic.Posts as its not a very efficient SQL statement // Use the post service to get them as it includes other used entities in one // statement rather than loads of sql selects var sortQuerystring = Request.QueryString[Constants.PostOrderBy]; var orderBy = !string.IsNullOrWhiteSpace(sortQuerystring) ? EnumUtils.ReturnEnumValueFromString <PostOrderBy>(sortQuerystring) : PostOrderBy.Standard; // Store the amount per page var amountPerPage = settings.PostsPerPage; if (sortQuerystring == Constants.AllPosts) { // Overide to show all posts amountPerPage = int.MaxValue; } // Get the posts var posts = await _postService.GetPagedPostsByTopic(pageIndex, amountPerPage, int.MaxValue, topic.Id, orderBy); // Get the topic starter post var starterPost = _postService.GetTopicStarterPost(topic.Id); // Get the permissions for the category that this topic is in var permissions = RoleService.GetPermissions(topic.Category, loggedOnUsersRole); // If this user doesn't have access to this topic then // redirect with message if (permissions[ForumConfiguration.Instance.PermissionDenyAccess].IsTicked) { return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } // Set editor permissions ViewBag.ImageUploadType = permissions[ForumConfiguration.Instance.PermissionInsertEditorImages].IsTicked ? "forumimageinsert" : "image"; var postIds = posts.Select(x => x.Id).ToList(); var votes = _voteService.GetVotesByPosts(postIds); var favourites = _favouriteService.GetAllPostFavourites(postIds); var viewModel = ViewModelMapping.CreateTopicViewModel(topic, permissions, posts, postIds, starterPost, posts.PageIndex, posts.TotalCount, posts.TotalPages, loggedOnReadOnlyUser, settings, _notificationService, _pollService, votes, favourites, true); // If there is a quote querystring var quote = Request["quote"]; if (!string.IsNullOrWhiteSpace(quote)) { try { // Got a quote var postToQuote = _postService.Get(new Guid(quote)); viewModel.QuotedPost = postToQuote.PostContent; viewModel.ReplyTo = postToQuote.Id; viewModel.ReplyToUsername = postToQuote.User.UserName; } catch (Exception ex) { LoggingService.Error(ex); } } var reply = Request["reply"]; if (!string.IsNullOrWhiteSpace(reply)) { try { // Set the reply var toReply = _postService.Get(new Guid(reply)); viewModel.ReplyTo = toReply.Id; viewModel.ReplyToUsername = toReply.User.UserName; } catch (Exception ex) { LoggingService.Error(ex); } } var updateDatabase = false; // User has permission lets update the topic view count // but only if this topic doesn't belong to the user looking at it var addView = !(User.Identity.IsAuthenticated && loggedOnReadOnlyUser.Id == topic.User.Id); if (addView) { updateDatabase = true; } // Check the poll - To see if it has one, and whether it needs to be closed. if (viewModel.Poll?.Poll?.ClosePollAfterDays != null && viewModel.Poll.Poll.ClosePollAfterDays > 0 && !viewModel.Poll.Poll.IsClosed) { // Check the date the topic was created var endDate = viewModel.Poll.Poll.DateCreated.AddDays((int)viewModel.Poll.Poll.ClosePollAfterDays); if (DateTime.UtcNow > endDate) { topic.Poll.IsClosed = true; viewModel.Topic.Poll.IsClosed = true; updateDatabase = true; } } if (!BotUtils.UserIsBot() && updateDatabase) { if (addView) { // Increase the topic views topic.Views = topic.Views + 1; } try { Context.SaveChanges(); } catch (Exception ex) { LoggingService.Error(ex); } } return(View(viewModel)); } return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage"))); }
public virtual ActionResult EditPostTopic(Guid id) { // Get the post var post = _postService.Get(id); // Get the topic var topic = post.Topic; // Get the current logged on user var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnloggedOnUsersRole = loggedOnReadOnlyUser.GetRole(RoleService); // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, loggedOnloggedOnUsersRole); // Is the user allowed to edit this post if (post.User.Id == loggedOnReadOnlyUser.Id || permissions[ForumConfiguration.Instance.PermissionEditPosts].IsTicked) { // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(loggedOnloggedOnUsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(loggedOnloggedOnUsersRole, ForumConfiguration.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); // If this user hasn't got any allowed cats OR they are not allowed to post then abandon if (allowedAccessCategories.Any() && loggedOnReadOnlyUser.DisablePosting != true) { // Create the model for just the post var viewModel = new CreateEditTopicViewModel { Content = post.PostContent, Id = post.Id, Category = topic.Category.Id, Name = topic.Name, TopicId = topic.Id, OptionalPermissions = GetCheckCreateTopicPermissions(permissions) }; // Now check if this is a topic starter, if so add the rest of the field if (post.IsTopicStarter) { // Remove all Categories that don't have create topic permission allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); // See if this user is subscribed to this topic var topicNotifications = _notificationService.GetTopicNotificationsByUserAndTopic(loggedOnReadOnlyUser, topic); // Populate the properties we can viewModel.IsLocked = topic.IsLocked; viewModel.IsSticky = topic.IsSticky; viewModel.IsTopicStarter = post.IsTopicStarter; viewModel.SubscribeToTopic = topicNotifications.Any(); viewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); // Tags - Populate from the topic if (topic.Tags.Any()) { viewModel.Tags = string.Join <string>(",", topic.Tags.Select(x => x.Tag)); } // Populate the poll answers if (topic.Poll != null && topic.Poll.PollAnswers.Any()) { // Has a poll so add it to the view model viewModel.PollAnswers = topic.Poll.PollAnswers; viewModel.PollCloseAfterDays = topic.Poll.ClosePollAfterDays ?? 0; } } // Return the edit view return(View(viewModel)); } } // If we get here the user has no permission to try and edit the post return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); }
public HelpModule(CommandService command, IDbLanguage language, LocalizationService localization) { _command = command; _language = language; _localization = localization; }
public FileBrowserView(FileInfoBase fileInfo, Modes mode) : this(new[] { fileInfo }, mode) { Type?optionsType = mode == Modes.Load ? fileInfo.LoadOptionsViewType : fileInfo.SaveOptionsViewType; if (optionsType != null) { this.OptionsControl = (UserControl?)Activator.CreateInstance(optionsType); } this.SelectButton.Text = mode == Modes.Load ? LocalizationService.GetString("Common_OpenFile") : LocalizationService.GetString("Common_SaveFile"); this.Selector.SearchEnabled = mode == Modes.Load; }
public ActionResult CreatePost(CreateAjaxPostViewModel post) { PermissionSet permissions; var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnUser = MembershipService.GetUser(loggedOnReadOnlyUser.Id); // Flood control if (!_postService.PassedPostFloodTest(loggedOnReadOnlyUser)) { throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage")); } // Check stop words var stopWords = _bannedWordService.GetAll(true); foreach (var stopWord in stopWords) { if (post.PostContent.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0) { throw new Exception(LocalizationService.GetResourceString("StopWord.Error")); } } // Quick check to see if user is locked out, when logged in if (loggedOnUser.IsLockedOut || !loggedOnUser.IsApproved) { FormsAuthentication.SignOut(); throw new Exception(LocalizationService.GetResourceString("Errors.NoAccess")); } var topic = _topicService.Get(post.Topic); var postContent = _bannedWordService.SanitiseBannedWords(post.PostContent); var akismetHelper = new AkismetHelper(SettingsService); var newPost = _postService.AddNewPost(postContent, topic, loggedOnUser, out permissions); // Set the reply to newPost.InReplyTo = post.InReplyTo; if (akismetHelper.IsSpam(newPost)) { newPost.Pending = true; } if (!newPost.Pending.HasValue || !newPost.Pending.Value) { _activityService.PostCreated(newPost); } try { Context.SaveChanges(); } catch (Exception ex) { Context.RollBack(); LoggingService.Error(ex); throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage")); } //Check for moderation if (newPost.Pending == true) { return(PartialView("_PostModeration")); } // All good send the notifications and send the post back // Create the view model var viewModel = ViewModelMapping.CreatePostViewModel(newPost, new List <Vote>(), permissions, topic, loggedOnReadOnlyUser, SettingsService.GetSettings(), new List <Favourite>()); // Success send any notifications NotifyNewTopics(topic, loggedOnReadOnlyUser); // Return view return(PartialView("_Post", viewModel)); }
public ActionResult MovePost(MovePostViewModel viewModel) { var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnUsersRole = loggedOnReadOnlyUser.GetRole(RoleService); // Firstly check if this is a post and they are allowed to move it var post = _postService.Get(viewModel.PostId); if (post == null) { return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage"))); } var permissions = RoleService.GetPermissions(post.Topic.Category, loggedOnUsersRole); var allowedCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole); // Does the user have permission to this posts category var cat = allowedCategories.FirstOrDefault(x => x.Id == post.Topic.Category.Id); if (cat == null) { return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"))); } // Does this user have permission to move if (!permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked) { return(NoPermission(post.Topic)); } var previousTopic = post.Topic; var category = post.Topic.Category; var postCreator = post.User; Topic topic; var cancelledByEvent = false; // If the dropdown has a value, then we choose that first if (viewModel.TopicId != null) { // Get the selected topic topic = _topicService.Get((Guid)viewModel.TopicId); } else if (!string.IsNullOrWhiteSpace(viewModel.TopicTitle)) { // We get the banned words here and pass them in, so its just one call // instead of calling it several times and each call getting all the words back var bannedWordsList = _bannedWordService.GetAll(); List <string> bannedWords = null; if (bannedWordsList.Any()) { bannedWords = bannedWordsList.Select(x => x.Word).ToList(); } // Create the topic topic = new Topic { Name = _bannedWordService.SanitiseBannedWords(viewModel.TopicTitle, bannedWords), Category = category, User = postCreator }; // Create the topic topic = _topicService.Add(topic); // Save the changes Context.SaveChanges(); // Set the post to be a topic starter post.IsTopicStarter = true; // Check the Events var e = new TopicMadeEventArgs { Topic = topic }; EventManager.Instance.FireBeforeTopicMade(this, e); if (e.Cancel) { cancelledByEvent = true; ShowMessage(new GenericMessageViewModel { MessageType = GenericMessages.warning, Message = LocalizationService.GetResourceString("Errors.GenericMessage") }); } } else { // No selected topic OR topic title, just redirect back to the topic return(Redirect(post.Topic.NiceUrl)); } // If this create was cancelled by an event then don't continue if (!cancelledByEvent) { // Now update the post to the new topic post.Topic = topic; // Also move any posts, which were in reply to this post if (viewModel.MoveReplyToPosts) { var relatedPosts = _postService.GetReplyToPosts(viewModel.PostId); foreach (var relatedPost in relatedPosts) { relatedPost.Topic = topic; } } Context.SaveChanges(); // Update Last post.. As we have done a save, we should get all posts including the added ones var lastPost = topic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault(); topic.LastPost = lastPost; // If any of the posts we are moving, were the last post - We need to update the old Topic var previousTopicLastPost = previousTopic.Posts.OrderByDescending(x => x.DateCreated).FirstOrDefault(); previousTopic.LastPost = previousTopicLastPost; try { Context.SaveChanges(); EventManager.Instance.FireAfterTopicMade(this, new TopicMadeEventArgs { Topic = topic }); // On Update redirect to the topic return(RedirectToAction("Show", "Topic", new { slug = topic.Slug })); } catch (Exception ex) { Context.RollBack(); LoggingService.Error(ex); ShowMessage(new GenericMessageViewModel { Message = ex.Message, MessageType = GenericMessages.danger }); } } // Repopulate the topics var topics = _topicService.GetAllSelectList(allowedCategories, 30); topics.Insert(0, new SelectListItem { Text = LocalizationService.GetResourceString("Topic.Choose"), Value = "" }); viewModel.LatestTopics = topics; viewModel.Post = ViewModelMapping.CreatePostViewModel(post, post.Votes.ToList(), permissions, post.Topic, loggedOnReadOnlyUser, SettingsService.GetSettings(), post.Favourites.ToList()); viewModel.Post.MinimalPost = true; viewModel.PostId = post.Id; return(View(viewModel)); }
public ActionResult DeletePost(Guid id) { var loggedOnReadOnlyUser = User.GetMembershipUser(MembershipService); var loggedOnUsersRole = loggedOnReadOnlyUser.GetRole(RoleService); // Got to get a lot of things here as we have to check permissions // Get the post var post = _postService.Get(id); var postId = post.Id; // get this so we know where to redirect after var isTopicStarter = post.IsTopicStarter; // Get the topic var topic = post.Topic; var topicUrl = topic.NiceUrl; // get the users permissions var permissions = RoleService.GetPermissions(topic.Category, loggedOnUsersRole); if (post.User.Id == loggedOnReadOnlyUser.Id || permissions[SiteConstants.Instance.PermissionDeletePosts].IsTicked) { try { // Delete post / topic if (post.IsTopicStarter) { // Delete entire topic _topicService.Delete(topic); } else { // Deletes single post and associated data _postService.Delete(post, false); // Remove in replyto's var relatedPosts = _postService.GetReplyToPosts(postId); foreach (var relatedPost in relatedPosts) { relatedPost.InReplyTo = null; } } Context.SaveChanges(); } catch (Exception ex) { Context.RollBack(); LoggingService.Error(ex); ShowMessage(new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Errors.GenericMessage"), MessageType = GenericMessages.danger }); return(Redirect(topicUrl)); } } // Deleted successfully if (isTopicStarter) { // Redirect to root as this was a topic and deleted TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Topic.Deleted"), MessageType = GenericMessages.success }; return(RedirectToAction("Index", "Home")); } // Show message that post is deleted TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Post.Deleted"), MessageType = GenericMessages.success }; return(Redirect(topic.NiceUrl)); }
protected void ValidateField(AssertPair <FieldDefinition, SPField> assert, SPField spObject, FieldDefinition definition) { assert .ShouldNotBeNull(spObject) .ShouldBeEqual(m => m.Title, o => o.Title) //.ShouldBeEqual(m => m.InternalName, o => o.InternalName) .ShouldBeEqual(m => m.Id, o => o.Id) .ShouldBeEqual(m => m.Required, o => o.Required); //.ShouldBeEqual(m => m.Description, o => o.Description) //.ShouldBeEqual(m => m.FieldType, o => o.TypeAsString) //.ShouldBeEqual(m => m.Group, o => o.Group); if (!string.IsNullOrEmpty(definition.Group)) { assert.ShouldBeEqual(m => m.Group, o => o.Group); } else { assert.SkipProperty(m => m.Group); } if (!string.IsNullOrEmpty(definition.StaticName)) { assert.ShouldBeEqual(m => m.StaticName, o => o.StaticName); } else { assert.SkipProperty(m => m.StaticName); } if (!string.IsNullOrEmpty(definition.Description)) { assert.ShouldBeEqual(m => m.Description, o => o.Description); } else { assert.SkipProperty(m => m.Description); } CustomFieldTypeValidation(assert, spObject, definition); if (definition.AddFieldOptions.HasFlag(BuiltInAddFieldOptions.DefaultValue)) { assert.SkipProperty(m => m.AddFieldOptions, "BuiltInAddFieldOptions.DefaultValue. Skipping."); } else { // TODO } if (definition.AddToDefaultView) { if (IsListScopedField) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.AddToDefaultView); var field = HostList.Fields[definition.Id]; var isValid = HostList.DefaultView .ViewFields .ToStringCollection() .Contains(field.InternalName); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.AddToDefaultView, "IsListScopedField = true. AddToDefaultView is ignored. Skipping."); } } else { assert.SkipProperty(m => m.AddToDefaultView, "AddToDefaultView is false. Skipping."); } if (definition.AdditionalAttributes.Count == 0) { assert.SkipProperty(m => m.AdditionalAttributes, "AdditionalAttributes count is 0. Skipping."); } else { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.AdditionalAttributes); var isValid = true; var dstXmlNode = XDocument.Parse(d.SchemaXml).Root; foreach (var attr in s.AdditionalAttributes) { var sourceAttrName = attr.Name; var sourceAttrValue = attr.Value; var destAttrValue = dstXmlNode.GetAttributeValue(sourceAttrName); isValid = sourceAttrValue == destAttrValue; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } if (string.IsNullOrEmpty(definition.RawXml)) { assert.SkipProperty(m => m.RawXml, "RawXml is NULL or empty. Skipping."); } else { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.RawXml); var isValid = true; var srcXmlNode = XDocument.Parse(s.RawXml).Root; var dstXmlNode = XDocument.Parse(d.SchemaXml).Root; foreach (var attr in srcXmlNode.Attributes()) { var sourceAttrName = attr.Name.LocalName; var sourceAttrValue = attr.Value; var destAttrValue = dstXmlNode.GetAttributeValue(sourceAttrName); isValid = sourceAttrValue == destAttrValue; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } // TODO, R&D to check InternalName changes in list-scoped fields if (spObject.InternalName == definition.InternalName) { assert.ShouldBeEqual(m => m.InternalName, o => o.InternalName); } else { assert.SkipProperty(m => m.InternalName, "Target InternalName is different to source InternalName. Could be an error if this is not a list scoped field"); } assert.ShouldBeEqual(m => m.Hidden, o => o.Hidden); if (definition.EnforceUniqueValues.HasValue) { assert.ShouldBeEqual(m => m.EnforceUniqueValues, o => o.EnforceUniqueValues); } else { assert.SkipProperty(m => m.EnforceUniqueValues, "EnforceUniqueValues is NULL"); } if (!string.IsNullOrEmpty(definition.ValidationFormula)) { assert.ShouldBeEqual(m => m.ValidationFormula, o => o.ValidationFormula); } else { assert.SkipProperty(m => m.ValidationFormula, string.Format("ValidationFormula value is not set. Skippping.")); } if (!string.IsNullOrEmpty(definition.ValidationMessage)) { assert.ShouldBeEqual(m => m.ValidationMessage, o => o.ValidationMessage); } else { assert.SkipProperty(m => m.ValidationMessage, string.Format("ValidationFormula value is not set. Skippping.")); } if (!string.IsNullOrEmpty(definition.DefaultValue)) { assert.ShouldBePartOf(m => m.DefaultValue, o => o.DefaultValue); } else { assert.SkipProperty(m => m.DefaultValue, string.Format("Default value is not set. Skippping.")); } if (!string.IsNullOrEmpty(definition.DefaultFormula)) { assert.ShouldBePartOf(m => m.DefaultFormula, o => o.DefaultFormula); } else { assert.SkipProperty(m => m.DefaultFormula, string.Format("Default formula is not set. Skippping.")); } if (!string.IsNullOrEmpty(spObject.JSLink) && (spObject.JSLink == "SP.UI.Taxonomy.js|SP.UI.Rte.js(d)|SP.Taxonomy.js(d)|ScriptForWebTaggingUI.js(d)" || spObject.JSLink == "choicebuttonfieldtemplate.js" || spObject.JSLink == "clienttemplates.js")) { assert.SkipProperty(m => m.JSLink, string.Format("OOTB read-ony JSLink value:[{0}]", spObject.JSLink)); } else { assert.ShouldBePartOf(m => m.JSLink, o => o.JSLink); } if (definition.ShowInDisplayForm.HasValue) { assert.ShouldBeEqual(m => m.ShowInDisplayForm, o => o.ShowInDisplayForm); } else { assert.SkipProperty(m => m.ShowInDisplayForm, "ShowInDisplayForm is NULL"); } if (definition.ShowInEditForm.HasValue) { assert.ShouldBeEqual(m => m.ShowInEditForm, o => o.ShowInEditForm); } else { assert.SkipProperty(m => m.ShowInEditForm, "ShowInEditForm is NULL"); } if (definition.ShowInListSettings.HasValue) { assert.ShouldBeEqual(m => m.ShowInListSettings, o => o.ShowInListSettings); } else { assert.SkipProperty(m => m.ShowInListSettings, "ShowInListSettings is NULL"); } if (definition.ShowInNewForm.HasValue) { assert.ShouldBeEqual(m => m.ShowInNewForm, o => o.ShowInNewForm); } else { assert.SkipProperty(m => m.ShowInNewForm, "ShowInNewForm is NULL"); } if (definition.ShowInVersionHistory.HasValue) { assert.ShouldBeEqual(m => m.ShowInVersionHistory, o => o.ShowInVersionHistory); } else { assert.SkipProperty(m => m.ShowInVersionHistory, "ShowInVersionHistory is NULL"); } if (definition.ShowInViewForms.HasValue) { assert.ShouldBeEqual(m => m.ShowInViewForms, o => o.ShowInViewForms); } else { assert.SkipProperty(m => m.ShowInViewForms, "ShowInViewForms is NULL"); } assert .ShouldBeEqual(m => m.Indexed, o => o.Indexed); if (definition.AllowDeletion.HasValue) { assert.ShouldBeEqual(m => m.AllowDeletion, o => o.AllowDeletion); } else { assert.SkipProperty(m => m.AllowDeletion, "AllowDeletion is NULL"); } /// localization if (definition.TitleResource.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.TitleResource); var isValid = true; foreach (var userResource in s.TitleResource) { var culture = LocalizationService.GetUserResourceCultureInfo(userResource); var value = d.TitleResource.GetValueForUICulture(culture); isValid = userResource.Value == value; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping."); } if (definition.DescriptionResource.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.DescriptionResource); var isValid = true; foreach (var userResource in s.DescriptionResource) { var culture = LocalizationService.GetUserResourceCultureInfo(userResource); var value = d.DescriptionResource.GetValueForUICulture(culture); isValid = userResource.Value == value; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.DescriptionResource, "DescriptionResource is NULL or empty. Skipping."); } }
/// <summary> /// Constructor /// </summary> /// <param name="localizationService">Localization service</param> protected DialogReactionElementBase(LocalizationService localizationService) : base(localizationService) { }
public ActionResult ActivityRss() { using (UnitOfWorkManager.NewUnitOfWork()) { // get an rss lit ready var rssActivities = new List <RssItem>(); var activities = _activityService.GetAll(50).OrderByDescending(x => x.ActivityMapped.Timestamp); var activityLink = Url.Action("Activity"); // Now loop through the topics and remove any that user does not have permission for foreach (var activity in activities) { if (activity is BadgeActivity) { var badgeActivity = activity as BadgeActivity; rssActivities.Add(new RssItem { Description = badgeActivity.Badge.Description, Title = string.Concat(badgeActivity.User.UserName, " ", LocalizationService.GetResourceString("Activity.UserAwardedBadge"), " ", badgeActivity.Badge.DisplayName, " ", LocalizationService.GetResourceString("Activity.Badge")), PublishedDate = badgeActivity.ActivityMapped.Timestamp, RssImage = AppHelpers.ReturnBadgeUrl(badgeActivity.Badge.Image), Link = activityLink }); } else if (activity is MemberJoinedActivity) { var memberJoinedActivity = activity as MemberJoinedActivity; rssActivities.Add(new RssItem { Description = string.Empty, Title = LocalizationService.GetResourceString("Activity.UserJoined"), PublishedDate = memberJoinedActivity.ActivityMapped.Timestamp, RssImage = memberJoinedActivity.User.MemberImage(SiteConstants.Instance.GravatarPostSize), Link = activityLink }); } else if (activity is ProfileUpdatedActivity) { var profileUpdatedActivity = activity as ProfileUpdatedActivity; rssActivities.Add(new RssItem { Description = string.Empty, Title = LocalizationService.GetResourceString("Activity.ProfileUpdated"), PublishedDate = profileUpdatedActivity.ActivityMapped.Timestamp, RssImage = profileUpdatedActivity.User.MemberImage(SiteConstants.Instance.GravatarPostSize), Link = activityLink }); } } return(new RssResult(rssActivities, LocalizationService.GetResourceString("Rss.LatestActivity.Title"), LocalizationService.GetResourceString("Rss.LatestActivity.Description"))); } }
public HomeController(LoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, MembershipService membershipService, SettingsService settingsService, CacheService cacheService, LocalizationService localizationService) : base(loggingService, unitOfWorkManager, membershipService, settingsService, cacheService, localizationService) { }
public LocalizedAuthorBuilder(LocalizationService localization, LocalizedLanguage language) { _builder = new LocalEmbedAuthorBuilder(); _localization = localization; _language = language; }
public FashionProductContentController(IWarehouseInventoryService inventoryService, LocalizationService localizationService, ReadOnlyPricingLoader readOnlyPricingLoader, ICurrentMarket currentMarket) { _inventoryService = inventoryService; _localizationService = localizationService; _readOnlyPricingLoader = readOnlyPricingLoader; _currentMarket = currentMarket; }
public FileBrowserView(FileInfoBase[] fileInfos, Modes mode) { this.mode = mode; this.fileInfos = fileInfos; this.InitializeComponent(); this.SelectButton.Text = mode == Modes.Load ? LocalizationService.GetString("Common_OpenFile") : LocalizationService.GetString("Common_SaveFile"); this.Selector.SearchEnabled = mode == Modes.Load; this.ContentArea.DataContext = this; foreach (FileInfoBase info in fileInfos) { IFileSource[]? sources = info.GetFileSources(); if (sources == null) { continue; } foreach (IFileSource source in sources) { this.FileSources.Add(source); } } this.FileSource = this.GetDefaultFileSource(); this.IsOpen = true; if (this.mode == Modes.Save) { this.FileName = "New " + fileInfos[0].Name; Task.Run(async() => { await Task.Delay(100); await Dispatch.MainThread(); this.FileNameInputBox.Focus(); this.FileNameInputBox.SelectAll(); FocusManager.SetFocusedElement(FocusManager.GetFocusScope(this), this.FileNameInputBox); Keyboard.Focus(this.FileNameInputBox); }); } Task.Run(this.UpdateEntries); Type?optionsType = mode == Modes.Load ? fileInfos[0].LoadOptionsViewType : fileInfos[0].SaveOptionsViewType; if (optionsType != null) { this.OptionsControl = (UserControl?)Activator.CreateInstance(optionsType); } }
public override void DeployModel(object modelHost, DefinitionBase model) { var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull()); var definition = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull()); var list = listModelHost.HostList; var spObject = list.Views.FindByName(definition.Title); var assert = ServiceFactory.AssertService .NewAssert(definition, spObject) .ShouldBeEqual(m => m.Title, o => o.Title) .ShouldBeEqual(m => m.IsDefault, o => o.IsDefaul()) .ShouldBeEqual(m => m.Hidden, o => o.Hidden) .ShouldBeEqual(m => m.RowLimit, o => (int)o.RowLimit) .ShouldBeEqual(m => m.IsPaged, o => o.Paged); if (definition.InlineEdit.HasValue) { assert.ShouldBeEqual(m => m.InlineEdit.ToString().ToLower(), o => o.InlineEdit.ToLower()); } else { assert.SkipProperty(m => m.InlineEdit); } if (!string.IsNullOrEmpty(definition.Scope)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Scope); var dstProp = d.GetExpressionValue(o => o.Scope); var scopeValue = ListViewScopeTypesConvertService.NormilizeValueToSSOMType(definition.Scope); var isValid = scopeValue == d.Scope.ToString(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Scope); } if (!string.IsNullOrEmpty(definition.Query)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Query); var dstProp = d.GetExpressionValue(o => o.Query); var srcViewDate = assert.Src.Query.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/"); var dstViewDate = assert.Dst.Query.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/"); srcViewDate = Regex.Replace(srcViewDate, @"\r\n?|\n", string.Empty); dstViewDate = Regex.Replace(dstViewDate, @"\r\n?|\n", string.Empty); var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Query); } if (!string.IsNullOrEmpty(definition.ViewData)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.ViewData); var dstProp = d.GetExpressionValue(o => o.ViewData); var srcViewDate = assert.Src.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/"); var dstViewDate = assert.Dst.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/"); srcViewDate = Regex.Replace(srcViewDate, @"\r\n?|\n", string.Empty); dstViewDate = Regex.Replace(dstViewDate, @"\r\n?|\n", string.Empty); var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ViewData); } if (!string.IsNullOrEmpty(definition.Type)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Type); var dstProp = d.GetExpressionValue(o => o.Type); var isValid = srcProp.Value.ToString().ToUpper() == dstProp.Value.ToString().ToUpper(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Type); } if (definition.ViewStyleId.HasValue) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.ViewStyleId); var isValid = false; var srcViewId = s.ViewStyleId; var destViewId = 0; var doc = XDocument.Parse(d.SchemaXml); destViewId = ConvertUtils.ToInt(doc.Descendants("ViewStyle") .First() .GetAttributeValue("ID") ).Value; isValid = srcViewId == destViewId; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ViewStyleId, "ViewStyleId is null"); } if (!string.IsNullOrEmpty(definition.JSLink)) { assert.ShouldBeEqual(m => m.JSLink, o => o.JSLink); } else { assert.SkipProperty(m => m.JSLink); } if (definition.DefaultViewForContentType.HasValue) { assert.ShouldBeEqual(m => m.DefaultViewForContentType, o => o.DefaultViewForContentType); } else { assert.SkipProperty(m => m.DefaultViewForContentType, "DefaultViewForContentType is null or empty. Skipping."); } if (definition.TabularView.HasValue) { assert.ShouldBeEqual(m => m.TabularView, o => o.TabularView); } else { assert.SkipProperty(m => m.TabularView, "TabularView is null or empty. Skipping."); } if (string.IsNullOrEmpty(definition.ContentTypeName)) { assert.SkipProperty(m => m.ContentTypeName, "ContentTypeName is null or empty. Skipping."); } else { var contentTypeId = LookupListContentTypeByName(list, definition.ContentTypeName); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.ContentTypeName); var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId); var isValis = contentTypeId == d.ContentTypeId; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValis }); }); } if (string.IsNullOrEmpty(definition.ContentTypeId)) { assert.SkipProperty(m => m.ContentTypeId, "ContentTypeId is null or empty. Skipping."); } else { var contentTypeId = LookupListContentTypeById(list, definition.ContentTypeId); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.ContentTypeId); var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId); var isValis = contentTypeId == d.ContentTypeId; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = isValis }); }); } if (string.IsNullOrEmpty(definition.AggregationsStatus)) { assert.SkipProperty(m => m.AggregationsStatus, "Aggregationsstatus is null or empty. Skipping."); } else { assert.ShouldBeEqual(m => m.AggregationsStatus, o => o.AggregationsStatus); } if (string.IsNullOrEmpty(definition.Aggregations)) { assert.SkipProperty(m => m.Aggregations, "Aggregations is null or empty. Skipping."); } else { assert.ShouldBeEqual(m => m.Aggregations, o => o.Aggregations); } if (string.IsNullOrEmpty(definition.Url)) { assert.SkipProperty(m => m.Url, "Url is null or empty. Skipping."); } else { assert.ShouldBePartOf(m => m.Url, o => o.ServerRelativeUrl); } assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.Fields); var dstProp = d.GetExpressionValue(ct => ct.ViewFields); var hasAllFields = true; foreach (var srcField in s.Fields) { var listField = d.ParentList.Fields.OfType <SPField>().FirstOrDefault(f => f.StaticName == srcField); // if list-scoped field we need to check by internal name // internal name is changed for list scoped-fields // that's why to check by BOTH, definition AND real internal name if (!d.ViewFields.ToStringCollection().Contains(srcField) && !d.ViewFields.ToStringCollection().Contains(listField.InternalName)) { hasAllFields = false; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = dstProp, IsValid = hasAllFields }); }); /// localization if (definition.TitleResource.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.TitleResource); var isValid = true; foreach (var userResource in s.TitleResource) { var culture = LocalizationService.GetUserResourceCultureInfo(userResource); var value = d.TitleResource.GetValueForUICulture(culture); isValid = userResource.Value == value; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping."); } }
public virtual async Task <ActionResult> Create(CreateEditTopicViewModel topicViewModel) { // Get the user and roles var loggedOnUser = User.GetMembershipUser(MembershipService, false); var loggedOnUsersRole = loggedOnUser.GetRole(RoleService); // Get the category var category = _categoryService.Get(topicViewModel.Category); // First check this user is allowed to create topics in this category var permissions = RoleService.GetPermissions(category, loggedOnUsersRole); // Now we have the category and permissionSet - Populate the optional permissions // This is just in case the viewModel is return back to the view also sort the allowedCategories topicViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); topicViewModel.Categories = _categoryService.GetBaseSelectListCategories(AllowedCreateCategories(loggedOnUsersRole)); topicViewModel.IsTopicStarter = true; if (topicViewModel.PollAnswers == null) { topicViewModel.PollAnswers = new List <PollAnswer>(); } if (ModelState.IsValid) { // See if the user has actually added some content to the topic if (string.IsNullOrWhiteSpace(topicViewModel.Content)) { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } else { // Map the new topic (Pass null for new topic) var topic = topicViewModel.ToTopic(category, loggedOnUser, null); // Run the create pipeline var createPipeLine = await _topicService.Create(topic, topicViewModel.Files, topicViewModel.Tags, topicViewModel.SubscribeToTopic, topicViewModel.Content, null); if (createPipeLine.Successful == false) { // TODO - Not sure on this? // Remove the topic if unsuccessful, as we may have saved some items. await _topicService.Delete(createPipeLine.EntityToProcess); // Tell the user the topic is awaiting moderation ModelState.AddModelError(string.Empty, createPipeLine.ProcessLog.FirstOrDefault()); return(View(topicViewModel)); } if (createPipeLine.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate)) { var moderate = createPipeLine.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?; if (moderate == true) { // Tell the user the topic is awaiting moderation TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"), MessageType = GenericMessages.info }; return(RedirectToAction("Index", "Home")); } } // Redirect to the newly created topic return(Redirect($"{topic.NiceUrl}?postbadges=true")); } } return(View(topicViewModel)); }
public PollModule(IDbLanguage language, LocalizationService localization) { _language = language; _localization = localization; }
public virtual async Task <ActionResult> EditPostTopic(CreateEditTopicViewModel editPostViewModel) { // Get the current user and role var loggedOnUser = User.GetMembershipUser(MembershipService, false); var loggedOnUsersRole = loggedOnUser.GetRole(RoleService, false); // Get the category var category = _categoryService.Get(editPostViewModel.Category); // Get all the permissions for this user var permissions = RoleService.GetPermissions(category, loggedOnUsersRole); // Now we have the category and permissionSet - Populate the optional permissions // This is just in case the viewModel is return back to the view also sort the allowedCategories // Get the allowed categories for this user var allowedAccessCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole); var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(loggedOnUsersRole, ForumConfiguration.Instance.PermissionCreateTopics); var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id); // TODO ??? Is this correct ?? allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id)); // Set the categories editPostViewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories); // Get the users permissions for the topic editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions); // See if this is a topic starter or not editPostViewModel.IsTopicStarter = editPostViewModel.Id == Guid.Empty; // IS the model valid if (ModelState.IsValid) { // Got to get a lot of things here as we have to check permissions // Get the post var originalPost = _postService.Get(editPostViewModel.Id); // Get the topic var originalTopic = originalPost.Topic; // See if the user has actually added some content to the topic if (string.IsNullOrWhiteSpace(editPostViewModel.Content)) { ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage")); } else { // Map the new topic (Pass null for new topic) var topic = editPostViewModel.ToTopic(category, loggedOnUser, originalTopic); // Run the create pipeline var editPipeLine = await _topicService.Edit(originalTopic, editPostViewModel.Files, editPostViewModel.Tags, editPostViewModel.SubscribeToTopic, editPostViewModel.Content, editPostViewModel.Name, editPostViewModel.PollAnswers, editPostViewModel.PollCloseAfterDays); // Check if successful if (editPipeLine.Successful == false) { // Tell the user the topic is awaiting moderation ModelState.AddModelError(string.Empty, editPipeLine.ProcessLog.FirstOrDefault()); return(View(editPostViewModel)); } if (editPipeLine.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Moderate)) { var moderate = editPipeLine.ExtendedData[Constants.ExtendedDataKeys.Moderate] as bool?; if (moderate == true) { // Tell the user the topic is awaiting moderation TempData[Constants.MessageViewBagName] = new GenericMessageViewModel { Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"), MessageType = GenericMessages.info }; return(RedirectToAction("Index", "Home")); } } // Redirect to the newly created topic return(Redirect($"{topic.NiceUrl}?postbadges=true")); } } return(View(editPostViewModel)); }
public MonthPickerHandler(LocalizationService locale) { _locale = locale; }
public async Task <IActionResult> CreateProductAttribute( [ModelBinder(typeof(JsonModelBinder <ProductAttributeDto>))] Delta <ProductAttributeDto> productAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // Inserting the new product var productAttribute = new ProductAttribute(); productAttributeDelta.Merge(productAttribute); await _productAttributeService.InsertProductAttributeAsync(productAttribute); await CustomerActivityService.InsertActivityAsync("AddNewProductAttribute", await LocalizationService.GetResourceAsync("ActivityLog.AddNewProductAttribute"), productAttribute); // Preparing the result dto of the new product var productAttributeDto = _dtoHelper.PrepareProductAttributeDTO(productAttribute); var productAttributesRootObjectDto = new ProductAttributesRootObjectDto(); productAttributesRootObjectDto.ProductAttributes.Add(productAttributeDto); var json = JsonFieldsSerializer.Serialize(productAttributesRootObjectDto, string.Empty); return(new RawJsonActionResult(json)); }
public SubscriptionMail(LocalizationService localizationService, ISiteDefinitionResolver siteDefinitionResolver) { this._localizationService = localizationService ?? LocalizationService.Current; this._siteDefinitionResolver = siteDefinitionResolver ?? ServiceLocator.Current.GetInstance <ISiteDefinitionResolver>(); }
public async Task <IActionResult> DeleteProductAttribute(int id) { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var productAttribute = await _productAttributesApiService.GetByIdAsync(id); if (productAttribute == null) { return(Error(HttpStatusCode.NotFound, "product attribute", "not found")); } await _productAttributeService.DeleteProductAttributeAsync(productAttribute); //activity log await CustomerActivityService.InsertActivityAsync("DeleteProductAttribute", await LocalizationService.GetResourceAsync("ActivityLog.DeleteProductAttribute"), productAttribute); return(new RawJsonActionResult("{}")); }
public PluginController(ProductSevice productSevice, LoggingService loggingService, IUnitOfWorkManager unitOfWorkManager, MembershipService membershipService, SettingsService settingsService, CacheService cacheService, LocalizationService localizationService) : base(loggingService, unitOfWorkManager, membershipService, settingsService, cacheService, localizationService) { _productSevice = productSevice; }
//TODO:TMP:tmp solution; public static string Translate(this string key, string uid = App.LangUid, string @default = "") => LocalizationService.GetString(uid, key, @default);
public Guild(ulong id, LocalizationService localization) { Id = id; Language = localization.Languages.First(x => x.CultureCode.Equals("en-US")); }
public override void DeployModel(object modelHost, DefinitionBase model) { var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull()); var definition = model.WithAssertAndCast <ListDefinition>("model", value => value.RequireNotNull()); var web = webModelHost.HostWeb; var context = web.Context; context.Load(web, w => w.ServerRelativeUrl); var lists = context.LoadQuery <List>(web.Lists.Include(l => l.DefaultViewUrl)); context.ExecuteQueryWithTrace(); #pragma warning disable 618 var spObject = FindListByUrl(lists, definition.GetListUrl()); #pragma warning restore 618 context.Load(spObject); context.Load(spObject, list => list.RootFolder.Properties); context.Load(spObject, list => list.RootFolder.ServerRelativeUrl); context.Load(spObject, list => list.RootFolder.Properties); context.Load(spObject, list => list.EnableAttachments); context.Load(spObject, list => list.EnableFolderCreation); context.Load(spObject, list => list.EnableMinorVersions); context.Load(spObject, list => list.EnableModeration); context.Load(spObject, list => list.EnableVersioning); context.Load(spObject, list => list.ForceCheckout); context.Load(spObject, list => list.Hidden); context.Load(spObject, list => list.NoCrawl); context.Load(spObject, list => list.OnQuickLaunch); context.Load(spObject, list => list.DocumentTemplateUrl); context.Load(spObject, list => list.DraftVersionVisibility); context.ExecuteQueryWithTrace(); var assert = ServiceFactory.AssertService.NewAssert(model, definition, spObject); assert .ShouldBeEqual(m => m.Title, o => o.Title) //.ShouldBeEqual(m => m.Description, o => o.Description) //.ShouldBeEqual(m => m.IrmEnabled, o => o.IrmEnabled) //.ShouldBeEqual(m => m.IrmExpire, o => o.IrmExpire) //.ShouldBeEqual(m => m.IrmReject, o => o.IrmReject) //.ShouldBeEndOf(m => m.GetServerRelativeUrl(web), m => m.Url, o => o.GetServerRelativeUrl(), o => o.GetServerRelativeUrl()) .ShouldBeEqual(m => m.ContentTypesEnabled, o => o.ContentTypesEnabled); if (!string.IsNullOrEmpty(definition.Description)) { assert.ShouldBeEqual(m => m.Description, o => o.Description); } else { assert.SkipProperty(m => m.Description, "Description is null or empty. Skipping."); } assert.SkipProperty(m => m.WriteSecurity, "WriteSecurity is notsupported by CSOM"); if (!string.IsNullOrEmpty(definition.DraftVersionVisibility)) { var draftOption = (DraftVisibilityType)Enum.Parse(typeof(DraftVisibilityType), definition.DraftVersionVisibility); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.DraftVersionVisibility); var dstProp = d.GetExpressionValue(m => m.DraftVersionVisibility); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = draftOption == (DraftVisibilityType)dstProp.Value }); }); } else { assert.SkipProperty(m => m.DraftVersionVisibility, "Skipping from validation. DraftVersionVisibility IS NULL"); } if (definition.Hidden.HasValue) { assert.ShouldBeEqual(m => m.Hidden, m => m.Hidden); } else { assert.SkipProperty(m => m.Hidden, "Skipping from validation. Url IS NULL"); } #pragma warning disable 618 if (!string.IsNullOrEmpty(definition.Url)) { assert.ShouldBeEndOf(m => m.GetListUrl(), m => m.Url, o => o.GetServerRelativeUrl(), o => o.GetServerRelativeUrl()); } else { assert.SkipProperty(m => m.Url, "Skipping from validation. Url IS NULL"); } #pragma warning restore 618 if (!string.IsNullOrEmpty(definition.CustomUrl)) { assert.ShouldBeEndOf(m => m.CustomUrl, o => o.GetServerRelativeUrl()); } else { assert.SkipProperty(m => m.CustomUrl, "Skipping from validation. CustomUrl IS NULL"); } // common if (definition.EnableAttachments.HasValue) { assert.ShouldBeEqual(m => m.EnableAttachments, o => o.EnableAttachments); } else { assert.SkipProperty(m => m.EnableAttachments, "Skipping from validation. EnableAttachments IS NULL"); } if (definition.EnableFolderCreation.HasValue) { assert.ShouldBeEqual(m => m.EnableFolderCreation, o => o.EnableFolderCreation); } else { assert.SkipProperty(m => m.EnableFolderCreation, "Skipping from validation. EnableFolderCreation IS NULL"); } if (definition.EnableMinorVersions.HasValue) { assert.ShouldBeEqual(m => m.EnableMinorVersions, o => o.EnableMinorVersions); } else { assert.SkipProperty(m => m.EnableMinorVersions, "Skipping from validation. EnableMinorVersions IS NULL"); } if (definition.EnableModeration.HasValue) { assert.ShouldBeEqual(m => m.EnableModeration, o => o.EnableModeration); } else { assert.SkipProperty(m => m.EnableModeration, "Skipping from validation. EnableModeration IS NULL"); } if (definition.EnableVersioning.HasValue) { assert.ShouldBeEqual(m => m.EnableVersioning, o => o.EnableVersioning); } else { assert.SkipProperty(m => m.EnableVersioning, "Skipping from validation. EnableVersioning IS NULL"); } if (definition.ForceCheckout.HasValue) { assert.ShouldBeEqual(m => m.ForceCheckout, o => o.ForceCheckout); } else { assert.SkipProperty(m => m.ForceCheckout, "Skipping from validation. ForceCheckout IS NULL"); } if (definition.NoCrawl.HasValue) { assert.ShouldBeEqual(m => m.NoCrawl, o => o.NoCrawl); } else { assert.SkipProperty(m => m.NoCrawl, "Skipping from validation. NoCrawl IS NULL"); } if (definition.OnQuickLaunch.HasValue) { assert.ShouldBeEqual(m => m.OnQuickLaunch, o => o.OnQuickLaunch); } else { assert.SkipProperty(m => m.OnQuickLaunch, "Skipping from validation. OnQuickLaunch IS NULL"); } // IRM if (definition.IrmEnabled.HasValue) { assert.ShouldBeEqual(m => m.IrmEnabled, o => o.IrmEnabled); } else { assert.SkipProperty(m => m.IrmEnabled, "Skipping from validation. IrmEnabled IS NULL"); } if (definition.IrmExpire.HasValue) { assert.ShouldBeEqual(m => m.IrmExpire, o => o.IrmExpire); } else { assert.SkipProperty(m => m.IrmExpire, "Skipping from validation. IrmExpire IS NULL"); } if (definition.IrmReject.HasValue) { assert.ShouldBeEqual(m => m.IrmReject, o => o.IrmReject); } else { assert.SkipProperty(m => m.IrmReject, "Skipping from validation. IrmReject IS NULL"); } if (definition.TemplateType > 0) { assert.ShouldBeEqual(m => m.TemplateType, o => o.BaseTemplate); } else { assert.SkipProperty(m => m.TemplateType, "TemplateType == 0. Skipping."); } if (!string.IsNullOrEmpty(definition.TemplateName)) { context.Load(web, tmpWeb => tmpWeb.ListTemplates); context.ExecuteQueryWithTrace(); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Fetching all list templates and matching target one."); var listTemplate = ResolveListTemplate(webModelHost, definition); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.TemplateName); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = (spObject.TemplateFeatureId == listTemplate.FeatureId) && (spObject.BaseTemplate == listTemplate.ListTemplateTypeKind) }); }); } else { assert.SkipProperty(m => m.TemplateName, "TemplateName is null or empty. Skipping."); } if (definition.MajorVersionLimit.HasValue) { if (ReflectionUtils.HasProperty(spObject, "MajorVersionLimit")) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.MajorVersionLimit); var value = (int)ReflectionUtils.GetPropertyValue(spObject, "MajorVersionLimit"); var isValid = value == definition.MajorVersionLimit.Value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.MajorVersionLimit, "Skipping from validation. MajorVersionLimit does not exist. CSOM runtime is below required."); } } else { assert.SkipProperty(m => m.MajorVersionLimit, "Skipping from validation. MajorVersionLimit IS NULL"); } if (definition.MajorWithMinorVersionsLimit.HasValue) { if (ReflectionUtils.HasProperty(spObject, "MajorWithMinorVersionsLimit")) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.MajorWithMinorVersionsLimit); var value = (int)ReflectionUtils.GetPropertyValue(spObject, "MajorWithMinorVersionsLimit"); var isValid = value == definition.MajorWithMinorVersionsLimit.Value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.MajorWithMinorVersionsLimit, "Skipping from validation. MajorWithMinorVersionsLimit does not exist. CSOM runtime is below required."); } } else { assert.SkipProperty(m => m.MajorWithMinorVersionsLimit, "Skipping from validation. MajorWithMinorVersionsLimit IS NULL"); } // template url if (string.IsNullOrEmpty(definition.DocumentTemplateUrl)) { assert.SkipProperty(m => m.DocumentTemplateUrl, "Skipping DocumentTemplateUrl or library. Skipping."); } else { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.DocumentTemplateUrl); var dstProp = d.DocumentTemplateUrl; var srcUrl = srcProp.Value as string; var dstUrl = dstProp; if (!dstUrl.StartsWith("/")) { dstUrl = "/" + dstUrl; } bool isValid; if (s.DocumentTemplateUrl.Contains("~sitecollection")) { var siteCollectionUrl = webModelHost.HostSite.ServerRelativeUrl == "/" ? string.Empty : webModelHost.HostSite.ServerRelativeUrl; isValid = srcUrl.Replace("~sitecollection", siteCollectionUrl) == dstUrl; } else if (s.DocumentTemplateUrl.Contains("~site")) { var siteCollectionUrl = web.ServerRelativeUrl == "/" ? string.Empty : web.ServerRelativeUrl; isValid = srcUrl.Replace("~site", siteCollectionUrl) == dstUrl; } else { isValid = dstUrl.EndsWith(srcUrl); } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } if (definition.IndexedRootFolderPropertyKeys.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.IndexedRootFolderPropertyKeys); var isValid = false; if (d.RootFolder.Properties.FieldValues.ContainsKey("vti_indexedpropertykeys")) { // check props, TODO // check vti_indexedpropertykeys var indexedPropertyKeys = d.RootFolder.Properties["vti_indexedpropertykeys"] .ToString() .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries) .Select(es => Encoding.Unicode.GetString(System.Convert.FromBase64String(es))); // Search if any indexPropertyKey from definition is not in WebModel var differentKeys = s.IndexedRootFolderPropertyKeys.Select(o => o.Name) .Except(indexedPropertyKeys); isValid = !differentKeys.Any(); } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.IndexedRootFolderPropertyKeys, "IndexedRootFolderPropertyKeys is NULL or empty. Skipping."); } var supportsLocalization = ReflectionUtils.HasProperties(spObject, new[] { "TitleResource", "DescriptionResource" }); if (supportsLocalization) { if (definition.TitleResource.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.TitleResource); var isValid = true; foreach (var userResource in s.TitleResource) { var culture = LocalizationService.GetUserResourceCultureInfo(userResource); var resourceObject = ReflectionUtils.GetPropertyValue(spObject, "TitleResource"); var value = ReflectionUtils.GetMethod(resourceObject, "GetValueForUICulture") .Invoke(resourceObject, new[] { culture.Name }) as ClientResult <string>; context.ExecuteQuery(); isValid = userResource.Value == value.Value; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping."); } if (definition.DescriptionResource.Any()) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.DescriptionResource); var isValid = true; foreach (var userResource in s.DescriptionResource) { var culture = LocalizationService.GetUserResourceCultureInfo(userResource); var resourceObject = ReflectionUtils.GetPropertyValue(spObject, "DescriptionResource"); var value = ReflectionUtils.GetMethod(resourceObject, "GetValueForUICulture") .Invoke(resourceObject, new[] { culture.Name }) as ClientResult <string>; context.ExecuteQuery(); isValid = userResource.Value == value.Value; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.DescriptionResource, "DescriptionResource is NULL or empty. Skipping."); } } else { TraceService.Critical((int)LogEventId.ModelProvisionCoreCall, "CSOM runtime doesn't have Web.TitleResource and Web.DescriptionResource() methods support. Skipping validation."); assert.SkipProperty(m => m.TitleResource, "TitleResource is null or empty. Skipping."); assert.SkipProperty(m => m.DescriptionResource, "DescriptionResource is null or empty. Skipping."); } }
private void CalculatePosForErfassungsPeriod <TZustandsabschnittBase, TStrassenabschnittBase>(TZustandsabschnittBase[] zustandsabschnittList, JahresInterval jahresInterval, ErfassungsPeriod erfassungsPeriod) where TStrassenabschnittBase : StrassenabschnittBase where TZustandsabschnittBase : ZustandsabschnittBase { var zustandsspiegelProJahrGrafischeDiagramPos = Enum.GetValues(typeof(ZustandsindexTyp)) .OfType <ZustandsindexTyp>() .Where(z => z != ZustandsindexTyp.Unbekannt) .Select(z => CreateDiagramPo(z, jahresInterval)) .ToDictionary(po => po.ZustandsindexTyp, po => po); decimal totalUnknowZustandsindexTypFlaeche = 0; decimal mittlereZustandsindexWithFlaeche = 0; decimal mittlererAufnahmedatumTickMultipliedWithFlaeche = 0; foreach (var zustandsabschnitt in zustandsabschnittList) { var zustandsindexTyp = ZustandsindexCalculator.GetTyp(zustandsabschnitt.Zustandsindex); zustandsspiegelProJahrGrafischeDiagramPos[zustandsindexTyp].FlaecheFahrbahn += (zustandsabschnitt.FlaecheFahrbahn ?? 0); mittlereZustandsindexWithFlaeche += zustandsabschnitt.Zustandsindex * (zustandsabschnitt.FlaecheFahrbahn ?? 0); mittlererAufnahmedatumTickMultipliedWithFlaeche += zustandsabschnitt.Aufnahmedatum.Ticks * (zustandsabschnitt.FlaecheFahrbahn ?? 0); } var currentJahr = ErfassungsPeriodService.GetCurrentErfassungsPeriod().Erfassungsjahr.Year; diagramPos[jahresInterval.JahrBis] = zustandsspiegelProJahrGrafischeDiagramPos.Values.ToList(); var totalKnownZustandsindexTypFlaeche = zustandsspiegelProJahrGrafischeDiagramPos.Values.Sum(po => po.FlaecheFahrbahn); var totalFlaeche = totalKnownZustandsindexTypFlaeche + totalUnknowZustandsindexTypFlaeche; var totalStrasseFlaeche = transactionScopeProvider.Queryable <TStrassenabschnittBase>() .Where(z => z.ErfassungsPeriod == erfassungsPeriod) .Sum(g => g.Laenge * g.BreiteFahrbahn); var zustandsspiegelProJahrGrafischeTablePos = zustandsspiegelProJahrGrafischeDiagramPos.Values .Select(po => CreateTablePo(jahresInterval, GetPerzent(po.FlaecheFahrbahn, totalKnownZustandsindexTypFlaeche), FormatHelper.ToReportNoDecimalPercentString, LocalizationService.GetLocalizedEnum(po.ZustandsindexTyp), (int)po.ZustandsindexTyp, currentJahr, po.ZustandsindexTyp)); tablePos[jahresInterval.JahrBis] = zustandsspiegelProJahrGrafischeTablePos.ToList(); PercentPartitioningCorrector.Corrigate(tablePos[jahresInterval.JahrBis].Cast <IPercentHolder>().ToList()); var mittlererAufnahmedatum = (mittlererAufnahmedatumTickMultipliedWithFlaeche == 0 || totalFlaeche == 0) ? (decimal?)null : (decimal.Divide(mittlererAufnahmedatumTickMultipliedWithFlaeche, totalFlaeche)); tablePos[jahresInterval.JahrBis].Add(CreateTablePo(jahresInterval, mittlererAufnahmedatum, d => FormatHelper.ToReportDateTimeString(d, "-"), reportLocalizationService.MittleresAlterDerZustandsaufnahmen, -10, currentJahr)); var netzAnteil = GetPerzent(totalKnownZustandsindexTypFlaeche, totalStrasseFlaeche); tablePos[jahresInterval.JahrBis].Add(CreateTablePo(jahresInterval, netzAnteil, FormatHelper.ToReportNoDecimalPercentString, reportLocalizationService.NetzAnteil, -20, currentJahr)); var mittlererZustandsindex = (mittlereZustandsindexWithFlaeche == 0 || totalFlaeche == 0) ? 0 : decimal.Divide(mittlereZustandsindexWithFlaeche, totalFlaeche); tablePos[jahresInterval.JahrBis].Add(CreateTablePo(jahresInterval, mittlererZustandsindex, FormatHelper.ToReportDecimalString, reportLocalizationService.MittlererZustandsindex, -30, currentJahr)); }