/// <summary> /// Add a new post /// </summary> /// <param name="postContent"> </param> /// <param name="topic"> </param> /// <param name="user"></param> /// <param name="permissions"> </param> /// <returns>True if post added</returns> public Post AddNewPost(string postContent, Topic topic, Member user, out PermissionSet permissions) { // Get the permissions for the category that this topic is in permissions = ServiceFactory.PermissionService.GetPermissions(topic.Category, user.Groups.FirstOrDefault()); // Check this users role has permission to create a post if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked) { // Throw exception so Ajax caller picks it up throw new ApplicationException(AppHelpers.Lang("Errors.NoPermission")); } // Has permission so create the post var newPost = new Post { PostContent = postContent, Member = user, MemberId = user.Id, Topic = topic, IpAddress = AppHelpers.GetUsersIpAddress(), DateCreated = DateTime.UtcNow, DateEdited = DateTime.UtcNow }; newPost = SanitizePost(newPost); var category = topic.Category; if (category.ModerateAllPostsInThisCategory == true) { newPost.Pending = true; } // create the post Add(newPost); // Update the users points score and post count for posting ServiceFactory.MemberPointsService.Add(new MemberPoints { Points = Dialogue.Settings().PointsAddedPerNewPost, MemberId = user.Id, RelatedPostId = newPost.Id }); // add the last post to the topic topic.LastPost = newPost; // Add post to members count ServiceFactory.MemberService.AddPostCount(user); return(newPost); }
public static EditSettingsViewModel SettingsToSettingsViewModel(Settings currentSettings) { var settingViewModel = new EditSettingsViewModel { Id = currentSettings.Id, ForumName = currentSettings.ForumName, ForumUrl = currentSettings.ForumUrl, IsClosed = currentSettings.IsClosed, EnableRSSFeeds = currentSettings.EnableRSSFeeds, DisplayEditedBy = currentSettings.DisplayEditedBy, EnableMarkAsSolution = currentSettings.EnableMarkAsSolution, EnableSpamReporting = currentSettings.EnableSpamReporting, EnableMemberReporting = currentSettings.EnableMemberReporting, EnableEmailSubscriptions = currentSettings.EnableEmailSubscriptions, ManuallyAuthoriseNewMembers = currentSettings.ManuallyAuthoriseNewMembers, EmailAdminOnNewMemberSignUp = currentSettings.EmailAdminOnNewMemberSignUp, TopicsPerPage = currentSettings.TopicsPerPage, PostsPerPage = currentSettings.PostsPerPage, ActivitiesPerPage = currentSettings.ActivitiesPerPage, EnablePrivateMessages = currentSettings.EnablePrivateMessages, MaxPrivateMessagesPerMember = currentSettings.MaxPrivateMessagesPerMember, PrivateMessageFloodControl = currentSettings.PrivateMessageFloodControl, EnableSignatures = currentSettings.EnableSignatures, EnablePoints = currentSettings.EnablePoints, PointsAllowedToVoteAmount = currentSettings.PointsAllowedToVoteAmount, PointsAddedPerPost = currentSettings.PointsAddedPerPost, PointsAddedPostiveVote = currentSettings.PointsAddedPostiveVote, PointsDeductedNagativeVote = currentSettings.PointsDeductedNagativeVote, PointsAddedForSolution = currentSettings.PointsAddedForSolution, AdminEmailAddress = currentSettings.AdminEmailAddress, NotificationReplyEmail = currentSettings.NotificationReplyEmail, SMTP = currentSettings.SMTP, SMTPUsername = currentSettings.SMTPUsername, SMTPPassword = currentSettings.SMTPPassword, AkismentKey = currentSettings.AkismentKey, EnableAkisment = currentSettings.EnableAkisment != null && (bool)currentSettings.EnableAkisment, NewMemberEmailConfirmation = currentSettings.NewMemberEmailConfirmation != null && (bool)currentSettings.NewMemberEmailConfirmation, Theme = currentSettings.Theme, SMTPPort = string.IsNullOrEmpty(currentSettings.SMTPPort) ? null : (int?)(Convert.ToInt32(currentSettings.SMTPPort)), SpamQuestion = currentSettings.SpamQuestion, SpamAnswer = currentSettings.SpamAnswer, Themes = AppHelpers.GetThemeFolders(), SMTPEnableSSL = currentSettings.SMTPEnableSSL ?? false, EnableSocialLogins = currentSettings.EnableSocialLogins ?? false, EnablePolls = currentSettings.EnablePolls ?? false, SuspendRegistration = currentSettings.SuspendRegistration ?? false, PageTitle = currentSettings.PageTitle, MetaDesc = currentSettings.MetaDesc }; return(settingViewModel); }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { DataContext = (from a in Globals.AppViewModel.AccountsViewModel.Accounts where a.FriendlyName == AppViewModel.SelectedAccountFriendlyName select a).First(); var act = (Account)DataContext; if (act == null) { return; } QRCodeImage.Source = AppHelpers.GenerateQRCodeBMP(act.Address); }
public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { // Kodus to "Chad" http://stackoverflow.com/a/9914117 var rule = new ModelClientValidationRule { ErrorMessage = AppHelpers.Lang(this.ErrorMessage), ValidationType = "range" }; rule.ValidationParameters.Add("min", this.Minimum); rule.ValidationParameters.Add("max", this.Maximum); yield return(rule); }
/// <summary> /// Create Db page /// </summary> /// <returns></returns> public ActionResult CreateDb() { // Check installer should be running var previousVersionNo = AppHelpers.PreviousVersionNo(); var viewModel = new CreateDbViewModel { IsUpgrade = !string.IsNullOrEmpty(previousVersionNo), PreviousVersion = previousVersionNo, CurrentVersion = AppHelpers.GetCurrentVersionNo() }; return(View(viewModel)); }
public MemberPoints Add(MemberPoints points) { if (points.MemberId <= 0) { AppHelpers.LogError("Error adding point memberId null"); } else { points.DateAdded = DateTime.UtcNow; ContextPerRequest.Db.MemberPoints.Add(points); } return(points); }
/// <summary> /// Convert a string to an enum /// </summary> /// <param name="badgeTypeStr"></param> /// <returns></returns> private BadgeType?FromString(string badgeTypeStr) { try { return((BadgeType)Enum.Parse(typeof(BadgeType), badgeTypeStr)); } catch (ArgumentException) { AppHelpers.LogError(string.Format(AppHelpers.Lang("Badge.UnknownBadge"), badgeTypeStr)); } return(null); }
private async Task LogOutAsync(bool expired) { await AppHelpers.LogOutAsync(); _authService.LogOut(() => { Current.MainPage = new HomePage(); if (expired) { _platformUtilsService.ShowToast("warning", null, AppResources.LoginExpired); } }); }
/// <summary> /// Returns a pretty date like Facebook /// </summary> /// <param name="date"></param> /// <returns>28 Days Ago</returns> public static string GetPrettyDate(string date) { DateTime time; if (DateTime.TryParse(date, out time)) { var span = DateTime.UtcNow.Subtract(time); var totalDays = (int)span.TotalDays; var totalSeconds = (int)span.TotalSeconds; if ((totalDays < 0) || (totalDays >= 0x1f)) { return(AppHelpers.FormatDateTime(date, "dd MMMM yyyy")); } if (totalDays == 0) { if (totalSeconds < 60) { return(GetLocalisedText("Date.JustNow")); } if (totalSeconds < 120) { return(GetLocalisedText("Date.OneMinuteAgo")); } if (totalSeconds < 0xe10) { return(string.Format(GetLocalisedText("Date.MinutesAgo"), Math.Floor((double)(((double)totalSeconds) / 60.0)))); } if (totalSeconds < 0x1c20) { return(GetLocalisedText("Date.OneHourAgo")); } if (totalSeconds < 0x15180) { return(string.Format(GetLocalisedText("Date.HoursAgo"), Math.Floor((double)(((double)totalSeconds) / 3600.0)))); } } if (totalDays == 1) { return(GetLocalisedText("Date.Yesterday")); } if (totalDays < 7) { return(string.Format(GetLocalisedText("Date.DaysAgo"), totalDays)); } if (totalDays < 0x1f) { return(string.Format(GetLocalisedText("Date.WeeksAgo"), Math.Ceiling((double)(((double)totalDays) / 7.0)))); } } return(date); }
public MainWindowViewModel(AnimeViewModel animeViewModel, MangaViewModel mangaViewModel, SettingsViewModel settingsViewModel, IRunJobs <UpdateDbEntries> updateDbEntries) { _animeViewModel = animeViewModel; _mangaViewModel = mangaViewModel; _settingsViewModel = settingsViewModel; _updateDbEntries = updateDbEntries; ViewModels = new ObservableCollection <BaseViewModel>() { _animeViewModel, _mangaViewModel, _settingsViewModel }; ViewModelsView = CollectionViewSource.GetDefaultView(ViewModels); if (AppHelpers.CheckRootDir()) { InitApp(); } else { ConsentBoxVisibility = Visibility.Visible; } ToastEvent.ToastMessageRecieved += (sender, args) => { ToastMessage = args.Message; ToastMessageType = args.MessageType; }; JobEvent.JobStarted += (sender, args) => { IsJobRunning = true; JobDescription = args.JobDescription; JobProgressMaximum = args.JobLength; }; JobEvent.JobProgressChanged += (sender, args) => { JobProgressCurrent = args.IsIncremental ? (JobProgressCurrent + args.Progress) : args.Progress; if (args.StageDescriptor != null) { JobStage = args.StageDescriptor; } }; JobEvent.JobEnded += (sender) => { JobProgressCurrent = 0; IsJobRunning = false; }; }
private void _constructor(IBlock parent, IEntity cbDefinition) { var wrapLog = Log.Call(); Parent = parent; ParseContentBlockDefinition(cbDefinition); ParentId = parent.ParentId; ContentBlockId = -cbDefinition.EntityId; // Ensure we know what portal the stuff is coming from Tenant = Parent.App.Tenant; ZoneId = Parent.ZoneId; AppId = AppHelpers.GetAppIdFromGuidName(ZoneId, _appName); // should be 0 if unknown, must test if (AppId == Settings.DataIsMissingInDb) { _dataIsMissing = true; return; } // 2018-09-22 new, must come before the AppId == 0 check BlockBuilder = new BlockBuilder(parent.BlockBuilder, this, Parent.BlockBuilder.Container, Parent.BlockBuilder.Parameters, Log); if (AppId == 0) { return; } App = new App(Tenant, ZoneId, AppId, ConfigurationProvider.Build(BlockBuilder, false), true, Log); // 2019-11-11 2dm new, with CmsRuntime var cms = new CmsRuntime(App, Log, parent.BlockBuilder.UserMayEdit, parent.BlockBuilder.Environment.PagePublishing.IsEnabled(parent.BlockBuilder.Container.Id)); Configuration = cms.Blocks.GetContentGroupOrGeneratePreview(_contentGroupGuid, _previewTemplateGuid); // handle cases where the content group is missing - usually because of incomplete import if (Configuration.DataIsMissing) { _dataIsMissing = true; App = null; return; } // use the content-group template, which already covers stored data + module-level stored settings ((BlockBuilder)BlockBuilder).SetTemplateOrOverrideFromUrl(Configuration.View); wrapLog("ok"); }
protected override async void OnAppearing() { base.OnAppearing(); try { if (!await AppHelpers.IsVaultTimeoutImmediateAsync()) { await _vaultTimeoutService.CheckVaultTimeoutAsync(); } if (await _vaultTimeoutService.IsLockedAsync()) { return; } await _vm.InitAsync(); _broadcasterService.Subscribe(nameof(SendAddEditPage), message => { if (message.Command == "selectFileResult") { Device.BeginInvokeOnMainThread(() => { var data = message.Data as Tuple <byte[], string>; _vm.FileData = data.Item1; _vm.FileName = data.Item2; }); } }); await LoadOnAppearedAsync(_scrollView, true, async() => { var success = await _vm.LoadAsync(); if (!success) { await CloseAsync(); return; } await HandleCreateRequest(); if (!_vm.EditMode && string.IsNullOrWhiteSpace(_vm.Send?.Name)) { RequestFocus(_nameEntry); } AdjustToolbar(); }); } catch (Exception ex) { _logger.Value.Exception(ex); await CloseAsync(); } }
[DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.Anonymous)] // will check security internally, so assume no requirements public dynamic PublicQuery([FromUri] string appname, [FromUri] string name) { // todo: get app from appname var zid = ZoneHelpers.GetZoneID(PortalSettings.PortalId); if (zid == null) { throw new Exception("zone not found"); } var aid = AppHelpers.GetAppIdFromGuidName(zid.Value, appname); _queryApp = new App(PortalSettings, aid); return("ok!");// Query(name); }
private static UploadFileResult FileChecks(HttpPostedFileBase file, UploadFileResult upResult, string fileName, bool onlyImages = false) { //Before we do anything, check file size if (file.ContentLength > Dialogue.Settings().FileUploadMaximumFilesize) { //File is too big upResult.UploadSuccessful = false; upResult.ErrorMessage = AppHelpers.Lang("Post.UploadFileTooBig"); return(upResult); } // now check allowed extensions var allowedFileExtensions = Dialogue.Settings().FileUploadAllowedExtensions; if (onlyImages) { allowedFileExtensions = new List <string> { "jpg", "jpeg", "png", "gif" }; } if (allowedFileExtensions.Any()) { // Get the file extension var fileExtension = Path.GetExtension(fileName.ToLower()); // If can't work out extension then just error if (string.IsNullOrEmpty(fileExtension)) { upResult.UploadSuccessful = false; upResult.ErrorMessage = AppHelpers.Lang("Errors.GenericMessage"); return(upResult); } // Remove the dot then check against the extensions in the web.config settings fileExtension = fileExtension.TrimStart('.'); if (!allowedFileExtensions.Contains(fileExtension)) { upResult.UploadSuccessful = false; upResult.ErrorMessage = AppHelpers.Lang("Post.UploadBannedFileExtension"); return(upResult); } } return(upResult); }
/// <summary> /// Return a topic by url slug /// </summary> /// <param name="slug"></param> /// <returns></returns> public Topic GetTopicBySlug(string slug) { var safeSlug = AppHelpers.GetSafeHtml(slug); var topics = ContextPerRequest.Db.Topic .Include(x => x.Poll) .Include(x => x.Poll.PollAnswers) .FirstOrDefault(x => x.Slug == safeSlug); PopulateAll(new List <Topic> { topics }); return(topics); }
public List <Category> Get(List <int> ids) { var cats = new List <Category>(); if (ids.Any()) { var allCats = AppHelpers.UmbHelper().TypedContent(ids); foreach (var cat in allCats) { cats.Add(CategoryMapper.MapCategory(cat)); } } return(cats); }
protected void Application_AcquireRequestState(object sender, EventArgs e) { //It's important to check whether session object is ready if (!AppHelpers.InInstaller()) { if (HttpContext.Current.Session != null) { // Set the culture per request var ci = new CultureInfo(LocalizationService.CurrentLanguage.LanguageCulture); Thread.CurrentThread.CurrentUICulture = ci; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name); } } }
private async Task LogOutAsync(string userId, bool userInitiated, bool expired) { await AppHelpers.LogOutAsync(userId, userInitiated); await SetMainPageAsync(); _authService.LogOut(() => { if (expired) { _platformUtilsService.ShowToast("warning", null, AppResources.LoginExpired); } }); }
public bool ResetPassword(Member member, string newPassword) { try { var iMember = _memberService.GetById(member.Id); _memberService.SavePassword(iMember, newPassword); return(true); } catch (Exception ex) { AppHelpers.LogError("ResetPassword()", ex); return(false); } }
private async Task SsoAuthSuccessAsync() { RestoreAppOptionsFromCopy(); await AppHelpers.ClearPreviousPage(); if (await _vaultTimeoutService.IsLockedAsync()) { Application.Current.MainPage = new NavigationPage(new LockPage(_appOptions)); } else { Application.Current.MainPage = new TabsPage(_appOptions, null); } }
public async Task LogOutAsync(string userId, bool userInitiated, bool expired) { await AppHelpers.LogOutAsync(userId, userInitiated); await NavigateOnAccountChangeAsync(); _authService.LogOut(() => { if (expired) { _platformUtilsService.ShowToast("warning", null, AppResources.LoginExpired); } }); }
private void btnSearch_Click(object sender, EventArgs e) { lblResults.Text = "Searching..."; Application.DoEvents(); _results = Search(); lblResults.Text = _results.Count + " Results"; dgResults.Columns.Clear(); List <DataGridViewColumn> columns = new List <DataGridViewColumn>(); if (_selectProperties.SelectedProperty == null) { columns = AppHelpers.GetColumns(_selectProperties.ParentType); } else { columns = AppHelpers.GetColumns(_selectProperties.SelectedProperty.Type); } if (columns.Count > 0) { dgResults.AutoGenerateColumns = false; dgResults.Columns.AddRange(columns.ToArray()); } else { dgResults.AutoGenerateColumns = true; } if (_results.Count > 1000) { dgResults.DataSource = _results.Take(1000).ToList(); lblResults.Text += " (First 1000)"; } else { dgResults.DataSource = _results; } /*if (results.Count > 0 && results.First().GetType() == typeof(HistoricalFigure)) * { * DataGridViewTextBoxColumn killCount = new DataGridViewTextBoxColumn(); * killCount.DataPropertyName = "NotableKills"; * killCount.HeaderText = "NotableKills"; * dgResults.Columns.Insert(killCount); * dgResults.Columns.AddRange( * }*/ }
public ActionResult Index(EditSettingsViewModel settingsViewModel) { if (ModelState.IsValid) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { try { var existingSettings = SettingsService.GetSettings(false); var updatedSettings = ViewModelMapping.SettingsViewModelToSettings(settingsViewModel, existingSettings); // Map over viewModel from if (settingsViewModel.NewMemberStartingRole != null) { updatedSettings.NewMemberStartingRole = _roleService.GetRole(settingsViewModel.NewMemberStartingRole.Value); } if (settingsViewModel.DefaultLanguage != null) { updatedSettings.DefaultLanguage = LocalizationService.Get(settingsViewModel.DefaultLanguage.Value); } unitOfWork.Commit(); _cacheService.ClearStartsWith(AppConstants.SettingsCacheName); } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); } } // All good clear cache and get reliant lists using (UnitOfWorkManager.NewUnitOfWork()) { TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = "Settings Updated", MessageType = GenericMessages.success }; settingsViewModel.Themes = AppHelpers.GetThemeFolders(); settingsViewModel.Roles = _roleService.AllRoles().ToList(); settingsViewModel.Languages = LocalizationService.AllLanguages.ToList(); } } return(View(settingsViewModel)); }
private void NotifyNewTopics(Topic topic, IUnitOfWork unitOfWork) { try { // Get all notifications for this category var notifications = _topicNotificationService.GetByTopic(topic).Select(x => x.User.Id).ToList(); if (notifications.Any()) { // remove the current user from the notification, don't want to notify yourself that you // have just made a topic! notifications.Remove(LoggedOnReadOnlyUser.Id); if (notifications.Count > 0) { // Now get all the users that need notifying var usersToNotify = MembershipService.GetUsersById(notifications); // Create the email var sb = new StringBuilder(); sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("Post.Notification.NewPosts"), topic.Name)); if (SiteConstants.Instance.IncludeFullPostInEmailNotifications) { sb.Append(AppHelpers.ConvertPostContent(topic.LastPost.PostContent)); } sb.AppendFormat("<p><a href=\"{0}\">{0}</a></p>", string.Concat(Domain, topic.NiceUrl)); // create the emails only to people who haven't had notifications disabled var emails = usersToNotify.Where(x => x.DisableEmailNotifications != true && !x.IsLockedOut && x.IsBanned != true).Select(user => new Email { Body = _emailService.EmailTemplate(user.UserName, sb.ToString()), EmailTo = user.Email, NameTo = user.UserName, Subject = string.Concat(LocalizationService.GetResourceString("Post.Notification.Subject"), SettingsService.GetSettings().ForumName) }).ToList(); // and now pass the emails in to be sent _emailService.SendMail(emails); unitOfWork.Commit(); } } } catch (Exception ex) { unitOfWork.Rollback(); LoggingService.Error(ex); } }
public void Execute(IJobExecutionContext context) { using (_unitOfWorkManager.NewUnitOfWork()) { try { var url = _settingsService.GetSettings(false).ForumUrl; AppHelpers.Ping(url); } catch (Exception ex) { _loggingService.Error(string.Concat("Error in KeepAlive job > ", ex.Message)); } } }
private void LogoutIfAuthed() { NSRunLoop.Main.BeginInvokeOnMainThread(async() => { if (await IsAuthed()) { await AppHelpers.LogOutAsync(); var deviceActionService = ServiceContainer.Resolve <IDeviceActionService>("deviceActionService"); if (deviceActionService.SystemMajorVersion() >= 12) { await ASCredentialIdentityStore.SharedStore?.RemoveAllCredentialIdentitiesAsync(); } } }); }
public static List <Member> MapMember(List <int> memberids, bool populateAll = false) { var key = string.Format("umb-members-{0}", string.Join("-", memberids.Select(x => x.ToString()).ToArray())); if (!HttpContext.Current.Items.Contains(key)) { var mappedMembers = new List <IPublishedContent>(); foreach (var member in memberids.Distinct()) { mappedMembers.Add(AppHelpers.UmbMemberHelper().GetById(member)); } return(MapMember(mappedMembers)); } return(HttpContext.Current.Items[key] as List <Member>); }
public static DialogueSettings Settings() { if (!HttpContext.Current.Items.Contains(AppConstants.SiteSettingsKey)) { var currentPage = AppHelpers.CurrentPage(); var forumNode = currentPage.AncestorOrSelf(AppConstants.DocTypeForumRoot); if (forumNode == null) { // Only do this is if we can't find the forum normally forumNode = currentPage.DescendantOrSelf(AppConstants.DocTypeForumRoot); } HttpContext.Current.Items.Add(AppConstants.SiteSettingsKey, Settings(forumNode)); } return(HttpContext.Current.Items[AppConstants.SiteSettingsKey] as DialogueSettings); }
private async Task ApplyManagedSettingsAsync() { var userDefaults = NSUserDefaults.StandardUserDefaults; var managedSettings = userDefaults.DictionaryForKey("com.apple.configuration.managed"); if (managedSettings != null && managedSettings.Count > 0) { var dict = new Dictionary <string, string>(); foreach (var setting in managedSettings) { dict.Add(setting.Key.ToString(), setting.Value?.ToString()); } await AppHelpers.SetPreconfiguredSettingsAsync(dict); } }
internal int GetCurrentAppIdFromPath(string appPath) { // check zone var zid = ZoneHelpers.GetZoneID(PortalSettings.PortalId); if (zid == null) { throw new Exception("zone not found"); } // get app from appname var aid = AppHelpers.GetAppIdFromGuidName(zid.Value, appPath, true); return(aid); }