Beispiel #1
0
        /// <summary>
        /// Gets the specified <see cref="Rock.Model.EntityType"/> by the object type. If a match is not found, it can optionally create a new <see cref="Rock.Model.EntityType"/> for the object.
        /// </summary>
        /// <param name="type">The <see cref="System.Type"/> to search for.</param>
        /// <param name="createIfNotFound">A <see cref="System.Boolean"/> value that indicates if a new <see cref="Rock.Model.EntityType"/> should be created if a match is not found. This value
        /// will be <c>true</c> if a new <see cref="Rock.Model.EntityType"/> should be created if there is not a match; otherwise <c>false</c>/</param>
        /// <param name="personAlias">A <see cref="Rock.Model.PersonAlias"/> representing the alias of the <see cref="Rock.Model.Person"/> who is searching for and possibly creating a new EntityType.  This value can be
        /// null if the logged in person is not known (i.e. an anonymous user).</param>
        /// <returns>A <see cref="Rock.Model.EntityType"/> matching the provided type. If a match is not found and createIfNotFound is false this value will be null.</returns>
        public EntityType Get(Type type, bool createIfNotFound, PersonAlias personAlias)
        {
            var entityType = Get(type.FullName);

            if (entityType != null)
            {
                return(entityType);
            }

            if (createIfNotFound)
            {
                // Create a new context so type can be saved independing of current context
                using (var rockContext = new RockContext())
                {
                    var entityTypeService = new EntityTypeService(rockContext);
                    entityType              = new EntityType();
                    entityType.Name         = type.FullName;
                    entityType.FriendlyName = type.Name.SplitCase();
                    entityType.AssemblyName = type.AssemblyQualifiedName;
                    entityTypeService.Add(entityType);
                    rockContext.SaveChanges();
                }

                // Read type using current context
                return(this.Get(entityType.Id));
            }

            return(null);
        }
Beispiel #2
0
        /// <summary>
        /// Gets the by public key.
        /// </summary>
        /// <param name="publicKey">The public key.</param>
        /// <returns></returns>
        public virtual PersonAlias GetByAliasPublicKey(string publicKey)
        {
            try
            {
                string[] idParts = publicKey.Split('>');
                if (idParts.Length == 2)
                {
                    int  id   = Int32.Parse(idParts[0]);
                    Guid guid = new Guid(idParts[1]);

                    PersonAlias personAlias = GetByAliasId(id);

                    if (personAlias != null && personAlias.AliasPersonGuid.CompareTo(guid) == 0)
                    {
                        return(personAlias);
                    }
                }

                return(null);
            }
            catch
            {
                return(null);
            }
        }
        /// <summary>
        /// Gets the PersonAlias the by AliasPersonId
        /// </summary>
        /// <param name="aliasPersonId">The alias person identifier.</param>
        /// <returns></returns>
        public virtual PersonAlias GetByAliasId(int aliasPersonId)
        {
            var personAlias = Queryable("Person").Where(a => a.AliasPersonId == aliasPersonId).FirstOrDefault();

            if (personAlias != null)
            {
                return(personAlias);
            }
            else
            {
                // If the personId is valid, there should be a personAlias with the AliasPersonID equal
                // to that personId.  If there isn't for some reason, create it now.
                var person = new PersonService((RockContext)this.Context).Get(aliasPersonId);
                if (person != null)
                {
                    personAlias                 = new PersonAlias();
                    personAlias.Guid            = Guid.NewGuid();
                    personAlias.AliasPersonId   = person.Id;
                    personAlias.AliasPersonGuid = person.Guid;
                    personAlias.PersonId        = person.Id;

                    // Use a different context so calling method's changes are not yet saved
                    var rockContext = new RockContext();
                    new PersonAliasService(rockContext).Add(personAlias);
                    rockContext.SaveChanges();

                    return(Get(personAlias.Id));
                }
            }

            return(null);
        }
Beispiel #4
0
        /// <summary>
        /// Logs new <see cref="Rock.Model.ExceptionLog" /> entities.  This method serves as an interface to asynchronously log exceptions.
        /// </summary>
        /// <param name="ex">A <see cref="System.Exception" /> object to log.</param>
        /// <param name="request">The <see cref="T:System.Net.HttpRequestMessage" /></param>
        /// <param name="personAlias">The person alias.</param>
        public static void LogApiException(Exception ex, HttpRequestMessage request, PersonAlias personAlias = null)
        {
            // Populate the initial ExceptionLog with data from HttpContext. Must capture initial
            // HttpContext details before spinning off new thread, because the current context will
            // not be the same within the context of the new thread.
            var exceptionLog = PopulateExceptionLog(ex, request, personAlias);

            // Spin off a new thread to handle the real logging work so the UI is not blocked whilst
            // recursively writing to the database.
            Task.Run(() => LogExceptions(ex, exceptionLog, true));
        }
Beispiel #5
0
        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <param name="personAlias">The person alias.</param>
        /// <param name="personAliasId">The person alias identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="blankValue">The blank value.</param>
        /// <returns></returns>
        private static string GetPersonAliasValue(PersonAlias personAlias, int?personAliasId, RockContext rockContext, string blankValue)
        {
            Person person = null;

            if (personAlias != null && personAlias.Person != null)
            {
                person = personAlias.Person;
            }
            else if (personAliasId.HasValue)
            {
                person = new PersonAliasService(rockContext).GetPerson(personAliasId.Value);
            }

            return(person != null?string.Format("{0} [{1}]", person.FullName, person.Id) : blankValue);
        }
Beispiel #6
0
        /// <summary>
        /// Creates and stores a new PersonToken for a person using the specified ExpireDateTime, UsageLimit, and Page
        /// Returns the encrypted URLEncoded Token which can be used as a rckipid
        /// </summary>
        /// <param name="personAlias">The person alias.</param>
        /// <param name="expireDateTime">The expire date time.</param>
        /// <param name="usageLimit">The usage limit.</param>
        /// <param name="pageId">The page identifier.</param>
        /// <returns></returns>
        public static string CreateNew(PersonAlias personAlias, DateTime?expireDateTime, int?usageLimit, int?pageId)
        {
            if (personAlias == null)
            {
                return(null);
            }

            using (var rockContext = new RockContext())
            {
                var token = Rock.Security.Encryption.GenerateUniqueToken();

                PersonToken personToken = new PersonToken();
                personToken.PersonAliasId = personAlias.Id;
                personToken.Token         = token;
                if (expireDateTime != null)
                {
                    personToken.ExpireDateTime = expireDateTime;
                }
                else
                {
                    int?tokenExpireMinutes = GlobalAttributesCache.Get().GetValue("core.PersonTokenExpireMinutes").AsIntegerOrNull();
                    if (tokenExpireMinutes.HasValue)
                    {
                        personToken.ExpireDateTime = RockDateTime.Now.AddMinutes(tokenExpireMinutes.Value);
                    }
                    else
                    {
                        personToken.ExpireDateTime = null;
                    }
                }

                personToken.TimesUsed  = 0;
                personToken.UsageLimit = usageLimit ?? GlobalAttributesCache.Get().GetValue("core.PersonTokenUsageLimit").AsIntegerOrNull();

                personToken.PageId = pageId;

                var personTokenService = new PersonTokenService(rockContext);
                personTokenService.Add(personToken);
                rockContext.SaveChanges(true);

                var encryptedToken = Rock.Security.Encryption.EncryptString(token);

                // do a Replace('%', '!') after we UrlEncode it (to make it more safely embeddable in HTML and cross browser compatible)
                return(System.Web.HttpUtility.UrlEncode(encryptedToken).Replace('%', '!'));
            }
        }
Beispiel #7
0
        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.AppendFormat("{0} ", this.AllowOrDeny == "A" ? "Allow" : "Deny");

            if (SpecialRole != Model.SpecialRole.None)
            {
                sb.AppendFormat("{0} ", SpecialRole.ToStringSafe().SplitCase());
            }
            else if (PersonAlias != null)
            {
                sb.AppendFormat("{0} ", PersonAlias.ToStringSafe());
            }
            else if (Group != null)
            {
                sb.AppendFormat("{0} ", Group.ToStringSafe());
            }

            sb.AppendFormat("{0} Access", Action);

            return(sb.ToString());
        }
Beispiel #8
0
 /// <summary>
 /// Evaluates the person alias change.
 /// </summary>
 /// <param name="historyMessages">The history messages.</param>
 /// <param name="propertyName">Name of the property.</param>
 /// <param name="oldPersonAliasId">The old person alias identifier.</param>
 /// <param name="newPersonAlias">The new person alias.</param>
 /// <param name="newPersonAliasId">The new person alias identifier.</param>
 /// <param name="rockContext">The rock context.</param>
 public static void EvaluateChange(List <string> historyMessages, string propertyName, int?oldPersonAliasId, PersonAlias newPersonAlias, int?newPersonAliasId, RockContext rockContext)
 {
     EvaluateChange(historyMessages, propertyName, oldPersonAliasId, newPersonAlias, newPersonAliasId, rockContext, string.Empty, false);
 }
        /// <summary>
        /// Populates the <see cref="Rock.Model.ExceptionLog" /> entity with the exception data.
        /// </summary>
        /// <param name="ex">The <see cref="System.Exception" /> to log.</param>
        /// <param name="context">The <see cref="System.Web.HttpContext" />.</param>
        /// <param name="pageId">An <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Page" /> where the exception occurred.
        /// This value is nullable.</param>
        /// <param name="siteId">An <see cref="System.Int32" /> containing the Id the <see cref="Rock.Model.Site" /> where the exception occurred.
        /// This value is nullable.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <returns></returns>
        private static ExceptionLog PopulateExceptionLog(Exception ex, HttpContext context, int?pageId, int?siteId, PersonAlias personAlias)
        {
            int?personAliasId = null;

            if (personAlias != null)
            {
                personAliasId = personAlias.Id;
            }

            var exceptionLog = new ExceptionLog
            {
                SiteId            = siteId,
                PageId            = pageId,
                HasInnerException = ex.InnerException != null,
                ExceptionType     = ex.GetType().ToString(),
                Description       = ex.Message,
                Source            = ex.Source,
                StackTrace        = ex.StackTrace,
                Guid = Guid.NewGuid(),
                CreatedByPersonAliasId  = personAliasId,
                ModifiedByPersonAliasId = personAliasId,
                CreatedDateTime         = RockDateTime.Now,
                ModifiedDateTime        = RockDateTime.Now
            };

            try
            {
                // If current HttpContext is null, return early.
                if (context == null)
                {
                    return(exceptionLog);
                }

                // If current HttpContext is available, populate its information as well.
                var request = context.Request;

                StringBuilder cookies    = new StringBuilder();
                var           cookieList = request.Cookies;

                if (cookieList.Count > 0)
                {
                    cookies.Append("<table class=\"cookies exception-table\">");

                    foreach (string cookie in cookieList)
                    {
                        var httpCookie = cookieList[cookie];
                        if (httpCookie != null)
                        {
                            cookies.Append("<tr><td><b>" + cookie + "</b></td><td>" + httpCookie.Value + "</td></tr>");
                        }
                    }

                    cookies.Append("</table>");
                }

                StringBuilder formItems = new StringBuilder();
                var           formList  = request.Form;

                if (formList.Count > 0)
                {
                    formItems.Append("<table class=\"form-items exception-table\">");

                    foreach (string formItem in formList)
                    {
                        formItems.Append("<tr><td><b>" + formItem + "</b></td><td>" + formList[formItem] + "</td></tr>");
                    }

                    formItems.Append("</table>");
                }

                StringBuilder serverVars    = new StringBuilder();
                var           serverVarList = request.ServerVariables;

                if (serverVarList.Count > 0)
                {
                    serverVars.Append("<table class=\"server-variables exception-table\">");

                    foreach (string serverVar in serverVarList)
                    {
                        serverVars.Append("<tr><td><b>" + serverVar + "</b></td><td>" + serverVarList[serverVar] + "</td></tr>");
                    }

                    serverVars.Append("</table>");
                }

                exceptionLog.Cookies         = cookies.ToString();
                exceptionLog.StatusCode      = context.Response.StatusCode.ToString();
                exceptionLog.PageUrl         = request.Url.ToString();
                exceptionLog.ServerVariables = serverVars.ToString();
                exceptionLog.QueryString     = request.Url.Query;
                exceptionLog.Form            = formItems.ToString();
            }
            catch {
                // Intentionally do nothing
            }

            return(exceptionLog);
        }
Beispiel #10
0
        /// <summary>
        /// Populates the <see cref="Rock.Model.ExceptionLog" /> entity with the exception data.
        /// </summary>
        /// <param name="ex">The <see cref="System.Exception" /> to log.</param>
        /// <param name="context">The <see cref="System.Web.HttpContext" />.</param>
        /// <param name="pageId">An <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Page" /> where the exception occurred.
        /// This value is nullable.</param>
        /// <param name="siteId">An <see cref="System.Int32" /> containing the Id the <see cref="Rock.Model.Site" /> where the exception occurred.
        /// This value is nullable.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <returns></returns>
        private static ExceptionLog PopulateExceptionLog(Exception ex, HttpContext context, int?pageId, int?siteId, PersonAlias personAlias)
        {
            int?personAliasId = null;

            if (personAlias != null)
            {
                personAliasId = personAlias.Id;
            }

            string exceptionMessage = ex.Message;

            if (ex is System.Data.SqlClient.SqlException)
            {
                var sqlEx        = ex as System.Data.SqlClient.SqlException;
                var sqlErrorList = sqlEx.Errors.OfType <System.Data.SqlClient.SqlError>().ToList().Select(a => string.Format("{0}: Line {1}", a.Procedure, a.LineNumber));
                if (sqlErrorList.Any())
                {
                    exceptionMessage += string.Format("[{0}]", sqlErrorList.ToList().AsDelimited(", "));
                }
            }

            var exceptionLog = new ExceptionLog
            {
                SiteId            = siteId,
                PageId            = pageId,
                HasInnerException = ex.InnerException != null,
                ExceptionType     = ex.GetType().ToString(),
                Description       = exceptionMessage,
                Source            = ex.Source,
                StackTrace        = ex.StackTrace,
                Guid = Guid.NewGuid(),
                CreatedByPersonAliasId            = personAliasId,
                ModifiedByPersonAliasId           = personAliasId,
                CreatedDateTime                   = RockDateTime.Now,
                ModifiedDateTime                  = RockDateTime.Now,
                ModifiedAuditValuesAlreadyUpdated = true
            };

            if (exceptionLog.StackTrace == null)
            {
                try
                {
                    // if the Exception didn't include a StackTrace, manually grab it
                    var stackTrace = new System.Diagnostics.StackTrace(2);
                    exceptionLog.StackTrace = stackTrace.ToString();
                }
                catch
                {
                    // ignore
                }
            }

            try
            {
                ex.Data.Add("ExceptionLogGuid", exceptionLog.Guid);
            }
            catch
            {
                // ignore
            }

            try
            {
                // If current HttpContext is null, return early.
                if (context == null)
                {
                    return(exceptionLog);
                }

                // If current HttpContext is available, populate its information as well.
                var request = context.Request;

                StringBuilder cookies    = new StringBuilder();
                var           cookieList = request.Cookies;

                if (cookieList.Count > 0)
                {
                    cookies.Append("<table class=\"cookies exception-table\">");

                    foreach (string cookie in cookieList)
                    {
                        var httpCookie = cookieList[cookie];
                        if (httpCookie != null)
                        {
                            cookies.Append("<tr><td><b>" + cookie + "</b></td><td>" + httpCookie.Value.EncodeHtml() + "</td></tr>");
                        }
                    }

                    cookies.Append("</table>");
                }

                StringBuilder formItems = new StringBuilder();
                var           formList  = request.Form;

                if (formList.Count > 0)
                {
                    formItems.Append("<table class=\"form-items exception-table\">");
                    foreach (string formItem in formList)
                    {
                        if (formItem.IsNotNullOrWhiteSpace())
                        {
                            string formValue = formList[formItem].EncodeHtml();
                            string lc        = formItem.ToLower();
                            if (lc.Contains("nolog") ||
                                lc.Contains("creditcard") ||
                                lc.Contains("cc-number") ||
                                lc.Contains("cvv") ||
                                lc.Contains("ssn") ||
                                lc.Contains("accountnumber") ||
                                lc.Contains("account-number"))
                            {
                                formValue = "***obfuscated***";
                            }
                            formItems.Append("<tr><td><b>" + formItem + "</b></td><td>" + formValue + "</td></tr>");
                        }
                    }
                    formItems.Append("</table>");
                }

                StringBuilder serverVars    = new StringBuilder();
                var           serverVarList = request.ServerVariables;

                if (serverVarList.Count > 0)
                {
                    serverVars.Append("<table class=\"server-variables exception-table\">");

                    foreach (string serverVar in serverVarList)
                    {
                        string val = string.Empty;
                        try
                        {
                            // 'serverVarList[serverVar]' throws an exception if the value is empty, even if the key exists. Was not able to find a more elegant way to avoid an exception.
                            val = serverVarList[serverVar].ToStringSafe().EncodeHtml();
                        }
                        catch
                        {
                        }

                        serverVars.Append($"<tr><td><b>{serverVar}</b></td><td>{val}</td></tr>");
                    }

                    serverVars.Append("</table>");
                }

                exceptionLog.Cookies         = cookies.ToString();
                exceptionLog.StatusCode      = context.Response.StatusCode.ToString();
                exceptionLog.PageUrl         = request.Url.ToString();
                exceptionLog.ServerVariables = serverVars.ToString();
                exceptionLog.QueryString     = request.Url.Query;
                exceptionLog.Form            = formItems.ToString();
            }
            catch {
                // Intentionally do nothing
            }

            return(exceptionLog);
        }
Beispiel #11
0
 public GroupMember GetInverseRelationship(GroupMember groupMember, bool createGroup, PersonAlias personAlias)
 {
     return(GetInverseRelationship(groupMember, createGroup));
 }
Beispiel #12
0
        /// <summary>
        /// Populates the <see cref="Rock.Model.ExceptionLog" /> entity with the exception data.
        /// </summary>
        /// <param name="ex">The <see cref="System.Exception" /> to log.</param>
        /// <param name="context">The <see cref="System.Web.HttpContext" />.</param>
        /// <param name="pageId">An <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Page" /> where the exception occurred.
        /// This value is nullable.</param>
        /// <param name="siteId">An <see cref="System.Int32" /> containing the Id the <see cref="Rock.Model.Site" /> where the exception occurred.
        /// This value is nullable.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <returns></returns>
        private static ExceptionLog PopulateExceptionLog(Exception ex, HttpContext context, int?pageId, int?siteId, PersonAlias personAlias)
        {
            int?personAliasId = null;

            if (personAlias != null)
            {
                personAliasId = personAlias.Id;
            }

            string exceptionMessage = ex.Message;

            if (ex is System.Data.SqlClient.SqlException)
            {
                var sqlEx        = ex as System.Data.SqlClient.SqlException;
                var sqlErrorList = sqlEx.Errors.OfType <System.Data.SqlClient.SqlError>().ToList().Select(a => string.Format("{0}: Line {1}", a.Procedure, a.LineNumber));
                if (sqlErrorList.Any())
                {
                    exceptionMessage += string.Format("[{0}]", sqlErrorList.ToList().AsDelimited(", "));
                }
            }

            var exceptionLog = new ExceptionLog
            {
                SiteId            = siteId,
                PageId            = pageId,
                HasInnerException = ex.InnerException != null,
                ExceptionType     = ex.GetType().ToString(),
                Description       = exceptionMessage,
                Source            = ex.Source,
                StackTrace        = ex.StackTrace,
                Guid = Guid.NewGuid(),
                CreatedByPersonAliasId            = personAliasId,
                ModifiedByPersonAliasId           = personAliasId,
                CreatedDateTime                   = RockDateTime.Now,
                ModifiedDateTime                  = RockDateTime.Now,
                ModifiedAuditValuesAlreadyUpdated = true
            };

            if (exceptionLog.StackTrace == null)
            {
                try
                {
                    // if the Exception didn't include a StackTrace, manually grab it
                    var stackTrace = new System.Diagnostics.StackTrace(2);
                    exceptionLog.StackTrace = stackTrace.ToString();
                }
                catch
                {
                }
            }

            try
            {
                ex.Data.Add("ExceptionLogGuid", exceptionLog.Guid);
            }
            catch
            {
            }

            try
            {
                // If current HttpContext is null, return early.
                if (context == null)
                {
                    return(exceptionLog);
                }

                // If current HttpContext is available, populate its information as well.
                var request = context.Request;

                StringBuilder cookies    = new StringBuilder();
                var           cookieList = request.Cookies;

                if (cookieList.Count > 0)
                {
                    cookies.Append("<table class=\"cookies exception-table\">");

                    foreach (string cookie in cookieList)
                    {
                        var httpCookie = cookieList[cookie];
                        if (httpCookie != null)
                        {
                            cookies.Append("<tr><td><b>" + cookie + "</b></td><td>" + httpCookie.Value.EncodeHtml() + "</td></tr>");
                        }
                    }

                    cookies.Append("</table>");
                }

                StringBuilder serverVars = new StringBuilder();

                // 'serverVarList[serverVar]' throws an exception if the value is empty, even if the key exists,
                // so make a copy of the request server variables to help avoid that error
                var serverVarList       = new NameValueCollection(request.ServerVariables);
                var serverVarListString = serverVarList.ToString();

                var serverVarKeys = request.ServerVariables.AllKeys;

                if (serverVarList.Count > 0)
                {
                    serverVars.Append("<table class=\"server-variables exception-table\">");

                    foreach (string serverVar in serverVarList)
                    {
                        string val = string.Empty;
                        try
                        {
                            val = serverVarList[serverVar].ToStringSafe().EncodeHtml();
                        }
                        catch
                        {
                            // ignore
                        }

                        serverVars.Append($"<tr><td><b>{serverVar}</b></td><td>{val}</td></tr>");
                    }

                    serverVars.Append("</table>");
                }

                exceptionLog.Cookies         = cookies.ToString();
                exceptionLog.StatusCode      = context.Response.StatusCode.ToString();
                exceptionLog.PageUrl         = request.UrlProxySafe().ToString();
                exceptionLog.ServerVariables = serverVars.ToString();
                exceptionLog.QueryString     = request.UrlProxySafe().Query;

                /*
                 *   SK - 11/24/2021
                 *   We are commenting out below line as we have decided not to store form data from now on as it may contain sensative data.
                 *   exceptionLog.Form = formItems.ToString();
                 */
            }
            catch
            {
            }

            return(exceptionLog);
        }
Beispiel #13
0
 /// <summary>
 /// Creates and stores a new PersonToken for a person limited to a specific PageId
 /// Returns the encrypted URLEncoded Token which can be used as a rckipid
 /// </summary>
 /// <param name="personAlias">The person alias.</param>
 /// <param name="pageId">The page identifier.</param>
 /// <returns></returns>
 public static string CreateNew(PersonAlias personAlias, int pageId)
 {
     return(CreateNew(personAlias, null, null, pageId));
 }
Beispiel #14
0
 /// <summary>
 /// Creates and stores a new PersonToken for a person using the default ExpireDateTime and UsageLimit.
 /// Returns the encrypted URLEncoded Token which can be used as a rckipid.
 /// </summary>
 /// <param name="personAlias">The person alias.</param>
 /// <returns></returns>
 public static string CreateNew(PersonAlias personAlias)
 {
     return(CreateNew(personAlias, null, null, null));
 }
Beispiel #15
0
 /// <summary>
 /// Evaluates the change.
 /// </summary>
 /// <param name="historyMessages">The history messages.</param>
 /// <param name="propertyName">Name of the property.</param>
 /// <param name="oldPersonAliasId">The old person alias identifier.</param>
 /// <param name="newPersonAlias">The new person alias.</param>
 /// <param name="newPersonAliasId">The new person alias identifier.</param>
 /// <param name="rockContext">The rock context.</param>
 /// <param name="blankValue">The blank value.</param>
 /// <param name="isSensitive">if set to <c>true</c> [is sensitive].</param>
 public static void EvaluateChange(List <string> historyMessages, string propertyName, int?oldPersonAliasId, PersonAlias newPersonAlias, int?newPersonAliasId, RockContext rockContext, string blankValue, bool isSensitive)
 {
     if (!oldPersonAliasId.Equals(newPersonAliasId))
     {
         string oldStringValue = GetValue <PersonAlias>(null, oldPersonAliasId, rockContext, blankValue);
         string newStringValue = GetValue <PersonAlias>(newPersonAlias, newPersonAliasId, rockContext, blankValue);
         EvaluateChange(historyMessages, propertyName, oldStringValue, newStringValue, isSensitive);
     }
 }
Beispiel #16
0
 /// <summary>
 /// Gets the value.
 /// </summary>
 /// <param name="personAlias">The person alias.</param>
 /// <param name="personAliasId">The person alias identifier.</param>
 /// <param name="rockContext">The rock context.</param>
 /// <returns></returns>
 private static string GetPersonAliasValue(PersonAlias personAlias, int?personAliasId, RockContext rockContext)
 {
     return(GetPersonAliasValue(personAlias, personAliasId, rockContext, string.Empty));
 }
Beispiel #17
0
        /// <summary>
        /// Populates the <see cref="Rock.Model.ExceptionLog" /> entity with the exception data.
        /// </summary>
        /// <param name="ex">The <see cref="System.Exception" /> to log.</param>
        /// <param name="request">The <see cref="T:System.Net.HttpRequestMessage" />.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <returns></returns>
        private static ExceptionLog PopulateExceptionLog(Exception ex, HttpRequestMessage request, PersonAlias personAlias)
        {
            string exceptionMessage = ex.Message;

            if (ex is System.Data.SqlClient.SqlException)
            {
                var sqlEx        = ex as System.Data.SqlClient.SqlException;
                var sqlErrorList = sqlEx.Errors.OfType <System.Data.SqlClient.SqlError>().ToList().Select(a => string.Format("{0}: Line {1}", a.Procedure, a.LineNumber));
                if (sqlErrorList.Any())
                {
                    exceptionMessage += string.Format("[{0}]", sqlErrorList.ToList().AsDelimited(", "));
                }
            }

            var exceptionLog = new ExceptionLog
            {
                HasInnerException = ex.InnerException != null,
                ExceptionType     = ex.GetType().ToString(),
                Description       = exceptionMessage,
                Source            = ex.Source,
                StackTrace        = ex.StackTrace,
                Guid = Guid.NewGuid(),
                CreatedByPersonAliasId            = personAlias?.Id,
                ModifiedByPersonAliasId           = personAlias?.Id,
                CreatedDateTime                   = RockDateTime.Now,
                ModifiedDateTime                  = RockDateTime.Now,
                ModifiedAuditValuesAlreadyUpdated = true
            };

            if (exceptionLog.StackTrace == null)
            {
                try
                {
                    // if the Exception didn't include a StackTrace, manually grab it
                    var stackTrace = new System.Diagnostics.StackTrace(2);
                    exceptionLog.StackTrace = stackTrace.ToString();
                }
                catch { }
            }

            try
            {
                ex.Data.Add("ExceptionLogGuid", exceptionLog.Guid);
            }
            catch { }

            try
            {
                // If current HttpRequestMessage is null, return early.
                if (request == null)
                {
                    return(exceptionLog);
                }

                StringBuilder cookies    = new StringBuilder();
                var           cookieList = request.Headers.GetCookies();

                if (cookieList.Count > 0)
                {
                    cookies.Append("<table class=\"cookies exception-table\">");

                    foreach (var cookieHeaderValue in cookieList)
                    {
                        foreach (var cookie in cookieHeaderValue.Cookies)
                        {
                            cookies.Append("<tr><td><b>" + cookie.Name + "</b></td><td>" + cookie.Value.EncodeHtml() + "</td></tr>");
                        }
                    }

                    cookies.Append("</table>");
                }

                //
                // Check query string parameters for sensitive data.
                //
                string queryString     = null;
                var    queryCollection = request.RequestUri.ParseQueryString();
                if (queryCollection.Count > 0)
                {
                    var nvc = new NameValueCollection();
                    foreach (string qKey in queryCollection.Keys)
                    {
                        if (IsKeySensitive(qKey.ToLower()))
                        {
                            nvc.Add(qKey, "obfuscated");
                        }
                        else
                        {
                            nvc.Add(qKey, queryCollection[qKey]);
                        }
                    }

                    queryString = "?" + String.Join("&", nvc.AllKeys.Select(a => a.UrlEncode() + "=" + nvc[a].UrlEncode()));
                }

                exceptionLog.Cookies     = cookies.ToString();
                exceptionLog.PageUrl     = request.RequestUri.GetLeftPart(UriPartial.Path);
                exceptionLog.QueryString = queryString;
            }
            catch { }

            return(exceptionLog);
        }
        /// <summary>
        /// Populates the <see cref="Rock.Model.ExceptionLog" /> entity with the exception data.
        /// </summary>
        /// <param name="ex">The <see cref="System.Exception" /> to log.</param>
        /// <param name="context">The <see cref="System.Web.HttpContext" />.</param>
        /// <param name="pageId">An <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Page" /> where the exception occurred.
        /// This value is nullable.</param>
        /// <param name="siteId">An <see cref="System.Int32" /> containing the Id the <see cref="Rock.Model.Site" /> where the exception occurred.
        /// This value is nullable.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <returns></returns>
        private static ExceptionLog PopulateExceptionLog(Exception ex, HttpContext context, int?pageId, int?siteId, PersonAlias personAlias)
        {
            int?personAliasId = null;

            if (personAlias != null)
            {
                personAliasId = personAlias.Id;
            }

            string exceptionMessage = ex.Message;

            if (ex is System.Data.SqlClient.SqlException)
            {
                var sqlEx        = ex as System.Data.SqlClient.SqlException;
                var sqlErrorList = sqlEx.Errors.OfType <System.Data.SqlClient.SqlError>().ToList().Select(a => string.Format("{0}: Line {1}", a.Procedure, a.LineNumber));
                if (sqlErrorList.Any())
                {
                    exceptionMessage += string.Format("[{0}]", sqlErrorList.ToList().AsDelimited(", "));
                }
            }

            var exceptionLog = new ExceptionLog
            {
                SiteId            = siteId,
                PageId            = pageId,
                HasInnerException = ex.InnerException != null,
                ExceptionType     = ex.GetType().ToString(),
                Description       = exceptionMessage,
                Source            = ex.Source,
                StackTrace        = ex.StackTrace,
                Guid = Guid.NewGuid(),
                CreatedByPersonAliasId            = personAliasId,
                ModifiedByPersonAliasId           = personAliasId,
                CreatedDateTime                   = RockDateTime.Now,
                ModifiedDateTime                  = RockDateTime.Now,
                ModifiedAuditValuesAlreadyUpdated = true
            };

            try
            {
                ex.Data.Add("ExceptionLogGuid", exceptionLog.Guid);
            }
            catch
            {
                // ignore
            }

            try
            {
                // If current HttpContext is null, return early.
                if (context == null)
                {
                    return(exceptionLog);
                }

                // If current HttpContext is available, populate its information as well.
                var request = context.Request;

                StringBuilder cookies    = new StringBuilder();
                var           cookieList = request.Cookies;

                if (cookieList.Count > 0)
                {
                    cookies.Append("<table class=\"cookies exception-table\">");

                    foreach (string cookie in cookieList)
                    {
                        var httpCookie = cookieList[cookie];
                        if (httpCookie != null)
                        {
                            cookies.Append("<tr><td><b>" + cookie + "</b></td><td>" + httpCookie.Value.EncodeHtml() + "</td></tr>");
                        }
                    }

                    cookies.Append("</table>");
                }

                StringBuilder formItems = new StringBuilder();
                var           formList  = request.Form;

                if (formList.Count > 0)
                {
                    formItems.Append("<table class=\"form-items exception-table\">");

                    foreach (string formItem in formList)
                    {
                        formItems.Append("<tr><td><b>" + formItem + "</b></td><td>" + formList[formItem].EncodeHtml() + "</td></tr>");
                    }

                    formItems.Append("</table>");
                }

                StringBuilder serverVars    = new StringBuilder();
                var           serverVarList = request.ServerVariables;

                if (serverVarList.Count > 0)
                {
                    serverVars.Append("<table class=\"server-variables exception-table\">");

                    foreach (string serverVar in serverVarList)
                    {
                        serverVars.Append("<tr><td><b>" + serverVar + "</b></td><td>" + serverVarList[serverVar].EncodeHtml() + "</td></tr>");
                    }

                    serverVars.Append("</table>");
                }

                exceptionLog.Cookies         = cookies.ToString();
                exceptionLog.StatusCode      = context.Response.StatusCode.ToString();
                exceptionLog.PageUrl         = request.Url.ToString();
                exceptionLog.ServerVariables = serverVars.ToString();
                exceptionLog.QueryString     = request.Url.Query;
                exceptionLog.Form            = formItems.ToString();
            }
            catch {
                // Intentionally do nothing
            }

            return(exceptionLog);
        }
Beispiel #19
0
        /// <summary>
        /// Gets the inverse relationship.
        /// Returns the <see cref="Rock.Model.GroupMember" /> who has an inverse relationship to the provided <see cref="Rock.Model.GroupMember" />.
        /// </summary>
        /// <param name="groupMember">A <see cref="Rock.Model.GroupMember" /> representing the person to find the inverse relationship for.</param>
        /// <param name="createGroup">A <see cref="System.Boolean"/> flag indicating if a new <see cref="Rock.Model.Group"/> can be created
        /// for the person with the inverse relationship. </param>
        /// <param name="personAlias">The alias of the <see cref="Rock.Model.Person"/> who has the inverse relationship.</param>
        /// <returns>
        /// A <see cref="Rock.Model.GroupMember"/> representing the <see cref="Rock.Model.Person"/> with the inverse relationship.
        /// </returns>
        /// <remarks>
        /// In Rock, examples of inverse relationships include: Parent/Child, Can Check In/Check in By, Sibling/Sibling, Grandparent/Grandchild, etc.
        /// </remarks>
        public GroupMember GetInverseRelationship(GroupMember groupMember, bool createGroup, PersonAlias personAlias)
        {
            var groupRole = groupMember.GroupRole;

            if (groupRole == null)
            {
                groupRole = Queryable()
                            .Where(m => m.Id == groupMember.Id)
                            .Select(m => m.GroupRole)
                            .FirstOrDefault();
            }

            if (groupRole != null)
            {
                if (groupRole.Attributes == null)
                {
                    groupRole.LoadAttributes();
                }

                if (groupRole.Attributes.ContainsKey("InverseRelationship"))
                {
                    Guid ownerRoleGuid = new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER);

                    var memberInfo = Queryable()
                                     .Where(m =>
                                            m.GroupId == groupMember.GroupId &&
                                            m.GroupRole.Guid.Equals(ownerRoleGuid))
                                     .Select(m => new
                    {
                        PersonId = m.PersonId,
                        RoleId   = m.GroupRoleId
                    })
                                     .FirstOrDefault();

                    int?ownerPersonId = null;
                    int?ownerRoleId   = null;

                    if (memberInfo != null)
                    {
                        ownerPersonId = memberInfo.PersonId;
                        ownerRoleId   = memberInfo.RoleId;
                    }

                    if (ownerPersonId.HasValue && ownerRoleId.HasValue)
                    {
                        // Find related person's group
                        var inverseGroup = Queryable()
                                           .Where(m =>
                                                  m.PersonId == groupMember.PersonId &&
                                                  m.Group.GroupTypeId == groupRole.GroupTypeId &&
                                                  m.GroupRole.Guid.Equals(ownerRoleGuid))
                                           .Select(m => m.Group)
                                           .FirstOrDefault();

                        if (inverseGroup == null && createGroup)
                        {
                            var ownerGroupMember = new GroupMember();
                            ownerGroupMember.PersonId    = groupMember.PersonId;
                            ownerGroupMember.GroupRoleId = ownerRoleId.Value;

                            inverseGroup             = new Group();
                            inverseGroup.Name        = groupRole.GroupType.Name;
                            inverseGroup.GroupTypeId = groupRole.GroupTypeId.Value;
                            inverseGroup.Members.Add(ownerGroupMember);
                        }

                        if (inverseGroup != null)
                        {
                            Guid inverseRoleGuid = Guid.Empty;
                            if (Guid.TryParse(groupRole.GetAttributeValue("InverseRelationship"), out inverseRoleGuid))
                            {
                                var inverseGroupMember = Queryable()
                                                         .Where(m =>
                                                                m.PersonId == ownerPersonId &&
                                                                m.GroupId == inverseGroup.Id &&
                                                                m.GroupRole.Guid.Equals(inverseRoleGuid))
                                                         .FirstOrDefault();

                                if (inverseGroupMember == null)
                                {
                                    var inverseRole = new GroupTypeRoleService((RockContext)Context).Get(inverseRoleGuid);
                                    if (inverseRole != null)
                                    {
                                        inverseGroupMember             = new GroupMember();
                                        inverseGroupMember.PersonId    = ownerPersonId.Value;
                                        inverseGroupMember.Group       = inverseGroup;
                                        inverseGroupMember.GroupRoleId = inverseRole.Id;
                                        Add(inverseGroupMember);
                                    }
                                }

                                return(inverseGroupMember);
                            }
                        }
                    }
                }
            }

            return(null);
        }