Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. namespace FichaProjeto
  2. {
  3.     using Administration;
  4.     using Serenity;
  5.     using Serenity.Abstractions;
  6.     using Serenity.Data;
  7.     using Serenity.Web;
  8.     using System;
  9.     using System.Configuration;
  10.  
  11.     public static partial class SiteInitialization
  12.     {
  13.         public static void ApplicationStart()
  14.         {
  15.             try
  16.             {
  17.                 SqlSettings.AutoQuotedIdentifiers = true;
  18.                 Serenity.Web.CommonInitialization.Run();
  19.  
  20.                 var registrar = Dependency.Resolve<IDependencyRegistrar>();
  21.                 registrar.RegisterInstance<IAuthorizationService>(new Administration.AuthorizationService());
  22.                 registrar.RegisterInstance<IAuthenticationService>(new Administration.AuthenticationService());
  23.                 registrar.RegisterInstance<IPermissionService>(new LogicOperatorPermissionService(new Administration.PermissionService()));
  24.                 registrar.RegisterInstance<IUserRetrieveService>(new Administration.UserRetrieveService());
  25.  
  26.                 if (!ConfigurationManager.AppSettings["LDAP"].IsTrimmedEmpty())
  27.                     registrar.RegisterInstance<IDirectoryService>(new LdapDirectoryService());
  28.  
  29.                 if (!ConfigurationManager.AppSettings["ActiveDirectory"].IsTrimmedEmpty())
  30.                     registrar.RegisterInstance<IDirectoryService>(new ActiveDirectoryService());
  31.  
  32.                 InitializeExceptionLog();
  33.                 InicializaSentryExceptionLog();
  34.             }
  35.             catch (Exception ex)
  36.             {
  37.                 ex.Log();
  38.                 throw;
  39.             }
  40.  
  41.             foreach (var databaseKey in databaseKeys)
  42.             {
  43.                 EnsureDatabase(databaseKey);
  44.                 RunMigrations(databaseKey);
  45.             }
  46.         }
  47.  
  48.         public static void ApplicationEnd()
  49.         {
  50.         }
  51.     }
  52. }
  53.  
  54. ///
  55. namespace FichaProjeto
  56. {
  57.     using Newtonsoft.Json;
  58.     using Serenity;
  59.     using Serenity.Abstractions;
  60.     using SharpRaven;
  61.     using StackExchange.Exceptional;
  62.     using System;
  63.     using System.Collections.Generic;
  64.     using System.Collections.Specialized;
  65.     using System.Configuration;
  66.     using System.Globalization;
  67.     using System.Web;
  68.     using System.Web.Security;
  69.  
  70.     public static partial class SiteInitialization
  71.     {
  72.         public static RavenClient ravenClient { get; set; }
  73.  
  74.         private static void InicializaSentryExceptionLog()
  75.         {
  76.             try
  77.             {
  78.  
  79.                 var configSentry = Setting<string>("SENTRY");
  80.  
  81.                 //Converte JSON para Dicionário de Dados
  82.                 var configuracoes = JsonConvert.DeserializeObject<Dictionary<string, object>>(configSentry);
  83.  
  84.                 var url = configuracoes["URL"].ToString();
  85.  
  86.                 ravenClient = ravenClient ?? new RavenClient(url);
  87.             }
  88.             catch (Exception ex)
  89.             {
  90.                 throw ex;
  91.             }
  92.         }
  93.  
  94.         private static T Setting<T>(string name)
  95.         {
  96.             string value = ConfigurationManager.AppSettings[name];
  97.  
  98.             if (value == null)
  99.             {
  100.                 throw new Exception(String.Format("Could not find setting '{0}',", name));
  101.             }
  102.  
  103.             return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
  104.         }
  105.  
  106.         private static void InitializeExceptionLog()
  107.         {
  108.             ErrorStore.Setup("FichaProjeto", new SqlErrorStore(null, "Default"));
  109.  
  110.             ErrorStore.GetCustomData = (exception, context, data) =>
  111.             {
  112.                 foreach (var key in exception.Data.Keys)
  113.                 {
  114.                     var s = key as string;
  115.                     if (s != null && s.StartsWith("log:", StringComparison.OrdinalIgnoreCase))
  116.                     {
  117.                         string v;
  118.                         var value = exception.Data[key];
  119.                         if (value == null)
  120.                             v = "[null]";
  121.                         else
  122.                             v = value.ToString();
  123.  
  124.                         data.Add(s.Substring(4), v);
  125.                     }
  126.                 }
  127.             };
  128.  
  129.             ErrorStore.OnBeforeLog += (sender, args) =>
  130.             {
  131.                 if (args.Error.Exception != null && args.Error is INotLoggedException)
  132.                     args.Abort = true;
  133.  
  134.                 args.Error.Cookies.Remove(FormsAuthentication.FormsCookieName);
  135.                 ReplaceKey(args.Error.Form, "Password");
  136.                 ReplaceKey(args.Error.Form, "PasswordConfirm");
  137.             };
  138.  
  139.             Dependency.Resolve<IDependencyRegistrar>().RegisterInstance<IExceptionLogger>(new ErrorStoreLogger());
  140.         }
  141.  
  142.         private static void ReplaceKey(NameValueCollection collection, string key)
  143.         {
  144.             var item = collection[key];
  145.             if (item != null)
  146.                 collection[item] = "***";
  147.         }
  148.  
  149.         private class ErrorStoreLogger : IExceptionLogger
  150.         {
  151.             public void Log(Exception exception)
  152.             {
  153.                 ravenClient.Capture(new SharpRaven.Data.SentryEvent(exception) { Extra = HttpContext.Current.Items });
  154.  
  155.                 ErrorStore.LogException(exception, HttpContext.Current);
  156.             }
  157.         }
  158.     }
  159. }
  160. /////
  161. using Serenity.Data;
  162. using StackExchange.Exceptional;
  163. using StackExchange.Exceptional.Extensions;
  164. using System;
  165. using System.Collections.Generic;
  166. using System.Data;
  167. using System.Linq;
  168.  
  169. namespace FichaProjeto
  170. {
  171.     /// <summary>
  172.     /// An <see cref="ErrorStore"/> implementation that uses an SQL database using Serenity helpers as its backing store.
  173.     /// </summary>
  174.     public sealed class SqlErrorStore : ErrorStore
  175.     {
  176.         private readonly int displayCount = DefaultDisplayCount;
  177.         private readonly string connectionString;
  178.         private readonly string providerName;
  179.         private readonly bool isSqlServer;
  180.  
  181.         /// <summary>
  182.         /// The maximum count of errors to show.
  183.         /// </summary>
  184.         public const int MaximumDisplayCount = 500;
  185.  
  186.         /// <summary>
  187.         /// The default maximum count of errors shown at once.
  188.         /// </summary>        
  189.         public const int DefaultDisplayCount = 200;
  190.  
  191.         /// <summary>
  192.         /// Creates a new instance of <see cref="SqlErrorStore"/> with the given configuration.
  193.         /// </summary>        
  194.         public SqlErrorStore(ErrorStoreSettings settings)
  195.             : this(settings.ConnectionString, settings.ConnectionStringName, settings.Size, settings.RollupSeconds)
  196.         {
  197.         }
  198.  
  199.         public SqlErrorStore(string connectionString, string connectionKey, int displayCount = DefaultDisplayCount, int rollupSeconds = DefaultRollupSeconds)
  200.             : base(rollupSeconds)
  201.         {
  202.             displayCount = Math.Min(displayCount, MaximumDisplayCount);
  203.  
  204.             if (connectionString.IsNullOrEmpty())
  205.             {
  206.                 var cs = SqlConnections.GetConnectionString(connectionKey);
  207.                 this.connectionString = cs.ConnectionString;
  208.                 this.providerName = cs.ProviderName;
  209.                 isSqlServer = cs.Dialect.ServerType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase);
  210.             }
  211.             else
  212.             {
  213.                 this.connectionString = connectionString;
  214.                 this.providerName = connectionKey;
  215.                 isSqlServer = providerName.IndexOf("SqlClient", StringComparison.OrdinalIgnoreCase) >= 0;
  216.             }
  217.  
  218.             // check that provider name is valid
  219.             SqlConnections.GetFactory(this.providerName);
  220.  
  221.             if (this.connectionString.IsNullOrEmpty())
  222.             {
  223.                 var ex = new ArgumentOutOfRangeException("settings", "A connection string or connection string name must be specified when using a SQL error store");
  224.                 SiteInitialization.ravenClient.Capture(new SharpRaven.Data.SentryEvent(ex));
  225.                 throw ex;
  226.             }
  227.  
  228.         }
  229.  
  230.         /// <summary>
  231.         /// Name for this error store
  232.         /// </summary>
  233.         public override string Name
  234.         {
  235.             get
  236.             {
  237.                 return "Serenity Sql Error Store";
  238.             }
  239.         }
  240.  
  241.         /// <summary>
  242.         /// Protects an error from deletion, by making IsProtected = 1 in the database
  243.         /// </summary>
  244.         /// <param name="guid">The guid of the error to protect</param>
  245.         /// <returns>True if the error was found and protected, false otherwise</returns>
  246.         protected override bool ProtectError(Guid guid)
  247.         {
  248.             using (var c = GetConnection())
  249.             {
  250.                 return new SqlUpdate("Exceptions")
  251.                     .Set("IsProtected", true)
  252.                     .SetNull("DeletionDate")
  253.                     .Where(new Criteria("[GUID]") == guid)
  254.                     .Execute(c, ExpectedRows.Ignore) > 0;
  255.             }
  256.         }
  257.  
  258.         /// <summary>
  259.         /// Protects errors from deletion, by making IsProtected = 1 in the database
  260.         /// </summary>
  261.         /// <param name="guids">The guids of the error to protect</param>
  262.         /// <returns>True if the errors were found and protected, false otherwise</returns>
  263.         protected override bool ProtectErrors(IEnumerable<Guid> guids)
  264.         {
  265.             using (var c = GetConnection())
  266.             {
  267.                 return new SqlUpdate("Exceptions")
  268.                     .Set("IsProtected", true)
  269.                     .SetNull("DeletionDate")
  270.                     .Where(new Criteria("[GUID]").In(guids))
  271.                     .Execute(c, ExpectedRows.Ignore) > 0;
  272.             }
  273.         }
  274.  
  275.         /// <summary>
  276.         /// Deletes an error, by setting DeletionDate = GETUTCDATE() in SQL
  277.         /// </summary>
  278.         /// <param name="guid">The guid of the error to delete</param>
  279.         /// <returns>True if the error was found and deleted, false otherwise</returns>
  280.         protected override bool DeleteError(Guid guid)
  281.         {
  282.             using (var c = GetConnection())
  283.             {
  284.                 return new SqlUpdate("Exceptions")
  285.                     .Set("DeletionDate", DateTime.UtcNow)
  286.                     .Where(
  287.                         new Criteria("[GUID]") == guid &
  288.                         new Criteria("[DeletionDate]").IsNull())
  289.                     .Execute(c, ExpectedRows.Ignore) > 0;
  290.             }
  291.         }
  292.  
  293.         /// <summary>
  294.         /// Deletes errors, by setting DeletionDate = GETUTCDATE() in SQL
  295.         /// </summary>
  296.         /// <param name="guids">The guids of the error to delete</param>
  297.         /// <returns>True if the errors were found and deleted, false otherwise</returns>
  298.         protected override bool DeleteErrors(IEnumerable<Guid> guids)
  299.         {
  300.             using (var c = GetConnection())
  301.             {
  302.                 return new SqlUpdate("Exceptions")
  303.                     .Set("DeletionDate", DateTime.UtcNow)
  304.                     .Where(
  305.                         new Criteria("[GUID]").In(guids) &
  306.                         new Criteria("[DeletionDate]").IsNull())
  307.                     .Execute(c, ExpectedRows.Ignore) > 0;
  308.             }
  309.         }
  310.  
  311.         /// <summary>
  312.         /// Hard deletes an error, actually deletes the row from SQL rather than setting DeletionDate
  313.         /// This is used to cleanup when testing the error store when attempting to come out of retry/failover mode after losing connection to SQL
  314.         /// </summary>
  315.         /// <param name="guid">The guid of the error to hard delete</param>
  316.         /// <returns>True if the error was found and deleted, false otherwise</returns>
  317.         protected override bool HardDeleteError(Guid guid)
  318.         {
  319.             using (var c = GetConnection())
  320.             {
  321.                 return new SqlDelete("Exceptions")
  322.                     .Where(
  323.                         new Criteria("[GUID]") == guid &
  324.                         new Criteria("[ApplicationName]") == ApplicationName)
  325.                     .Execute(c, ExpectedRows.Ignore) > 0;
  326.             }
  327.         }
  328.  
  329.         /// <summary>
  330.         /// Deleted all errors in the log, by setting DeletionDate = GETUTCDATE() in SQL
  331.         /// </summary>
  332.         /// <returns>True if any errors were deleted, false otherwise</returns>
  333.         protected override bool DeleteAllErrors(string applicationName = null)
  334.         {
  335.             using (var c = GetConnection())
  336.             {
  337.                 return new SqlUpdate("Exceptions")
  338.                     .Set("DeletionDate", DateTime.UtcNow)
  339.                     .Where(
  340.                         new Criteria("[DeletionDate]").IsNull() &
  341.                         new Criteria("[IsProtected]") == 0 &
  342.                         new Criteria("[ApplicationName]") == applicationName.IsNullOrEmptyReturn(ApplicationName))
  343.                     .Execute(c, ExpectedRows.Ignore) > 0;
  344.             }
  345.         }
  346.  
  347.         private static readonly BaseCriteria hashMatch =
  348.             new Criteria("[ErrorHash]") == new ParamCriteria("@ErrorHash") &
  349.             new Criteria("[ApplicationName]") == new ParamCriteria("@ApplicationName") &
  350.             new Criteria("[DeletionDate]").IsNull() &
  351.             new Criteria("[CreationDate]") >= new ParamCriteria("@minDate");
  352.  
  353.         /// <summary>
  354.         /// Logs the error to SQL
  355.         /// If the rollup conditions are met, then the matching error will have a DuplicateCount += @DuplicateCount (usually 1, unless in retry) rather than a distinct new row for the error
  356.         /// </summary>
  357.         /// <param name="error">The error to log</param>
  358.         protected override void LogError(Error error)
  359.         {
  360.             SiteInitialization.ravenClient.Capture(new SharpRaven.Data.SentryEvent(error.Exception) { Extra = error });
  361.  
  362.             using (var c = GetConnection())
  363.             {
  364.                 if (RollupThreshold.HasValue && error.ErrorHash.HasValue)
  365.                 {
  366.                     var queryParams = new Serenity.Data.DynamicParameters(new
  367.                     {
  368.                         error.DuplicateCount,
  369.                         error.ErrorHash,
  370.                         ApplicationName = error.ApplicationName.Truncate(50),
  371.                         minDate = DateTime.UtcNow.Add(RollupThreshold.Value.Negate())
  372.                     });
  373.  
  374.                     if (isSqlServer)
  375.                     {
  376.                         queryParams.Add("@newGUID", dbType: DbType.Guid, direction: ParameterDirection.Output);
  377.                         var count = c.Execute(@"
  378. Update Exceptions
  379.     Set DuplicateCount = DuplicateCount + @DuplicateCount,
  380.         @newGUID = GUID
  381.     Where Id In (Select Top 1 Id
  382.                 From Exceptions
  383.                 Where ErrorHash = @ErrorHash
  384.                     And ApplicationName = @ApplicationName
  385.                     And DeletionDate Is Null
  386.                     And CreationDate >= @minDate)", queryParams);
  387.                         // if we found an error that's a duplicate, jump out
  388.                         if (count > 0)
  389.                         {
  390.                             error.GUID = queryParams.Get<Guid>("@newGUID");
  391.                             return;
  392.                         }
  393.                     }
  394.                     else
  395.                     {
  396.                         var count = new SqlUpdate("Exceptions")
  397.                             .Set("DuplicateCount", "DuplicateCount + @DuplicateCount")
  398.                             .Where(new Criteria("[Id]").In(new Criteria("(" +
  399.                                 new SqlQuery()
  400.                                     .Dialect(c.GetDialect())
  401.                                     .Select("[Id]")
  402.                                     .From("Exceptions")
  403.                                     .Take(1)
  404.                                     .Where(hashMatch)) + ")"))
  405.                                 .Execute(c, ExpectedRows.Ignore);
  406.  
  407.                         // if we found an exception that's a duplicate, jump out
  408.                         if (count > 0)
  409.                         {
  410.                             error.GUID = c.Query<Guid>(new SqlQuery()
  411.                                 .Dialect(c.GetDialect())
  412.                                 .From("Exceptions")
  413.                                 .Select("GUID")
  414.                                 .Take(1)
  415.                                 .Where(hashMatch)).First();
  416.  
  417.                             return;
  418.                         }
  419.                     }
  420.  
  421.                     error.FullJson = error.ToJson();
  422.  
  423.                     c.Execute(@"
  424. Insert Into Exceptions ([GUID], [ApplicationName], [MachineName], [CreationDate], [Type], [IsProtected], [Host], [Url], [HTTPMethod], [IPAddress], [Source], [Message], [Detail], [StatusCode], [SQL], [FullJson], [ErrorHash], [DuplicateCount])
  425. Values (@GUID, @ApplicationName, @MachineName, @CreationDate, @Type, @IsProtected, @Host, @Url, @HTTPMethod, @IPAddress, @Source, @Message, @Detail, @StatusCode, @SQL, @FullJson, @ErrorHash, @DuplicateCount)",
  426.                         new
  427.                         {
  428.                             error.GUID,
  429.                             ApplicationName = error.ApplicationName.Truncate(50),
  430.                             MachineName = error.MachineName.Truncate(50),
  431.                             error.CreationDate,
  432.                             Type = error.Type.Truncate(100),
  433.                             error.IsProtected,
  434.                             Host = error.Host.Truncate(100),
  435.                             Url = error.Url.Truncate(500),
  436.                             HTTPMethod = error.HTTPMethod.Truncate(10), // this feels silly, but you never know when someone will up and go crazy with HTTP 1.2!
  437.                             error.IPAddress,
  438.                             Source = error.Source.Truncate(100),
  439.                             Message = error.Message.Truncate(1000),
  440.                             error.Detail,
  441.                             error.StatusCode,
  442.                             error.SQL,
  443.                             error.FullJson,
  444.                             error.ErrorHash,
  445.                             error.DuplicateCount
  446.                         });
  447.                 }
  448.             }
  449.         }
  450.  
  451.         /// <summary>
  452.         /// Gets the error with the specified guid from SQL
  453.         /// This can return a deleted error as well, there's no filter based on DeletionDate
  454.         /// </summary>
  455.         /// <param name="guid">The guid of the error to retrieve</param>
  456.         /// <returns>The error object if found, null otherwise</returns>
  457.         protected override Error GetError(Guid guid)
  458.         {
  459.             Error sqlError;
  460.             using (var c = GetConnection())
  461.             {
  462.                 sqlError = c.Query<Error>(@"
  463. Select *
  464.   From [Exceptions]
  465.  Where [GUID] = @guid", new { guid }).FirstOrDefault(); // a guid won't collide, but the AppName is for security
  466.             }
  467.             if (sqlError == null) return null;
  468.  
  469.             // everything is in the JSON, but not the columns and we have to deserialize for collections anyway
  470.             // so use that deserialized version and just get the properties that might change on the SQL side and apply them
  471.             var result = Error.FromJson(sqlError.FullJson);
  472.             result.DuplicateCount = sqlError.DuplicateCount;
  473.             result.DeletionDate = sqlError.DeletionDate;
  474.             return result;
  475.         }
  476.  
  477.         /// <summary>
  478.         /// Retrieves all non-deleted application errors in the database
  479.         /// </summary>
  480.         protected override int GetAllErrors(List<Error> errors, string applicationName = null)
  481.         {
  482.             using (var c = GetConnection())
  483.             {
  484.                 errors.AddRange(c.Query<Error>(
  485.                     new SqlQuery()
  486.                         .Dialect(c.GetDialect())
  487.                         .From("Exceptions")
  488.                         .Take(displayCount)
  489.                         .Select("*")
  490.                         .Where(
  491.                             new Criteria("[ApplicationName]") == applicationName.IsNullOrEmptyReturn(ApplicationName) &
  492.                             new Criteria("[DeletionDate]").IsNull())
  493.                         .OrderBy("CreationDate", desc: true)));
  494.             }
  495.  
  496.             return errors.Count;
  497.         }
  498.  
  499.         /// <summary>
  500.         /// Retrieves a count of application errors since the specified date, or all time if null
  501.         /// </summary>
  502.         protected override int GetErrorCount(DateTime? since = null, string applicationName = null)
  503.         {
  504.             using (var c = GetConnection())
  505.             {
  506.                 return c.Query<int>(
  507.                     new SqlQuery()
  508.                         .Dialect(c.GetDialect())
  509.                         .From("Exceptions")
  510.                         .Select("Count(*)")
  511.                         .Where(
  512.                             new Criteria("[ApplicationName]") == applicationName.IsNullOrEmptyReturn(ApplicationName) &
  513.                             new Criteria("[DeletionDate]").IsNull() &
  514.                             (since.HasValue ? new Criteria("[CreationDate]") > since.Value : Criteria.Empty))
  515.                         .OrderBy("CreationDate", desc: true))
  516.                         .FirstOrDefault();
  517.             }
  518.         }
  519.  
  520.         private IDbConnection GetConnection()
  521.         {
  522.             return SqlConnections.New(connectionString, providerName);
  523.         }
  524.     }
  525. }
  526.  
  527. /////
  528. SharpRaven nuget
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement