예제 #1
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            var rockContext = new RockContext();

            var    currentUser   = new UserLoginService(rockContext).GetByUserName(UserLogin.GetCurrentUserName());
            Person currentPerson = currentUser != null ? currentUser.Person : null;

            Person person = GetPerson(context, rockContext);

            if (person == null)
            {
                SendNotFound(context);
                return;
            }
            else
            {
                if (!person.IsAuthorized(Authorization.VIEW, currentPerson))
                {
                    SendNotAuthorized(context);
                    return;
                }
            }

            var response = context.Response;

            response.ContentType = "text/vcard";

            // http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http
            string contentDisposition;
            string fileName = person.FullName + ".vcf";

            if (context.Request.Browser.Browser == "IE")
            {
                contentDisposition = "attachment; filename=" + Uri.EscapeDataString(fileName);
            }
            else if (context.Request.Browser.Browser == "Safari")
            {
                contentDisposition = "attachment; filename=" + fileName;
            }
            else
            {
                contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(fileName);
            }
            response.AddHeader("Content-Disposition", contentDisposition);

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, currentPerson);

            mergeFields.Add("Person", person);
            string vCard = GlobalAttributesCache.Value("VCardFormat").ResolveMergeFields(mergeFields).Trim();

            // remove empty lines (the vcard spec is very picky)
            vCard = Regex.Replace(vCard, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);

            var inputEncoding  = Encoding.Default;
            var outputEncoding = Encoding.GetEncoding(28591);
            var cardBytes      = inputEncoding.GetBytes(vCard);
            var outputBytes    = Encoding.Convert(inputEncoding, outputEncoding, cardBytes);

            response.OutputStream.Write(outputBytes, 0, outputBytes.Length);
        }
예제 #2
0
        /// <summary>
        /// Notifies the admins.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="message">The message.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param>
        /// <exception cref="System.Exception">Error sending System Email: Could not read Email Medium Entity Type</exception>
        public static void NotifyAdmins(string subject, string message, string appRoot = "", string themeRoot = "", bool createCommunicationHistory = true)
        {
            try
            {
                List <string> recipients = null;

                Guid adminGroup = Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid();
                using (var rockContext = new RockContext())
                {
                    recipients = new GroupMemberService(rockContext).Queryable()
                                 .Where(m =>
                                        m.Group.Guid.Equals(adminGroup) &&
                                        m.GroupMemberStatus == GroupMemberStatus.Active &&
                                        m.Person.Email != null &&
                                        m.Person.Email != "")
                                 .Select(m => m.Person.Email)
                                 .ToList();
                }

                Email.Send(GlobalAttributesCache.Value("OrganizationEmail"), subject, recipients, message, appRoot, themeRoot, null, createCommunicationHistory);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, HttpContext.Current);
            }
        }
예제 #3
0
        /// <summary>
        /// Creates the HTML controls required to configure this type of field
        /// </summary>
        /// <returns></returns>
        public override List <Control> ConfigurationControls()
        {
            var controls = new List <Control>();

            var infoBox = new NotificationBox
            {
                NotificationBoxType = NotificationBoxType.Info,
                Text = "The user will be prompted to complete verify they are human each time this field is displayed in edit mode."
            };

            controls.Add(infoBox);

            var siteKey   = GlobalAttributesCache.Value("core_GoogleReCaptchaSiteKey");
            var secretKey = GlobalAttributesCache.Value("core_GoogleReCaptchaSecretKey");

            if (siteKey.IsNullOrWhiteSpace() || secretKey.IsNullOrWhiteSpace())
            {
                var nokeysBox = new NotificationBox
                {
                    NotificationBoxType = NotificationBoxType.Warning,
                    Text = "Google ReCaptcha site key or secret key have not been configured yet. Captcha will not work until those are set."
                };
                controls.Add(nokeysBox);
            }

            return(controls);
        }
        public HttpResponseMessage GetVCard(Guid personGuid)
        {
            var rockContext = (Rock.Data.RockContext)Service.Context;

            var person = new PersonService(rockContext).Get(personGuid);

            if (person == null)
            {
                throw new HttpResponseException(new System.Net.Http.HttpResponseMessage(HttpStatusCode.NotFound));
            }

            string fileName            = person.FullName + ".vcf";
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, GetPerson());

            mergeFields.Add("Person", person);
            string vCard = GlobalAttributesCache.Value("VCardFormat").ResolveMergeFields(mergeFields).Trim();

            // remove empty lines (the vcard spec is very picky)
            vCard = Regex.Replace(vCard, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);

            var inputEncoding  = Encoding.Default;
            var outputEncoding = Encoding.GetEncoding(28591);
            var cardBytes      = inputEncoding.GetBytes(vCard);
            var outputBytes    = Encoding.Convert(inputEncoding, outputEncoding, cardBytes);

            result.Content = new ByteArrayContent(outputBytes);
            result.Content.Headers.ContentType                 = new System.Net.Http.Headers.MediaTypeHeaderValue("text/vcard");
            result.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = fileName;
            return(result);
        }
예제 #5
0
        public Dictionary <string, string> PostInteraction()
        {
            HttpContent            requestContent         = Request.Content;
            string                 content                = requestContent.ReadAsStringAsync().Result;
            InteractionInformation interactionInformation = JsonConvert.DeserializeObject <InteractionInformation>(content);

            var homePageId = GlobalAttributesCache.Value("AvalancheHomePage").AsInteger();
            var pageCache  = PageCache.Read(homePageId);
            var siteId     = pageCache.SiteId;
            var person     = GetPerson();

            AppInteractionTransaction transaction = new AppInteractionTransaction()
            {
                ComponentName      = "Mobile App",
                SiteId             = siteId,
                PageId             = interactionInformation.PageId.AsIntegerOrNull(),
                PageTitle          = interactionInformation.PageTitle,
                DateViewed         = Rock.RockDateTime.Now,
                Operation          = interactionInformation.Operation,
                PersonAliasId      = person?.PrimaryAliasId,
                InteractionData    = interactionInformation.InteractionData,
                InteractionSummary = interactionInformation.InteractionSummary,
                IPAddress          = GetClientIp(Request),
                UserAgent          = Request.Headers.UserAgent.ToString()
            };

            RockQueue.TransactionQueue.Enqueue(transaction);
            return(new Dictionary <string, string> {
                { "Status", "Ok" }
            });
        }
        private void PrepopulateUrl()
        {
            var eventType   = ddlEventType.SelectedValue.Split('.'); // <-- looks like a face
            var externalUrl = GlobalAttributesCache.Value("PublicApplicationRoot").EnsureTrailingForwardslash();

            tbUrl.Text = string.Format("{0}api/lms/rise/{1}/{2}", externalUrl, eventType[0], eventType[1]);
        }
예제 #7
0
        /// <summary>
        /// Checks for merge fields and then resolves them.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <param name="enabledLavaCommands">The enabled lava commands.</param>
        /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns>
        public static string ResolveMergeFields(this string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands)
        {
            try
            {
                if (!content.HasMergeFields())
                {
                    return(content ?? string.Empty);
                }

                // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults.
                if (enabledLavaCommands == null)
                {
                    enabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands");
                }

                Template template = GetTemplate(content);
                template.Registers.AddOrReplace("EnabledCommands", enabledLavaCommands);
                template.InstanceAssigns.AddOrReplace("CurrentPerson", currentPersonOverride);
                return(template.Render(Hash.FromDictionary(mergeObjects)));
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                return("Error resolving Lava merge fields: " + ex.Message);
            }
        }
예제 #8
0
        /// <summary>
        /// If input is a string that has been formatted as currency, return the decimal value. Otherwise return the object unchanged.
        /// </summary>
        /// <param name="input">A value that may be a currency-formatted string.</param>
        /// <returns></returns>
        public static object ReverseCurrencyFormatting(this object input)
        {
            var exportValueString = input as string;

            // If the object is a string...
            if (exportValueString != null)
            {
                var currencySymbol = GlobalAttributesCache.Value("CurrencySymbol");

                // ... that contains the currency symbol ...
                if (exportValueString.Contains(currencySymbol))
                {
                    var     decimalString = exportValueString.Replace(currencySymbol, string.Empty);
                    decimal exportValueDecimal;

                    // ... and the value without the currency symbol is a valid decimal value ...
                    if (decimal.TryParse(decimalString, out exportValueDecimal))
                    {
                        // ... that matches the input string when formatted as currency ...
                        if (exportValueDecimal.FormatAsCurrency() == exportValueString)
                        {
                            // ... return the input as a decimal
                            return(exportValueDecimal);
                        }
                    }
                }
            }

            // Otherwise just return the input back out
            return(input);
        }
예제 #9
0
        // used for private variables

        #endregion

        #region Properties

        // used for public / protected properties

        #endregion

        #region Base Control Methods

        //  overrides of the base RockBlock methods (i.e. OnInit, OnLoad)

        /// <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(EventArgs e)
        {
            base.OnInit(e);

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger(upnlContent);

            // provide some good default values for from email / from name
            string fromEmail = GetAttributeValue("FromEmail");

            if (string.IsNullOrWhiteSpace(fromEmail))
            {
                SetAttributeValue("FromEmail", GlobalAttributesCache.Value("OrganizationEmail"));
                SaveAttributeValues();
            }

            string fromName = GetAttributeValue("FromName");

            if (string.IsNullOrWhiteSpace(fromEmail))
            {
                SetAttributeValue("FromName", GlobalAttributesCache.Value("OrganizationName"));
                SaveAttributeValues();
            }

            Page.Form.Enctype = "multipart/form-data";
        }
        /// <summary>
        /// Use Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <param name="enabledLavaCommands">A comma-delimited list of the lava commands that are enabled for this template.</param>
        /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns>
        public static string RenderLava(this string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands)
        {
            try
            {
                // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults.
                if (enabledLavaCommands == null)
                {
                    enabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands");
                }

                var context = LavaService.NewRenderContext();

                context.SetEnabledCommands(enabledLavaCommands, ",");

                context.SetMergeField("CurrentPerson", currentPersonOverride);
                context.SetMergeFields(mergeObjects);

                var result = LavaService.RenderTemplate(content, LavaRenderParameters.WithContext(context));

                if (result.HasErrors)
                {
                    throw result.GetLavaException();
                }

                return(result.Text);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                return("Error resolving Lava merge fields: " + ex.Message);
            }
        }
예제 #11
0
        public HomeRequest GetHome()
        {
            var homeRequest = new HomeRequest();

            var footer = GlobalAttributesCache.Value("AvalancheFooterPage").AsIntegerOrNull();

            if (footer != null)
            {
                homeRequest.Footer = GetPage(footer.Value);
            }

            var header = GlobalAttributesCache.Value("AvalancheHeaderPage").AsIntegerOrNull();

            if (header != null)
            {
                homeRequest.Header = GetPage(header.Value);
            }

            var menu = GlobalAttributesCache.Value("AvalancheMenuPage").AsIntegerOrNull();

            if (menu != null)
            {
                homeRequest.Menu = GetPage(menu.Value);
            }

            homeRequest.Page = GetPage(GlobalAttributesCache.Value("AvalancheHomePage").AsInteger());
            return(homeRequest);
        }
예제 #12
0
        /// <summary>
        /// Gets the TV person.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        public static TvPerson GetTvPerson(Person person)
        {
            var baseUrl           = GlobalAttributesCache.Value("PublicApplicationRoot");
            var homePhoneTypeId   = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Id;
            var mobilePhoneTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id;
            var alternateIdTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID).Id;

            var alternateId = person.GetPersonSearchKeys()
                              .Where(a => a.SearchTypeValueId == alternateIdTypeId)
                              .FirstOrDefault()?.SearchValue;

            return(new TvPerson
            {
                FirstName = person.FirstName,
                NickName = person.NickName,
                LastName = person.LastName,
                Gender = (Rock.Common.Tv.Enum.Gender)person.Gender,
                BirthDate = person.BirthDate,
                Email = person.Email,
                HomePhone = person.PhoneNumbers.Where(p => p.NumberTypeValueId == homePhoneTypeId).Select(p => p.NumberFormatted).FirstOrDefault(),
                MobilePhone = person.PhoneNumbers.Where(p => p.NumberTypeValueId == mobilePhoneTypeId).Select(p => p.NumberFormatted).FirstOrDefault(),
                HomeAddress = GetTvAddress(person.GetHomeLocation()),
                CampusGuid = person.GetCampus()?.Guid,
                PersonAliasId = person.PrimaryAliasId.Value,
                PhotoUrl = (person.PhotoId.HasValue ? $"{baseUrl}{person.PhotoUrl}" : null),
                PersonGuid = person.Guid,
                PersonId = person.Id,
                AlternateId = alternateId,
                AuthToken = TvHelper.GetAuthenticationTokenFromPerson(person)
            });
        }
예제 #13
0
        /// <summary>
        /// Use Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <param name="enabledLavaCommands">A comma-delimited list of the lava commands that are enabled for this template.</param>
        /// <param name="encodeStringOutput">if set to <c>true</c> [encode string output].</param>
        /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns>
        private static LavaRenderResult ResolveMergeFieldsWithCurrentLavaEngine(string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands, bool encodeStringOutput)
        {
            // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults.
            if (enabledLavaCommands == null)
            {
                enabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands");
            }

            var context = LavaService.NewRenderContext();

            context.SetEnabledCommands(enabledLavaCommands, ",");

            if (currentPersonOverride != null)
            {
                context.SetMergeField("CurrentPerson", currentPersonOverride);
            }

            context.SetMergeFields(mergeObjects);

            var parameters = LavaRenderParameters.WithContext(context);

            parameters.ShouldEncodeStringsAsXml = encodeStringOutput;

            var result = LavaService.RenderTemplate(content, parameters);

            if (result.HasErrors &&
                LavaService.ExceptionHandlingStrategy == ExceptionHandlingStrategySpecifier.RenderToOutput)
            {
                // If the result is an error, encode the error message to prevent any part of it from appearing as rendered content, and then add markup for line breaks.
                result.Text = result.Text.EncodeHtml().ConvertCrLfToHtmlBr();
            }

            return(result);
        }
예제 #14
0
        /// <summary>
        /// Gets the note object that will be sent to the shell.
        /// </summary>
        /// <param name="note">The database note.</param>
        /// <returns>The note object that the shell understands.</returns>
        private object GetNoteObject(Note note)
        {
            var baseUrl  = GlobalAttributesCache.Value("PublicApplicationRoot");
            var canEdit  = note.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson);
            var canReply = note.NoteType.AllowsReplies;

            // If the note type specifies the max reply depth then calculate and check.
            if (canReply && note.NoteType.MaxReplyDepth.HasValue)
            {
                int replyDepth = 0;
                for (var noteParent = note; noteParent != null; noteParent = noteParent.ParentNote)
                {
                    replyDepth += 1;
                }

                canReply = replyDepth < note.NoteType.MaxReplyDepth.Value;
            }

            return(new
            {
                note.Guid,
                NoteTypeGuid = note.NoteType.Guid,
                note.Text,
                PhotoUrl = note.CreatedByPersonAlias?.Person?.PhotoId != null ? $"{baseUrl}{note.CreatedByPersonAlias.Person.PhotoUrl}" : null,
                Name = note.CreatedByPersonName,
                Date = note.CreatedDateTime.HasValue ? ( DateTimeOffset? )new DateTimeOffset(note.CreatedDateTime.Value) : null,
                ReplyCount = note.ChildNotes.Count(b => b.IsAuthorized(Authorization.VIEW, RequestContext.CurrentPerson)),
                note.IsAlert,
                IsPrivate = note.IsPrivateNote,
                CanEdit = canEdit,
                CanDelete = canEdit,
                CanReply = canReply
            });
        }
예제 #15
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var personAliasGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "Person").AsGuid()).AsGuidOrNull();

            if (personAliasGuid.HasValue)
            {
                PersonAliasService personAliasService = new PersonAliasService(new RockContext());
                PersonAlias        personAlias        = personAliasService.Get(personAliasGuid.Value);

                var client = new RestClient(GlobalAttributesCache.Value("MinistrySafeAPIURL"));

                var request = new RestRequest("/users/{ExternalId}", Method.GET);
                request.AddHeader("Authorization", "Token token=" + GlobalAttributesCache.Value("MinistrySafeAPIToken"));
                request.AddUrlSegment("ExternalId", personAlias.Id.ToString());
                var tmp  = client.Execute <MinistrySafeUser>(request);
                var user = tmp.Data;

                SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "Score").AsGuid(), user.score.ToString());
                if (user.complete_date != null)
                {
                    SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "CompletionDate").AsGuid(), user.complete_date.ToString());
                }

                return(true);
            }
            return(false);
        }
예제 #16
0
        /// <summary>
        /// Handles the Click event of the lbSaveNew control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSaveNew_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbUserNameNew.Text) && !string.IsNullOrWhiteSpace(tbPasswordNew.Text))
            {
                using (var rockContext = new RockContext())
                {
                    var settings = GetSettings(rockContext);
                    SetSettingValue(rockContext, settings, "UserName", tbUserNameNew.Text);
                    SetSettingValue(rockContext, settings, "Password", tbPasswordNew.Text, true);

                    string defaultReturnUrl = string.Format("{0}Webhooks/ProtectMyMinistry.ashx",
                                                            GlobalAttributesCache.Value("PublicApplicationRoot").EnsureTrailingForwardslash());
                    SetSettingValue(rockContext, settings, "ReturnURL", defaultReturnUrl);

                    rockContext.SaveChanges();

                    ShowView(settings);
                }
            }
            else
            {
                nbNotification.Text    = "<p>Username and Password are both required.</p>";
                nbNotification.Visible = true;
            }
        }
예제 #17
0
        /// <summary>
        /// Use Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <param name="enabledLavaCommands">The enabled lava commands.</param>
        /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns>
        public static string ResolveMergeFields(this string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands)
        {
            try
            {
                // 7-9-2020 JME / NA
                // We decided to remove the check for lava merge fields here as this method is specifically
                // made to resolve them. The performance increase for text without lava is acceptable as in
                // a vast majority of cases the string will have lava (that's what this method is for). In
                // these cases there is a performance tax (though small) on the vast majority of calls.

                // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults.
                if (enabledLavaCommands == null)
                {
                    enabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands");
                }

                Template template = GetTemplate(content);
                template.Registers.AddOrReplace("EnabledCommands", enabledLavaCommands);
                template.InstanceAssigns.AddOrReplace("CurrentPerson", currentPersonOverride);
                return(template.Render(Hash.FromDictionary(mergeObjects)));
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                return("Error resolving Lava merge fields: " + ex.Message);
            }
        }
예제 #18
0
        private static void InitializeGlobalLavaEngineInstance(Type engineType)
        {
            // Initialize the Lava engine.
            var options = new LavaEngineConfigurationOptions();

            if (engineType != typeof(RockLiquidEngine))
            {
                var defaultEnabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands").SplitDelimitedValues(",").ToList();

                options.FileSystem             = new WebsiteLavaFileSystem();
                options.CacheService           = new WebsiteLavaTemplateCacheService();
                options.DefaultEnabledCommands = defaultEnabledLavaCommands;
            }

            LavaService.SetCurrentEngine(engineType, options);

            // Subscribe to exception notifications from the Lava Engine.
            var engine = LavaService.GetCurrentEngine();

            engine.ExceptionEncountered += Engine_ExceptionEncountered;

            // Initialize Lava extensions.
            InitializeLavaFilters(engine);
            InitializeLavaTags(engine);
            InitializeLavaBlocks(engine);
            InitializeLavaShortcodes(engine);
            InitializeLavaSafeTypes(engine);
        }
예제 #19
0
 /// <summary>
 /// Formats the specified field value for a cell in the <see cref="T:System.Web.UI.WebControls.BoundField" /> object.
 /// </summary>
 /// <param name="dataValue">The field value to format.</param>
 /// <param name="encode">true to encode the value; otherwise, false.</param>
 /// <returns>
 /// The field value converted to the format specified by <see cref="P:System.Web.UI.WebControls.BoundField.DataFormatString" />.
 /// </returns>
 protected override string FormatDataValue(object dataValue, bool encode)
 {
     if (dataValue != null)
     {
         return(string.Format("{0}{1:N}", GlobalAttributesCache.Value("CurrencySymbol"), dataValue));
     }
     return(base.FormatDataValue(dataValue, encode));
 }
예제 #20
0
        /// <summary>
        /// Adds the play button on thumbnail and returns its url
        /// </summary>
        /// <param name="image"></param>
        /// <param name="fileName"></param>
        /// <param name="overlay"></param>
        /// <returns></returns>
        public string OverlayImage(Image image, string fileName, string overlay)
        {
            var rockContext           = new RockContext();
            var binaryFileTypeService = new BinaryFileTypeService(rockContext);
            var binaryFileType        = binaryFileTypeService.Get(Rock.SystemGuid.BinaryFiletype.COMMUNICATION_IMAGE.AsGuid());
            var binaryFileService     = new BinaryFileService(rockContext);

            // If a thumbnail of the video has already been made, lets not make another
            var preMadeThumbnail = binaryFileService.Queryable()
                                   .Where(f => f.FileName == fileName && f.BinaryFileTypeId == binaryFileType.Id)
                                   .FirstOrDefault();

            if (preMadeThumbnail != null)
            {
                return(string.Format("{0}/GetImage.ashx/Thumbnail{1}.png?guid={1}&filename={2}",
                                     GlobalAttributesCache.Value("PublicApplicationRoot").Trim('/'),
                                     preMadeThumbnail.Guid,
                                     preMadeThumbnail.FileName));
            }

            image = ScaleImage(image);
            var overlayImg = Image.FromFile(overlay);

            var size = Math.Min(image.Width, image.Height);

            overlayImg = new Bitmap(overlayImg, size, size);
            var img = new Bitmap(image.Width, image.Height);

            using (Graphics gr = Graphics.FromImage(img))
            {
                gr.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;

                gr.DrawImage(image, new Point(0, 0));
                gr.DrawImage(overlayImg, new Point((image.Width / 2) - (size / 2), 0));

                var stream = new System.IO.MemoryStream();
                img.Save(stream, ImageFormat.Png);
                stream.Position = 0;

                var binaryImage = new BinaryFile
                {
                    FileName         = fileName + ".png",
                    Guid             = Guid.NewGuid(),
                    BinaryFileTypeId = binaryFileType.Id,
                    MimeType         = "image/png",
                    IsTemporary      = false,
                    ContentStream    = stream
                };
                binaryFileService.Add(binaryImage);
                rockContext.SaveChanges();

                return(string.Format("{0}/GetImage.ashx/Thumbnail{1}.png?guid={1}&filename={2}",
                                     GlobalAttributesCache.Value("PublicApplicationRoot").Trim('/'),
                                     binaryImage.Guid,
                                     binaryImage.FileName));
            }
        }
예제 #21
0
        private void CreateRefreshToken(AuthenticationTokenCreateContext context)
        {
            var settings = GlobalAttributesCache.Value("OAuthSettings").AsDictionary();

            if (settings.ContainsKey("OAuthRefreshTokenLifespan") && settings["OAuthRefreshTokenLifespan"].AsInteger() > 0)
            {
                context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddHours(settings["OAuthRefreshTokenLifespan"].AsInteger()));
            }
            context.SetToken(context.SerializeTicket());
        }
예제 #22
0
        /// <summary>
        /// Gets a URL that should be used in configuring the Site Redirects to Rock.
        /// </summary>
        /// <returns>A string representing the URL to be used for site redirects.</returns>
        protected string GetRedirectUrl()
        {
            var url = GetAttributeValue("RedirectOverride");

            if (string.IsNullOrWhiteSpace(url))
            {
                url = string.Format("{0}.well-known/acme-challenge/", GlobalAttributesCache.Value("PublicApplicationRoot"));
            }

            return(url);
        }
        /// <summary>
        /// Show a summary of discount entries.
        /// </summary>
        /// <param name="report"></param>
        private void PopulateTotals(List <TemplateDiscountReport> report)
        {
            var currencySymbol = GlobalAttributesCache.Value("CurrencySymbol");

            lTotalTotalCost.Text             = string.Format(currencySymbol + "{0:#,##0.00}", report.Sum(r => r.TotalCost));
            lTotalDiscountQualifiedCost.Text = string.Format(currencySymbol + "{0:#,##0.00}", report.Sum(r => r.DiscountQualifiedCost));
            lTotalDiscounts.Text             = string.Format(currencySymbol + "{0:#,##0.00}", report.Sum(r => r.TotalDiscount));
            lTotalRegistrationCost.Text      = string.Format(currencySymbol + "{0:#,##0.00}", report.Sum(r => r.RegistrationCost));
            lTotalRegistrations.Text         = report.Count().ToString();
            lTotalRegistrants.Text           = report.Sum(r => r.RegistrantCount).ToString();
        }
예제 #24
0
        private List <ListElement> GetGroupMembers(string parameter, int page)
        {
            if (CurrentPerson == null)
            {
                return(null);
            }

            var          groupId      = parameter.AsInteger();
            RockContext  rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);
            var          group        = groupService.Get(groupId);

            if (group == null)
            {
                return(null);
            }

            if (!group.IsAuthorized(Authorization.EDIT, CurrentPerson))
            {
                return(null);
            }

            var personId = CurrentPerson.Id;
            var members  = group.Members;
            var leaders  = members.Where(m => m.PersonId == personId && m.GroupRole.IsLeader);

            if (!leaders.Any())
            {
                return(null);
            }
            var count = GetAttributeValue("MembersPerRequest").AsInteger();

            if (count < 1)
            {
                count = 20;
            }

            return(members
                   .OrderByDescending(m => m.GroupRole.IsLeader)
                   .ThenBy(m => m.Person.FirstName)
                   .ThenBy(m => m.Person.LastName)
                   .Skip(page * count)
                   .Take(count)
                   .ToList()
                   .Where(m => m.GroupMemberStatus != GroupMemberStatus.Inactive)
                   .Select(m => new ListElement
            {
                Id = m.Guid.ToString(),
                Title = m.Person.FullName,
                Image = GlobalAttributesCache.Value("InternalApplicationRoot") + m.Person.PhotoUrl + "&width=100",
                Description = m.GroupRole.Name
            })
                   .ToList());
        }
예제 #25
0
        /// <summary>
        /// This actually runs the startup for the OAuth implementation in OWIN
        /// </summary>
        /// <param name="app">The OWIN Builder object</param>
        public void OnStartup(IAppBuilder app)
        {
            var settings = GlobalAttributesCache.Value("OAuthSettings").AsDictionary();

            int tokenLifespan = settings["OAuthTokenLifespan"].AsIntegerOrNull() ?? 10;

            //Enable Application Sign In Cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "OAuth",
                AuthenticationMode = AuthenticationMode.Passive,
                LoginPath          = new PathString("/" + settings["OAuthLoginPath"].Trim('/')),
                LogoutPath         = new PathString("/" + settings["OAuthLogoutPath"].Trim('/')),
                SlidingExpiration  = false,
                ExpireTimeSpan     = new TimeSpan(0, tokenLifespan, 0)
            });


            //Setup Authorization Server
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath       = new PathString("/" + settings["OAuthAuthorizePath"].Trim('/')),
                AccessTokenExpireTimeSpan   = new TimeSpan(0, tokenLifespan, 0),
                TokenEndpointPath           = new PathString("/" + settings["OAuthTokenPath"].Trim('/')),
                ApplicationCanDisplayErrors = false,
                AllowInsecureHttp           = AllowInsecureHttp(),

                //Authorization server provider which controls the lifecycle fo the Authorization Server
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientRedirectUri     = ValidateClientRedirectUri,
                    OnValidateClientAuthentication  = ValidateClientAuthentication,
                    OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
                    OnGrantClientCredentials        = GrantClientCredentials,
                },

                //Authorization code provider who creates and receives authorization code
                AuthorizationCodeProvider = new AuthenticationTokenProvider
                {
                    OnCreate  = CreateAuthenticationCode,
                    OnReceive = ReceiveAuthenticationCode,
                },

                //Refresh token provider which creates and receives refresh token
                RefreshTokenProvider = new AuthenticationTokenProvider
                {
                    OnCreate  = CreateRefreshToken,
                    OnReceive = ReceiveRefreshToken
                }
            });

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
예제 #26
0
        /// <summary>
        /// Gets the keep alive URL.
        /// </summary>
        /// <returns></returns>
        private static string GetKeepAliveUrl()
        {
            var keepAliveUrl = GlobalAttributesCache.Value("KeepAliveUrl");

            if (string.IsNullOrWhiteSpace(keepAliveUrl))
            {
                keepAliveUrl = GlobalAttributesCache.Value("InternalApplicationRoot") ?? string.Empty;
                keepAliveUrl = keepAliveUrl.EnsureTrailingForwardslash() + "KeepAlive.aspx";
            }

            return(keepAliveUrl);
        }
예제 #27
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var qry         = GetQuery().AsNoTracking();
            var batchRowQry = qry.Select(b => new BatchRow
            {
                Id = b.Id,
                BatchStartDateTime = b.BatchStartDateTime.Value,
                Name = b.Name,
                AccountingSystemCode = b.AccountingSystemCode,
                TransactionCount     = b.Transactions.Count(),
                TransactionAmount    = b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M,
                ControlAmount        = b.ControlAmount,
                CampusName           = b.Campus != null ? b.Campus.Name : "",
                Status             = b.Status,
                UnMatchedTxns      = b.Transactions.Any(t => !t.AuthorizedPersonAliasId.HasValue),
                BatchNote          = b.Note,
                AccountSummaryList = b.Transactions
                                     .SelectMany(t => t.TransactionDetails)
                                     .GroupBy(d => d.AccountId)
                                     .Select(s => new BatchAccountSummary
                {
                    AccountId    = s.Key,
                    AccountOrder = s.Max(d => d.Account.Order),
                    AccountName  = s.Max(d => d.Account.Name),
                    Amount       = s.Sum(d => (decimal?)d.Amount) ?? 0.0M
                })
                                     .OrderBy(s => s.AccountOrder)
                                     .ToList()
            });

            gBatchList.SetLinqDataSource(batchRowQry.AsNoTracking());
            gBatchList.EntityTypeId = EntityTypeCache.Read <Rock.Model.FinancialBatch>().Id;
            gBatchList.DataBind();

            RegisterJavaScriptForGridActions();

            var qryTransactionDetails = qry.SelectMany(a => a.Transactions).SelectMany(a => a.TransactionDetails);
            var accountSummaryQry     = qryTransactionDetails.GroupBy(a => a.Account).Select(a => new
            {
                a.Key.Name,
                a.Key.Order,
                TotalAmount = (decimal?)a.Sum(d => d.Amount)
            }).OrderBy(a => a.Order);

            var    summaryList      = accountSummaryQry.ToList();
            var    grandTotalAmount = (summaryList.Count > 0) ? summaryList.Sum(a => a.TotalAmount ?? 0) : 0;
            string currencyFormat   = GlobalAttributesCache.Value("CurrencySymbol") + "{0:n}";

            lGrandTotal.Text             = string.Format(currencyFormat, grandTotalAmount);
            rptAccountSummary.DataSource = summaryList.Select(a => new { a.Name, TotalAmount = string.Format(currencyFormat, a.TotalAmount) }).ToList();
            rptAccountSummary.DataBind();
        }
예제 #28
0
        private static void InitializeLavaEngines()
        {
            // Register the RockLiquid Engine (pre-v13).
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var engineOptions = new LavaEngineConfigurationOptions();

                var rockLiquidEngine = new RockLiquidEngine();

                rockLiquidEngine.Initialize(engineOptions);

                return(rockLiquidEngine);
            });

            // Register the DotLiquid Engine.
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var defaultEnabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands").SplitDelimitedValues(",").ToList();

                var engineOptions = new LavaEngineConfigurationOptions
                {
                    FileSystem             = new WebsiteLavaFileSystem(),
                    CacheService           = new WebsiteLavaTemplateCacheService(),
                    DefaultEnabledCommands = defaultEnabledLavaCommands
                };

                var dotLiquidEngine = new DotLiquidEngine();

                dotLiquidEngine.Initialize(engineOptions);

                return(dotLiquidEngine);
            });

            // Register the Fluid Engine.
            LavaService.RegisterEngine((engineServiceType, options) =>
            {
                var defaultEnabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands").SplitDelimitedValues(",").ToList();

                var engineOptions = new LavaEngineConfigurationOptions
                {
                    FileSystem             = new WebsiteLavaFileSystem(),
                    CacheService           = new WebsiteLavaTemplateCacheService(),
                    DefaultEnabledCommands = defaultEnabledLavaCommands
                };

                var fluidEngine = new FluidEngine();

                fluidEngine.Initialize(engineOptions);

                return(fluidEngine);
            });
        }
예제 #29
0
        /// <summary>
        /// Saves all changes made in this context to the underlying database.  The
        /// default pre and post processing can also optionally be disabled.  This
        /// would disable audit records being created, workflows being triggered, and
        /// any PreSaveChanges() methods being called for changed entities.
        /// </summary>
        /// <param name="disablePrePostProcessing">if set to <c>true</c> disables
        /// the Pre and Post processing from being run. This should only be disabled
        /// when updating a large number of records at a time (e.g. importing records).</param>
        /// <returns></returns>
        public int SaveChanges(bool disablePrePostProcessing)
        {
            // Pre and Post processing has been disabled, just call the base
            // SaveChanges() method and return
            if (disablePrePostProcessing)
            {
                return(base.SaveChanges());
            }

            int result = 0;

            SaveErrorMessages = new List <string>();

            // Try to get the current person alias and id
            PersonAlias personAlias = GetCurrentPersonAlias();

            bool enableAuditing = GlobalAttributesCache.Value("EnableAuditing").AsBoolean();

            // Evaluate the current context for items that have changes
            var updatedItems = RockPreSave(this, personAlias, enableAuditing);

            // If update was not cancelled by triggered workflow
            if (updatedItems != null)
            {
                try
                {
                    // Save the context changes
                    result = base.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    var validationErrors = new List <string>();
                    foreach (var error in ex.EntityValidationErrors)
                    {
                        foreach (var prop in error.ValidationErrors)
                        {
                            validationErrors.Add(string.Format("{0} ({1}): {2}", error.Entry.Entity.GetType().Name, prop.PropertyName, prop.ErrorMessage));
                        }
                    }

                    throw new SystemException("Entity Validation Error: " + validationErrors.AsDelimited(";"), ex);
                }

                // If any items changed process audit and triggers
                if (updatedItems.Any())
                {
                    RockPostSave(updatedItems, personAlias, enableAuditing);
                }
            }

            return(result);
        }
예제 #30
0
        private bool AllowInsecureHttp()
        {
            bool allowInsecure = false;

            var settings = GlobalAttributesCache.Value("OAuthSettings").AsDictionary();

            if (settings["OAuthRequireSsl"] != null)
            {
                allowInsecure = !settings["OAuthRequireSsl"].AsBoolean();
            }

            return(allowInsecure);
        }