/// <summary> /// Gets the releases list from the rock server. /// </summary> /// <returns></returns> private List <Release> GetReleasesList() { List <Release> releases = new List <Release>(); var releaseProgram = ReleaseProgram.PRODUCTION; var updateUrl = GlobalAttributesCache.Get().GetValue("UpdateServerUrl"); if (updateUrl.Contains(ReleaseProgram.ALPHA)) { releaseProgram = ReleaseProgram.ALPHA; } else if (updateUrl.Contains(ReleaseProgram.BETA)) { releaseProgram = ReleaseProgram.BETA; } var client = new RestClient(string.Format("{0}/api/RockUpdate/GetReleasesList", RockSiteUrl)); var request = new RestRequest(Method.GET); request.RequestFormat = DataFormat.Json; request.AddParameter("rockInstanceId", Rock.Web.SystemSettings.GetRockInstanceId()); request.AddParameter("releaseProgram", releaseProgram); IRestResponse response = client.Execute(request); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Accepted) { foreach (var release in JsonConvert.DeserializeObject <List <Release> >(response.Content)) { releases.Add(release); } } return(releases); }
/// <summary> /// Initializes a new instance of the <see cref="DayOfWeekPicker"/> class. /// </summary> public GradePicker() : base() { Label = GlobalAttributesCache.Get().GetValue("core.GradeLabel"); PopulateItems(); }
private System.Web.IHttpHandler GetHandlerFor404(RequestContext requestContext, SiteCache site) { // If we couldn't match a route because it's the root, use the home page if (site != null && requestContext.HttpContext.Request.Path == "/") { return(GetHandlerForPage(requestContext, site.DefaultPage, site.DefaultPageRouteId ?? 0)); } if (site != null && site.PageNotFoundPageId.HasValue) { if (Convert.ToBoolean(GlobalAttributesCache.Get().GetValue("Log404AsException"))) { Rock.Model.ExceptionLogService.LogException( new Exception(string.Format("404 Error: {0}", requestContext.HttpContext.Request.Url.AbsoluteUri)), requestContext.HttpContext.ApplicationInstance.Context); } var page = PageCache.Get(site.PageNotFoundPageId.Value); requestContext.HttpContext.Response.StatusCode = 404; requestContext.HttpContext.Response.TrySkipIisCustomErrors = true; return(GetHandlerForPage(requestContext, page)); } else { // no 404 page found for the site, return the default 404 error page return((System.Web.UI.Page)BuildManager.CreateInstanceFromVirtualPath("~/Http404Error.aspx", typeof(System.Web.UI.Page))); } }
public FinancialTransactionsExport Export( int page = 1, int pageSize = 1000, string sortBy = null, System.Web.UI.WebControls.SortDirection sortDirection = System.Web.UI.WebControls.SortDirection.Ascending, int?dataViewId = null, DateTime?modifiedSince = null, DateTime?startDateTime = null, DateTime?endDateTime = null, string attributeKeys = null, AttributeReturnType attributeReturnType = AttributeReturnType.Raw ) { // limit to 'API Max Items Per Page' global attribute int maxPageSize = GlobalAttributesCache.Get().GetValue("core_ExportAPIsMaxItemsPerPage").AsIntegerOrNull() ?? 1000; var actualPageSize = Math.Min(pageSize, maxPageSize); FinancialTransactionExportOptions exportOptions = new FinancialTransactionExportOptions { SortBy = sortBy, SortDirection = sortDirection, DataViewId = dataViewId, ModifiedSince = modifiedSince, AttributeList = AttributesExport.GetAttributesFromAttributeKeys <FinancialTransaction>(attributeKeys), AttributeReturnType = attributeReturnType, StartDateTime = startDateTime, EndDateTime = endDateTime }; var rockContext = new RockContext(); var financialTransactionService = new FinancialTransactionService(rockContext); return(financialTransactionService.GetFinancialTransactionExport(page, actualPageSize, exportOptions)); }
/// <summary> /// Validates the type of the file. /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile">The uploaded file.</param> /// <exception cref="WebFaultException{System.String}">Filetype not allowed</exception> public virtual void ValidateFileType(HttpContext context, HttpPostedFile uploadedFile) { // validate file type (applies to all uploaded files) var globalAttributesCache = GlobalAttributesCache.Get(); IEnumerable <string> contentFileTypeBlackList = (globalAttributesCache.GetValue("ContentFiletypeBlacklist") ?? string.Empty).Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); contentFileTypeBlackList = contentFileTypeBlackList.Select(a => a.ToLower().TrimStart(new char[] { '.', ' ' })); IEnumerable <string> contentFileTypeWhiteList = (globalAttributesCache.GetValue("ContentFiletypeWhitelist") ?? string.Empty).Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); contentFileTypeWhiteList = contentFileTypeWhiteList.Select(a => a.ToLower().TrimStart(new char[] { '.', ' ' })); string filename = ScrubFileName(uploadedFile.FileName); // Get file extension and then trim any trailing spaces (to catch any nefarious stuff). string fileExtension = Path.GetExtension(filename).ToLower().TrimStart(new char[] { '.' }).Trim(); if (contentFileTypeBlackList.Contains(fileExtension)) { throw new Rock.Web.FileUploadException("Filetype not allowed", System.Net.HttpStatusCode.NotAcceptable); } if (contentFileTypeWhiteList.Any() && !contentFileTypeWhiteList.Contains(fileExtension)) { throw new Rock.Web.FileUploadException("Filetype not allowed", System.Net.HttpStatusCode.NotAcceptable); } }
/// <inheritdoc/> public override string GetClientValue(string value, Dictionary <string, string> configurationValues) { var guid = value.AsGuidOrNull(); Location location = null; if (guid.HasValue) { location = new LocationService(new RockContext()).Get(guid.Value); } if (location != null) { return(new AddressFieldValue { Street1 = location.Street1, Street2 = location.Street2, City = location.City, State = location.State, PostalCode = location.PostalCode, Country = location.Country }.ToCamelCaseJson(false, true)); } else { var globalAttributesCache = GlobalAttributesCache.Get(); return(new AddressFieldValue { State = globalAttributesCache.OrganizationState, Country = globalAttributesCache.OrganizationCountry }.ToCamelCaseJson(false, true)); } }
/// <inheritdoc/> public override string GetValueFromClient(string clientValue, Dictionary <string, string> configurationValues) { var addressValue = clientValue.FromJsonOrNull <AddressFieldValue>(); if (addressValue == null) { return(string.Empty); } var globalAttributesCache = GlobalAttributesCache.Get(); using (var rockContext = new RockContext()) { var locationService = new LocationService(rockContext); var location = locationService.Get(addressValue.Street1, addressValue.Street2, addressValue.City, addressValue.State, addressValue.PostalCode, addressValue.Country.IfEmpty(globalAttributesCache.OrganizationCountry)); if (location == null) { return(string.Empty); } return(location.Guid.ToString()); } }
/// <summary> /// Set the configuration of the address controls according to internal settings. /// </summary> private void ApplyCountryConfigurationToControls() { bool addressLine2IsVisible = (_AddressLine2Requirement != DataEntryRequirementLevelSpecifier.Unavailable); _tbStreet1.Attributes["field-name"] = addressLine2IsVisible ? "Address Line 1" : "Address"; _tbStreet1.Attributes["placeholder"] = addressLine2IsVisible ? "Address Line 1" : "Address"; _tbStreet1.Attributes["autocomplete"] = addressLine2IsVisible ? "address-line1" : "street-address"; _tbStreet2.Attributes["field-name"] = "Address Line 2"; _tbCity.Attributes["field-name"] = _CityLabel; _tbCounty.Attributes["field-name"] = _LocalityLabel; _tbState.Attributes["field-name"] = _StateLabel; _ddlState.Attributes["field-name"] = _StateLabel; _tbPostalCode.Attributes["field-name"] = _PostalCodeLabel; _tbCity.Attributes["placeholder"] = _CityLabel; _tbCounty.Attributes["placeholder"] = _LocalityLabel; _tbState.Attributes["placeholder"] = _StateLabel; _ddlState.Attributes["placeholder"] = _StateLabel; _tbPostalCode.Attributes["placeholder"] = _PostalCodeLabel; bool?showCountry = GlobalAttributesCache.Get().GetValue("SupportInternationalAddresses").AsBooleanOrNull(); _ddlCountry.Visible = showCountry.HasValue && showCountry.Value; }
/// <summary> /// Binds the countries data source to the selection control. /// </summary> private void BindCountries() { var definedType = DefinedTypeCache.Get(new Guid(SystemGuid.DefinedType.LOCATION_COUNTRIES)); var countryValues = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid()) .DefinedValues .OrderBy(v => v.Order) .ThenBy(v => v.Value) .ToList(); // Move default country to the top of the list string defaultCountryCode = GetDefaultCountry(); if (!string.IsNullOrWhiteSpace(defaultCountryCode)) { var defaultCountry = countryValues .Where(v => v.Value.Equals(defaultCountryCode, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (defaultCountry != null) { _ddlCountry.Items.Add(new ListItem("Countries", string.Empty)); _ddlCountry.Items.Add(new ListItem(UseCountryAbbreviation ? defaultCountry.Value : defaultCountry.Description, defaultCountry.Value)); _ddlCountry.Items.Add(new ListItem("------------------------", "------------------------")); } } foreach (var country in countryValues) { _ddlCountry.Items.Add(new ListItem(UseCountryAbbreviation ? country.Value : country.Description, country.Value)); } bool?showCountry = GlobalAttributesCache.Get().GetValue("SupportInternationalAddresses").AsBooleanOrNull(); _ddlCountry.Visible = showCountry.HasValue && showCountry.Value; }
/// <summary> /// Sets up the iframe. /// </summary> private void SetupIFrame() { var globalAttributesCache = GlobalAttributesCache.Get(); string imageFileTypeWhiteList = globalAttributesCache.GetValue("ContentImageFiletypeWhitelist"); string fileTypeBlackList = globalAttributesCache.GetValue("ContentFiletypeBlacklist"); string fileTypeWhiteList = globalAttributesCache.GetValue("ContentFiletypeWhitelist"); var iframeUrl = ResolveRockUrl("~/htmleditorplugins/rockfilebrowser"); string rootFolder = GetAttributeValue("RootFolder"); string browseMode = GetAttributeValue("BrowseMode"); string url = LinkedPageUrl("FileEditorPage"); if (string.IsNullOrWhiteSpace(browseMode)) { browseMode = "doc"; } iframeUrl += "?rootFolder=" + HttpUtility.UrlEncode(Encryption.EncryptString(rootFolder)); iframeUrl += "&browseMode=" + browseMode; iframeUrl += "&fileTypeBlackList=" + HttpUtility.UrlEncode(fileTypeBlackList); iframeUrl += "&fileTypeWhiteList=" + HttpUtility.UrlEncode(fileTypeWhiteList); iframeUrl += "&editFilePage=" + HttpUtility.UrlEncode(url); if (browseMode == "image") { iframeUrl += "&imageFileTypeWhiteList=" + HttpUtility.UrlEncode(imageFileTypeWhiteList); } iframeUrl += "&theme=" + this.RockPage.Site.Theme; iframeFileBrowser.Src = iframeUrl; }
private void Send(string recipients, string fromEmail, string fromName, string subject, string body, Dictionary <string, object> mergeFields, RockContext rockContext, bool createCommunicationRecord, BinaryFile[] attachments) { var emailMessage = new RockEmailMessage(); foreach (string recipient in recipients.SplitDelimitedValues().ToList()) { emailMessage.AddRecipient(new RecipientData(recipient, mergeFields)); } emailMessage.FromEmail = fromEmail; emailMessage.FromName = fromName.IsNullOrWhiteSpace() ? fromEmail : fromName; emailMessage.Subject = subject; emailMessage.Message = body; foreach (BinaryFile b in attachments) { if (b != null) { emailMessage.Attachments.Add(b); } } emailMessage.CreateCommunicationRecord = createCommunicationRecord; emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty; emailMessage.Send(); }
private static void InitGlobalAttributesCache() { DateTime today = RockDateTime.Now; GlobalAttributesCache globalAttributes = GlobalAttributesCache.Get(); globalAttributes.SetValue("GradeTransitionDate", string.Format("{0}/{1}", today.Month, today.Day), false); }
/// <summary> /// Binds the pipeline detail read only section. /// </summary> /// <param name="smsPipeline">The SMS pipeline.</param> private void BindReadOnlyDetails(SmsPipeline smsPipeline) { divSmsActionsPanel.Visible = true; divEditDetails.Visible = false; pdAuditDetails.Visible = true; pdAuditDetails.SetEntity(smsPipeline, ResolveRockUrl("~")); hlInactive.Visible = !smsPipeline.IsActive; lSmsPipelineDescription.Text = smsPipeline.Description; lSmsName.Text = smsPipeline.Name; var smsMedium = new Sms(); var smsTransport = smsMedium.Transport as ISmsPipelineWebhook; lWebhookUrl.Visible = false; if (smsTransport != null) { var globalAttributes = GlobalAttributesCache.Get(); string publicAppRoot = globalAttributes.GetValue("PublicApplicationRoot"); lWebhookUrl.Text = string.Format("{0}{1}?{2}={3}", publicAppRoot, smsTransport.SmsPipelineWebhookPath, PageParameterKey.EntityId, GetSmsPipelineId()); lWebhookUrl.Visible = true; } }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed) { string formattedValue = string.Empty; if (!string.IsNullOrWhiteSpace(value)) { Guid?locGuid = value.AsGuidOrNull(); if (locGuid.HasValue) { // Check to see if this is the org address first (to avoid db read) var globalAttributesCache = GlobalAttributesCache.Get(); var orgLocGuid = globalAttributesCache.GetValue("OrganizationAddress").AsGuidOrNull(); if (orgLocGuid.HasValue && orgLocGuid.Value == locGuid.Value) { return(globalAttributesCache.OrganizationLocationFormatted); } } using (var rockContext = new RockContext()) { var service = new LocationService(rockContext); var location = service.GetNoTracking(new Guid(value)); if (location != null) { formattedValue = location.ToString(); } } } return(base.FormatValue(parentControl, formattedValue, null, condensed)); }
protected override void OnInit(EventArgs e) { RockContext rockContext = new RockContext(); base.OnInit(e); //Reject non user if (CurrentUser == null) { NavigateToHomePage(); return; } LoadSession(rockContext); GroupType FilterGroupType = new GroupTypeService(rockContext) .Get(GlobalAttributesCache.Get().GetValue("FilterGroupType").AsGuid()); //If this group type inherits Filter Group if (CurrentGroup != null && FilterGroupType != null && CurrentGroup.GroupType.InheritedGroupTypeId == FilterGroupType.Id) { CurrentGroup.GroupType.LoadAttributes(); CurrentGroupFilters = CurrentGroup.GroupType.GetAttributeValue("FilterAttribute") .Split(new char[','], StringSplitOptions.RemoveEmptyEntries) .ToList(); } else { CurrentGroupFilters = new List <string>(); } }
private string GetSafeSender(string email) { var safeDomains = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.COMMUNICATION_SAFE_SENDER_DOMAINS.AsGuid()).DefinedValues.Select(v => v.Value).ToList(); var emailParts = email.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries); if (emailParts.Length != 2 || !safeDomains.Contains(emailParts[1], StringComparer.OrdinalIgnoreCase)) { var safeEmail = GetAttributeValue("SafeSenderEmail"); var safeEmailParts = safeEmail.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries); if (!string.IsNullOrWhiteSpace(safeEmail) && safeEmailParts.Length == 2 && safeDomains.Contains(safeEmailParts[1], StringComparer.OrdinalIgnoreCase)) { return(safeEmail); } else { return(GlobalAttributesCache.Get().GetValue("OrganizationEmail")); } } if (!string.IsNullOrWhiteSpace(email)) { return(email); } return(GlobalAttributesCache.Get().GetValue("OrganizationEmail")); }
/// <summary> /// Gets the attachment media urls. /// </summary> /// <param name="attachments">The attachments.</param> /// <returns></returns> private List <Uri> GetAttachmentMediaUrls(IQueryable <BinaryFile> attachments) { var binaryFilesInfo = attachments.Select(a => new { a.Id, a.MimeType }).ToList(); List <Uri> attachmentMediaUrls = new List <Uri>(); if (binaryFilesInfo.Any()) { string publicAppRoot = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash(); attachmentMediaUrls = binaryFilesInfo.Select(b => { if (b.MimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) { return(new Uri($"{publicAppRoot}GetImage.ashx?id={b.Id}")); } else { return(new Uri($"{publicAppRoot}GetFile.ashx?id={b.Id}")); } }).ToList(); } return(attachmentMediaUrls); }
/// <summary> /// Sets the organization address defaults. /// </summary> private void SetOrganizationAddressDefaults() { var globalAttributesCache = GlobalAttributesCache.Get(); _orgState = globalAttributesCache.OrganizationState; _orgCountry = globalAttributesCache.OrganizationCountry; }
/// <summary> /// Gets the file URL. /// </summary> /// <param name="fileId">The configuration mobile phone file identifier.</param> /// <returns>full path of resource from Binary file path</returns> private static string GetFileUrl(int?fileId) { string virtualPath = string.Empty; if (fileId.HasValue) { using (var rockContext = new RockContext()) { var binaryFile = new BinaryFileService(rockContext).Get(( int )fileId); if (binaryFile != null) { if (binaryFile.Path.Contains("~")) { // Need to build out full path virtualPath = VirtualPathUtility.ToAbsolute(binaryFile.Path); var globalAttributes = GlobalAttributesCache.Get(); string publicAppRoot = globalAttributes.GetValue("PublicApplicationRoot"); virtualPath = $"{publicAppRoot}{virtualPath}"; } else { virtualPath = binaryFile.Path; } } } } return(virtualPath); }
/// <summary> /// Creates the child controls. /// </summary> /// <returns></returns> public override Control[] CreateChildControls(System.Web.UI.Control parentControl) { var comparisonControl = ComparisonHelper.ComparisonControl(ComparisonType.LessThan | ComparisonType.GreaterThanOrEqualTo | ComparisonType.EqualTo); comparisonControl.ID = parentControl.ID + "_0"; parentControl.Controls.Add(comparisonControl); var globalAttributes = GlobalAttributesCache.Get(); NumberBox numberBoxAmount = new NumberBox(); numberBoxAmount.PrependText = globalAttributes.GetValue("CurrencySymbol") ?? "$"; numberBoxAmount.NumberType = ValidationDataType.Currency; numberBoxAmount.ID = parentControl.ID + "_1"; numberBoxAmount.Label = "Amount"; parentControl.Controls.Add(numberBoxAmount); AccountPicker accountPicker = new AccountPicker(); accountPicker.AllowMultiSelect = true; accountPicker.ID = parentControl.ID + "_accountPicker"; accountPicker.AddCssClass("js-account-picker"); accountPicker.Label = "Accounts"; parentControl.Controls.Add(accountPicker); SlidingDateRangePicker slidingDateRangePicker = new SlidingDateRangePicker(); slidingDateRangePicker.ID = parentControl.ID + "_slidingDateRangePicker"; slidingDateRangePicker.AddCssClass("js-sliding-date-range"); slidingDateRangePicker.Label = "Date Range"; slidingDateRangePicker.Help = "The date range of the transactions using the transaction date of each transaction"; slidingDateRangePicker.Required = true; parentControl.Controls.Add(slidingDateRangePicker); RockCheckBox cbCombineGiving = new RockCheckBox(); cbCombineGiving.ID = parentControl.ID + "_cbCombineGiving"; cbCombineGiving.Label = "Combine Giving"; cbCombineGiving.CssClass = "js-combine-giving"; cbCombineGiving.Help = "Combine individuals in the same giving group when calculating totals and reporting the list of individuals."; parentControl.Controls.Add(cbCombineGiving); RockCheckBox cbUseAnalytics = new RockCheckBox(); cbUseAnalytics.ID = parentControl.ID + "_cbUseAnalytics"; cbUseAnalytics.Label = "Use Analytics Models"; cbUseAnalytics.CssClass = "js-use-analytics"; cbUseAnalytics.Help = "Using Analytics Data is MUCH faster than querying real-time data, but it may not include data that has been added or updated in the last 24 hours."; parentControl.Controls.Add(cbUseAnalytics); var controls = new Control[6] { comparisonControl, numberBoxAmount, accountPicker, slidingDateRangePicker, cbCombineGiving, cbUseAnalytics }; SetSelection(controls, $"{ComparisonType.GreaterThanOrEqualTo.ConvertToInt().ToString()}|||||||"); return(controls); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(System.EventArgs e) { EnsureChildControls(); base.OnInit(e); _ShowCountrySelection = GlobalAttributesCache.Get().GetValue("SupportInternationalAddresses").AsBooleanOrNull() ?? false; BindCountries(); }
/// <summary> /// Job that updates the JobPulse setting with the current date/time. /// This will allow us to notify an admin if the jobs stop running. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { var globalAttributesCache = GlobalAttributesCache.Get(); // Update a JobPulse global attribute value so that 3rd Party plugins could query this value in case they need to know globalAttributesCache.SetValue("JobPulse", RockDateTime.Now.ToString(), true); UpdateScheduledJobs(context); }
/// <summary> /// Sends statistics to the SDN server but only if there are more than 100 person records /// or the sample data has not been loaded. /// /// The statistics are: /// * Rock Instance Id /// * Update Version /// * IP Address - The IP address of your Rock server. /// /// ...and we only send these if they checked the "Include Impact Statistics": /// * Organization Name and Address /// * Public Web Address /// * Number of Active Records /// /// As per https://www.rockrms.com/Rock/Impact /// </summary> /// <param name="version">the semantic version number</param> private void SendStatictics(string version) { try { var rockContext = new RockContext(); int numberOfActiveRecords = new PersonService(rockContext).Queryable(includeDeceased: false, includeBusinesses: false).Count(); if (numberOfActiveRecords > 100 || !Rock.Web.SystemSettings.GetValue(Rock.SystemKey.SystemSetting.SAMPLEDATA_DATE).AsDateTime().HasValue) { string organizationName = string.Empty; ImpactLocation organizationLocation = null; string publicUrl = string.Empty; var rockInstanceId = Rock.Web.SystemSettings.GetRockInstanceId(); var ipAddress = Request.ServerVariables["LOCAL_ADDR"]; if (cbIncludeStats.Checked) { var globalAttributes = GlobalAttributesCache.Get(); organizationName = globalAttributes.GetValue("OrganizationName"); publicUrl = globalAttributes.GetValue("PublicApplicationRoot"); // Fetch the organization address var organizationAddressLocationGuid = globalAttributes.GetValue("OrganizationAddress").AsGuid(); if (!organizationAddressLocationGuid.Equals(Guid.Empty)) { var location = new Rock.Model.LocationService(rockContext).Get(organizationAddressLocationGuid); if (location != null) { organizationLocation = new ImpactLocation(location); } } } else { numberOfActiveRecords = 0; } var environmentData = RockUpdateHelper.GetEnvDataAsJson(Request, ResolveRockUrl("~/")); // now send them to SDN/Rock server SendToSpark(rockInstanceId, version, ipAddress, publicUrl, organizationName, organizationLocation, numberOfActiveRecords, environmentData); } } catch (Exception ex) { // Just catch any exceptions, log it, and keep moving... We don't want to mess up the experience // over a few statistics/metrics. try { LogException(ex); } catch { } } }
/// <summary> /// Registers the java script. /// </summary> protected virtual void RegisterJavaScript() { string mapStyle = "null"; string markerColor = ""; try { DefinedValueCache dvcMapStyle = DefinedValueCache.Get(this.MapStyleValueGuid); if (dvcMapStyle != null) { mapStyle = dvcMapStyle.GetAttributeValue("DynamicMapStyle"); var colors = dvcMapStyle.GetAttributeValue("Colors").Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (colors.Any()) { markerColor = colors.First().Replace("#", ""); } } } catch { } // oh well... string options = string.Format("controlId: '{0}', drawingMode: '{1}', strokeColor: '{2}', fillColor: '{2}', mapStyle: {3}", this.ClientID, this.DrawingMode, markerColor, mapStyle); DbGeography centerPoint = CenterPoint; if (centerPoint != null && centerPoint.Latitude != null && centerPoint.Longitude != null) { options += string.Format(", centerLatitude: '{0}', centerLongitude: '{1}'", centerPoint.Latitude, centerPoint.Longitude); } else { // If no centerpoint was defined, try to get it from organization address var globalAttributes = GlobalAttributesCache.Get(); Guid guid = globalAttributes.GetValue("OrganizationAddress").AsGuid(); if (!guid.Equals(Guid.Empty)) { var location = new Rock.Model.LocationService(new Rock.Data.RockContext()).Get(guid); if (location != null && location.GeoPoint != null && location.GeoPoint.Latitude != null && location.GeoPoint.Longitude != null) { CenterPoint = location.GeoPoint; options += string.Format(", centerLatitude: '{0}', centerLongitude: '{1}'", location.GeoPoint.Latitude, location.GeoPoint.Longitude); } } } string script = string.Format(@" // if the geoPicker was rendered, initialize it if ($('#{1}').length > 0) {{ Rock.controls.geoPicker.initialize({{ {0} }}); }} ", options, this.ClientID); ScriptManager.RegisterStartupScript(this, this.GetType(), "geo_picker-" + this.ClientID, script, true); }
/// <summary> /// Sends the asynchronous. /// </summary> /// <param name="rockMessage">The rock message.</param> /// <returns></returns> public virtual async Task <SendMessageResult> SendAsync(RockMessage rockMessage) { if (this.IsActive) { // Get the Medium's Entity Type Id int mediumEntityTypeId = EntityTypeCache.Get(this.GetType()).Id; // Add the Medium's settings as attributes for the Transport to use. var mediumAttributes = GetMediumAttributes(); // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults. if (rockMessage.EnabledLavaCommands == null) { rockMessage.EnabledLavaCommands = GlobalAttributesCache.Get().GetValue("DefaultEnabledLavaCommands"); } // Use the transport to send communication var transport = Transport; if (transport != null && transport.IsActive) { var asyncTransport = transport as IAsyncTransport; if (asyncTransport == null) { var messageResult = new SendMessageResult { MessagesSent = transport.Send(rockMessage, mediumEntityTypeId, mediumAttributes, out var errorMessage) ? rockMessage.GetRecipients().Count : 0 }; return(await Task.FromResult(messageResult)); } else { return(await asyncTransport.SendAsync(rockMessage, mediumEntityTypeId, mediumAttributes).ConfigureAwait(false)); } } else { return(new SendMessageResult { Errors = new List <string> { "Invalid or Inactive Transport." } }); } } else { return(new SendMessageResult { Errors = new List <string> { "Inactive Medium." } }); } }
/// <summary> /// Gets the Zoom webhook url. /// </summary> /// <returns></returns> public static string GetWebhookUrl() { string webhookUrl = null; var appUrl = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot"); if (!string.IsNullOrWhiteSpace(appUrl)) { webhookUrl = string.Format("{0}Plugins/rocks_kfs/Zoom/Webhook.ashx", appUrl); } return(webhookUrl); }
/// <summary> /// Gets the domain URI. /// </summary> /// <param name="siteId">The site identifier.</param> /// <returns></returns> public Uri GetDefaultDomainUri(int siteId) { var site = this.Get(siteId); if (site != null) { return(site.DefaultDomainUri); } return(new Uri(GlobalAttributesCache.Get().GetValue("PublicApplicationRoot"))); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(System.EventArgs e) { base.OnInit(e); var globalAttributes = GlobalAttributesCache.Get(); if (globalAttributes != null) { this.PrependText = "<i class='fa fa-link'></i>"; } }
/// <summary> /// Gets the PersonToken by impersonation token (rckipid) /// </summary> /// <param name="impersonationToken">The impersonation token.</param> /// <returns></returns> public PersonToken GetByImpersonationToken(string impersonationToken) { // the impersonationToken should normally be a UrlEncoded string, but it is possible that the caller already UrlDecoded it, so first try without UrlDecoding it var decryptedToken = Rock.Security.Encryption.DecryptString(impersonationToken); if (decryptedToken == null) { // do a Replace('!', '%') on the token before UrlDecoding because we did a Replace('%', '!') after we UrlEncoded it (to make it embeddable in HTML and cross browser compatible) string urlDecodedKey = System.Web.HttpUtility.UrlDecode(impersonationToken.Replace('!', '%')); decryptedToken = Rock.Security.Encryption.DecryptString(urlDecodedKey); } var personToken = this.Queryable().Include(pt => pt.PersonAlias).FirstOrDefault(a => a.Token == decryptedToken); if (personToken == null) { bool tokenUseLegacyFallback = GlobalAttributesCache.Get().GetValue("core.PersonTokenUseLegacyFallback").AsBoolean(); if (tokenUseLegacyFallback) { var legacyPerson = new PersonService(this.Context as Data.RockContext).GetByLegacyEncryptedKey(impersonationToken, true); if (legacyPerson == null || !legacyPerson.IsPersonTokenUsageAllowed()) { return(null); } if (legacyPerson != null) { // if LegacyFallback is enabled, and we found a person, create a fake PersonToken personToken = new PersonToken { PersonAlias = legacyPerson.PrimaryAlias, ExpireDateTime = null, PageId = null, LastUsedDateTime = RockDateTime.Now, UsageLimit = null }; } } else { return(null); } } var person = new PersonService(this.Context as Data.RockContext).Get(personToken.PersonAlias.PersonId); if (!person.IsPersonTokenUsageAllowed()) { return(null); } return(personToken); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(System.EventArgs e) { base.OnInit(e); var globalAttributes = GlobalAttributesCache.Get(); if (globalAttributes != null) { string symbol = globalAttributes.GetValue("CurrencySymbol"); this.PrependText = string.IsNullOrWhiteSpace(symbol) ? "$" : symbol; } }