Beispiel #1
0
        public void Application_OnError(Object sender , EventArgs e)
        {
            //HttpApplication application = (HttpApplication)sender;
            //HttpContext context = application.Context;
            ////if (context.Server.GetLastError().GetBaseException() is MyException)
            //{
            //    //MyException ex = (MyException) context.Server.GetLastError().GetBaseException();
            //    context.Response.Write("<html><body style=\"font-size:14px;\">");
            //    context.Response.Write("Error:<br />");
            //    context.Response.Write("<textarea name=\"errormessage\" style=\"width:80%; height:200px; word-break:break-all\">");
            //    context.Response.Write(System.Web.HttpUtility.HtmlEncode(context.Server.GetLastError().ToString()));
            //    context.Response.Write("</textarea>");
            //    context.Response.Write("</body></html>");
            //    context.Response.End();
            //}
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;

            CSException csException = context.Server.GetLastError() as CSException;

            if (csException == null)
                csException = context.Server.GetLastError().GetBaseException() as CSException;

            try
            {
                if (csException != null)
                {
                    switch (csException.ExceptionType)
                    {
                        case CSExceptionType.UserInvalidCredentials:
                        case CSExceptionType.AccessDenied:
                        case CSExceptionType.AdministrationAccessDenied:
                        case CSExceptionType.ModerateAccessDenied:
                        case CSExceptionType.PostDeleteAccessDenied:
                        case CSExceptionType.PostProblem:
                        case CSExceptionType.UserAccountBanned:
                        case CSExceptionType.ResourceNotFound:
                        case CSExceptionType.UserUnknownLoginError:
                        case CSExceptionType.SectionNotFound:
                            csException.Log();
                            break;
                    }
                }
                else
                {
                    Exception ex = context.Server.GetLastError();
                    if (ex.InnerException != null)
                        ex = ex.InnerException;

                    csException = new CSException(CSExceptionType.UnknownError, ex.Message, context.Server.GetLastError());

                    System.Data.SqlClient.SqlException sqlEx = ex as System.Data.SqlClient.SqlException;
                    if (sqlEx == null || sqlEx.Number != -2) //don't log time outs
                        csException.Log();
                }
            }
            catch { } //not much to do here, but we want to prevent infinite looping with our error handles

            CSEvents.CSException(csException);
        }
Beispiel #2
0
 private static void RedirectToMessage(HttpContext context, CSException exception)
 {
     if ((exception.InnerException != null) && ( exception.InnerException is CSException))
     {
         CSException inner = (CSException) exception.InnerException;
     }
     context.Response.Redirect(Globals.GetSiteUrls().Message( exception.ExceptionType ), true);
 }
Beispiel #3
0
        private void csa_CSException(CSException csEx, CSEventArgs e)
        {
            CSContext csContext = CSContext.Current;

            if (csEx.ExceptionType != CSExceptionType.UnknownError && csContext.IsWebRequest)
            {
                RedirectToMessage(csContext.Context, csEx);
            }
        }
Beispiel #4
0
        public static void Write(HttpContext context, CSException csException, string filter, string errorFile)
        {
            CSConfiguration csConfig = CSConfiguration.GetConfig();
            string defaultLanguage = csConfig.DefaultLanguage;

            string path = "~/Languages/{0}/errors/{1}";
            StreamReader reader = new StreamReader( context.Server.MapPath(string.Format(path,defaultLanguage,errorFile)) );
            string html = reader.ReadToEnd();
            reader.Close();

            if(filter != null || filter.Trim().Length > 0)
            html = html.Replace(filter, csException.Message);

            context.Response.Write(html);
            context.Response.End();
        }
Beispiel #5
0
 public static void CSException(CSException csEx)
 {
     CSApplication.Instance().ExecuteCSExcetion(csEx);
 }
Beispiel #6
0
        public static string EmoticonTransforms(string formattedPost)
        {
            // remove some overhead if this is turned off
            if (!CSContext.Current.SiteSettings.EnableEmoticons)
                return formattedPost;

            try {
                // Load the emoticon transform table
                //
                ArrayList emoticonTxTable = Smilies.GetSmilies();

                const string imgFormat = "<img src=\"{0}{1}\" alt=\"{2}\" />";

                // EAD 6/27/2004: Changed to loop through twice.
                // Once for brackets first, so to capture the Party emoticon
                // (special emoticons that REQUIRE brackets), so not to replace
                // with other non-bracket icons. Less efficient yes, but captures
                // all emoticons properly.
                //
                string smileyPattern	= "";
                string replacePattern	= "";
                RegexOptions options	= RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline ;
                string forumHomePath = Globals.GetSiteUrls().Emoticon;

                foreach ( Smiley smiley in emoticonTxTable ) {
                    smileyPattern	= string.Format(@"\[{0}\]", Regex.Escape(smiley.SmileyCode) );
                    replacePattern	= string.Format(imgFormat, forumHomePath, smiley.SmileyUrl, smiley.SmileyText + " [[SmileyCode]]");

                    formattedPost = Regex.Replace( formattedPost, smileyPattern, replacePattern, options );

                    if ( smiley.IsSafeWithoutBrackets() )
                    {
                        formattedPost = Regex.Replace( formattedPost, Regex.Escape(smiley.SmileyCode),
                                replacePattern,
                                options );
                    }

                    // If the smiley code contains a < or >, check to see if it was HtmlEncoded in the body
                    if(smiley.SmileyCode.IndexOfAny( new char[] { '<', '>', '&' }) != -1)
                    {
                        try
                        {
                            smileyPattern	= string.Format(@"\[{0}\]", Regex.Escape(HttpContext.Current.Server.HtmlEncode(smiley.SmileyCode)) );
                            formattedPost = Regex.Replace( formattedPost, smileyPattern, replacePattern, options );

                            if(smiley.IsSafeWithoutBrackets())
                            {
                                formattedPost = Regex.Replace( formattedPost, Regex.Escape(HttpContext.Current.Server.HtmlEncode(smiley.SmileyCode)),
                                    replacePattern,
                                    options );
                            }
                        }
                        catch(NullReferenceException) { }	// If we are outside of a web-context, referencing HttpContext.Current could throw a null ref.
                    }

                    // Finally, look for [SmileyCode] to place the smiley's code back in there (mostly for in the alt tags)
                    // If the smiley was actually there, it could end up getting mistaken for another smiley... ie, [:)]
                    // would get an alt tag of "Smile [:)]", it'll then search for the non-bracket version, and see :) and treat it as another instance
                    formattedPost = Regex.Replace( formattedPost, @"\[SmileyCode\]", smiley.SmileyCode, options );

                }

                return formattedPost;
            } catch( Exception e ) {
                CSException ex = new CSException( CSExceptionType.UnknownError, "Could not transform smilies in the post.", e );
                ex.Log();

                return formattedPost;
            }
        }
Beispiel #7
0
 public void LogException(CSException exception)
 {
     LogException(exception,CSContext.Current.SiteSettings.SettingsID);
 }
Beispiel #8
0
 public abstract void LogException(CSException exception, int SettingsID);
Beispiel #9
0
        public static SiteSettings PopulateSiteSettingsFromIDataReader(IDataReader dr)
        {
            SiteSettings settings = null;

            try {
                settings =  Serializer.ConvertToObject(dr["SettingsXML"] as string,typeof(SiteSettings)) as SiteSettings;

                //When new sites/communities are created, it is very likely they will not have any XML history.
                //Serializer.ConvertToObject will return null if no XML is present.
                if(settings == null)
                    settings = new SiteSettings();
            } catch (Exception exception) {

                if (exception.InnerException is XmlException) {

                    Debug.WriteLine("Critical Error: SiteSettings serialized XML is invalid");
                    CSException csException = new CSException(CSExceptionType.SiteSettingsInvalidXML);

                    throw csException;

                } else {
                    throw exception;
                }

            }

            // read addition data
            settings.SettingsID = (int) dr["SettingsID"];
            settings.SiteDomain = dr["SiteUrl"] as string;
            settings.ForumsDisabled = (bool)dr["Disabled"];
            settings.SiteKey = (Guid)dr["SettingsKey"];
            settings.ApplicationName = dr["ApplicationName"] as string;

            return settings;
        }
Beispiel #10
0
        public static CSException PopulateForumExceptionFromIDataReader(IDataReader reader)
        {
            CSException exception = new CSException( (CSExceptionType) (int) reader["Category"], (string) reader["ExceptionMessage"]);

            exception.LoggedStackTrace  = (string) reader["Exception"];
            exception.IPAddress         = (string) reader["IPAddress"];
            exception.UserAgent         = (string) reader["UserAgent"];
            exception.HttpReferrer      = (string) reader["HttpReferrer"];
            exception.HttpVerb          = (string) reader["HttpVerb"];
            exception.HttpPathAndQuery  = (string) reader["PathAndQuery"];
            exception.DateCreated       = (DateTime) reader["DateCreated"];
            exception.DateLastOccurred  = (DateTime) reader["DateLastOccurred"];
            exception.Frequency         = (int) reader["Frequency"];
            exception.ExceptionID       = (int) reader["ExceptionID"];

            return exception;
        }
Beispiel #11
0
        /// <summary>
        /// Enables the interation of all current SiteSettings
        /// </summary>
        /// <param name="iter">Meth which takes a single parameter SettingsID</param>
        public static void IterateSiteSettings(SiteSettingsListIterator iter)
        {
            //            Hashtable ht = SiteSettingsManager.GetActiveSiteSettings();
            //            if(ht == null || ht.Count == 0)
            //                return;
            //
            //
            //			string[] keys = new string[ht.Count];
            //			ht.Keys.CopyTo(keys, 0);

            int[] settingIDs = SiteSettingsManager.GetSettingIDs();
            for(int i = 0; i < settingIDs.Length; i++)
            {

                try
                {
                    iter(settingIDs[i]);

                }
                catch(Exception ex)
                {
                    CSException csException = new CSException(CSExceptionType.UnknownError,string.Format("Iterator Failed. Type {0}. Method {1}. Reason {2}",iter.Method.DeclaringType, iter.Method.Name,ex.Message));
                    csException.Log(settingIDs[i]);
                    throw;
                }
            }
        }
Beispiel #12
0
 internal void ExecuteCSExcetion(CSException csEx)
 {
     CSExceptionHandler handler = Events[EventUnhandledException] as CSExceptionHandler;
     if (handler != null)
     {
         handler(csEx,new CSEventArgs());
     }
 }
Beispiel #13
0
        /// <summary>
        /// Returns a intance of SiteUrls. We first check the cache and if not found
        /// we parse the SiteUrls.config file and build it.
        /// </summary>
        /// <returns></returns>
        public static SiteUrls Instance()
        {
            const string cacheKey = "SiteUrls";

            SiteUrls siteUrls = CSCache.Get(cacheKey) as SiteUrls;

            if(siteUrls == null)
            {
                try
                {
                    HttpContext Context = HttpContext.Current;
                    CSConfiguration config = CSConfiguration.GetConfig();

                    Provider siteUrlProvider = config.Providers["SiteUrlsDataProvider"] as Provider;

                    if(siteUrlProvider == null)
                    {
                        if(Context != null)
                        {
                            Context.Response.Write("<h1>SiteUrl Provider was NOT found!</h1>");
                            Context.Response.Write("A provider named SiteUrlsDataProvider with the type or derived type of CommunityServer.Components.SiteUrlsData, CommunityServer.Components must be added to the provider list");
                            Context.Response.End();
                        }
                        else
                        {
                            throw new CSException(CSExceptionType.SiteUrlDataProvider,"Could not load SiteUrlsProvider");
                        }
                    }

                    string siteUrlsXmlFile = config.FilesPath +  siteUrlProvider.Attributes["path"];
                    string file = CSContext.Current.PhysicalPath(siteUrlProvider.Attributes["path"]); // CSContext.Current.MapPath(Globals.ApplicationPath + siteUrlsXmlFile);
                    Type type = Type.GetType(siteUrlProvider.Type);
                    SiteUrlsData data = Activator.CreateInstance(type,new object[]{file}) as SiteUrlsData;

                    // Create the instance for the provider, or fall back on the builtin one
                    //
                    Provider urlProvider = (Provider) CSConfiguration.GetConfig().Providers[SiteUrlsProviderName];
                    if(urlProvider != null)
                        siteUrls = ApplicationUrls.CreateInstance(urlProvider, data) as SiteUrls;
                    else
                        siteUrls = new SiteUrls(data);

                    CacheDependency dep = new CacheDependency(file);
                    CSCache.Max(cacheKey, siteUrls, dep);
                }
                catch(Exception ex)
                {

                    if (ex.InnerException != null && ex.InnerException is CSException)
                    {
                        throw ex.InnerException;
                    }

                    string message = "<p>" +  ex.Message + "</p>";

                    Exception inner = ex.InnerException;

                    while(inner != null)
                    {
                        message = string.Format("{0}<p>{1}</p>", message, inner.Message);
                        inner = inner.InnerException;

                    }

                    CSException csex =  new CSException(CSExceptionType.SiteUrlDataProvider,message,ex);
                    CatastrophicMessage.Write(HttpContext.Current,csex,"[SiteUrlData]","SiteUrlData.htm");
                }
            }

            return siteUrls;
        }
Beispiel #14
0
        public static void SendQueuedEmails(int failureInterval, int maxNumberOfTries)
        {
            CommonDataProvider dp = CommonDataProvider.Instance();
            CSConfiguration csConfig = CSConfiguration.GetConfig();

            // test to see if this server is disabled for sending email
            //
            if (csConfig.IsEmailDisabled)
                return;

            Hashtable sites = SiteSettingsManager.GetActiveSiteSettings();
            if(sites == null || sites.Count == 0)
                return;

            // Copy the keys to another array to avoid getting a collection modified error
            string[] keys = new string[sites.Count];
            sites.Keys.CopyTo(keys, 0);

            foreach(string key in keys)
            {
                SiteSettings site = sites[key] as SiteSettings;
                if(site == null || !site.EnableEmail)
                    continue;

                ArrayList emails = dp.EmailDequeue(site.SettingsID);
                ArrayList failure = new ArrayList();

                SmtpMail.SmtpServer = site.SmtpServer;
                string username = site.SmtpServerUserName;
                string password = site.SmtpServerPassword;

                int sentCount	= 0;
                int totalSent	= 0;
                short connectionLimit = csConfig.SmtpServerConnectionLimit;
                foreach (EmailTemplate m in emails)
                {
                    try
                    {
                        //for SMTP Authentication
                        if (site.SmtpServerRequiredLogin)
                        {
                            m.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1" ); //basic authentication
                            m.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", username ); //set your username here
                            m.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password ); //set your password here
                        }

                        // For Html emails, this resolves the complete paths for images and links.
                        // Should not effect non-Html emails via RFC-2110.
                        //
                        // EAD 1/14/2005: Commented out until we can access the forumContext from a background thread.
                        //m.Fields.Add("Content-Base", Globals.FullPath(Globals.GetSiteUrls().Home) );
                        //m.Fields.Add("Content-Location", Globals.FullPath(Globals.GetSiteUrls().Home) );
                        m.Headers.Add("X-CS-EmailID", m.EmailID.ToString());
                        m.Headers.Add("X-CS-ThreadId", AppDomain.GetCurrentThreadId().ToString());
                        m.Headers.Add("X-CS-Attempts", (m.NumberOfTries + 1).ToString());
                        m.Headers.Add("X-CS-AppDomain", AppDomain.CurrentDomain.FriendlyName);
                        SmtpMail.Send(m);

                        // (Ken) Moved the delete command to here
                        //       If a number of emails were sent, the command to delete them could timeout and duplicates would be sent on the next run
                        dp.EmailDelete(m.EmailID);

                        if(		connectionLimit != -1 &&	++sentCount >= connectionLimit )
                        {
                            Thread.Sleep( new TimeSpan( 0, 0, 0, 15, 0 ) );
                            sentCount = 0;
                        }
                        // on error, loop so to continue sending other email.
                    }
                    catch( Exception e )
                    {
                        Debug.WriteLine( e.Message + " : " + ( e.InnerException != null ? e.InnerException.Message : String.Empty ) );
                        CSException fe = new CSException( CSExceptionType.EmailUnableToSend, "SendQueuedEmails Failed To: " + m.To, ( e.InnerException != null ? e.InnerException : e ) );
                        fe.Log(site.SettingsID);

                        // Add it to the failure list
                        failure.Add(m.EmailID);
                    }

                    if( site.EmailThrottle > 0 && ++totalSent >= site.EmailThrottle ) {
                        break;
                    }
                }

                if(failure.Count > 0)
                    dp.EmailFailure(failure, failureInterval, maxNumberOfTries);

            }
        }
Beispiel #15
0
Datei: Roles.cs Projekt: pcstx/OA
        public static string[] GetUserRoleNames(string username, bool cacheable)
        {
            string[] roles  = null;
            string key = "UserRoleNames:" + username;

            if(cacheable)
                roles = CSCache.Get(key) as string[];
            else
                CSCache.Remove(key);

            if(roles == null)
            {

                // there is a situation where the cookie may be using an old username, which can cause this call to fail, at this point
                // we're too deep in the call tree to do anything else, so we just need to log the exception and force the
                // user to signout since we're having problems pulling the user's roles from the database
                try{
                    roles = Microsoft.ScalableHosting.Security.Roles.GetRolesForUser(username);

                    if(cacheable)
                        CSCache.Insert(key, roles, 10 * CSCache.MinuteFactor);
                }
                catch( Exception e ) {
                    CSException cse = new CSException( CSExceptionType.RoleNotFound, String.Format("Error while trying to find a role for the user '{0}'. Possible cause is a invalid client cookie or a user rename.", username ), e );
                    cse.Log();

                    FormsAuthentication.SignOut();
                    HttpContext.Current.Response.Redirect( SiteUrls.Instance().Home );
                }
            }

            return roles;
        }
Beispiel #16
0
        private void Application_AuthenticateRequest(Object source, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            Provider p = null;
            ExtensionModule module = null;

            // If the installer is making the request terminate early
            if (CSConfiguration.GetConfig().AppLocation.CurrentApplicationType == ApplicationType.Installer)
            {
                return;
            }

            // Only continue if we have a valid context
            //
            if ((context == null) || (context.User == null))
                return;

            try
            {
                // Logic to handle various authentication types
                //
                switch (context.User.Identity.GetType().Name.ToLower())
                {

                    // Microsoft passport
                    case "passportidentity":
                        p = (Provider)CSConfiguration.GetConfig().Extensions["PassportAuthentication"];
                        module = ExtensionModule.Instance(p);
                        if (module != null)
                            module.ProcessRequest();
                        else
                            goto default;
                        break;

                    // Windows
                    case "windowsidentity":
                        p = (Provider)CSConfiguration.GetConfig().Extensions["WindowsAuthentication"];
                        module = ExtensionModule.Instance(p);
                        if (module != null)
                            module.ProcessRequest();
                        else
                            goto default;
                        break;

                    // Forms
                    case "formsidentity":
                        p = (Provider)CSConfiguration.GetConfig().Extensions["FormsAuthentication"];
                        module = ExtensionModule.Instance(p);
                        if (module != null)
                            module.ProcessRequest();
                        else
                            goto default;
                        break;

                    // Custom
                    case "customidentity":
                        p = (Provider)CSConfiguration.GetConfig().Extensions["CustomAuthentication"];
                        module = ExtensionModule.Instance(p);
                        if (module != null)
                            module.ProcessRequest();
                        else
                            goto default;
                        break;

                    default:
                        CSContext.Current.UserName = context.User.Identity.Name;
                        break;

                }

            }
            catch (Exception ex)
            {
                CSException forumEx = new CSException(CSExceptionType.UnknownError, "Error in AuthenticateRequest", ex);
                forumEx.Log();

                throw forumEx;
            }

            //			// Get the roles the user belongs to
            //			//
            //			Roles roles = new Roles();
            //			roles.GetUserRoles();
        }