Exemplo n.º 1
0
 public void ExecuteNonQueryCommand(SqlCommand command)
 {
     try
     {
         if (command.Connection.State != ConnectionState.Open)
         {
             try
             {
                 command.Connection.Open();
                 command.ExecuteNonQuery();
             }
             finally
             {
                 try { command.Connection.Close(); }
                 catch { }
             }
         }
         else
         {
             command.ExecuteNonQuery();
         }
     }
     catch (Exception exception)
     {
         InfLogger.Log(exception);
         throw;
     }
 }
Exemplo n.º 2
0
        public DataSet ExecuteDataSetCommand(SqlCommand command)
        {
            var cachedResult = GetCachedResult(command);

            if (cachedResult != null)
            {
                return((DataSet)cachedResult);
            }

            try
            {
                using (var dataSet = new DataSet())
                {
                    dataSet.Locale = CultureInfo.InvariantCulture;

                    using (var adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dataSet);
                    }

                    SetCachedResult(command, dataSet);
                    return(dataSet);
                }
            }
            catch (Exception exception)
            {
                InfLogger.Log(exception);
                throw;
            }
        }
Exemplo n.º 3
0
 public ActionResult Log(int logLevel, string source, string message)
 {
     return(Json(InfLogger.Log(new InfLogEntry
     {
         LogLevel = (InfLogLevel)logLevel,
         Source = source,
         Message = message
     })));
 }
Exemplo n.º 4
0
 public ActionResult StartEmailQueue()
 {
     try
     {
         InfEmail.StartQueue();
         return(Content("The email queue was started successfully."));
     }
     catch (Exception exception)
     {
         var baseException = exception.GetBaseException();
         InfLogger.Log(baseException);
         return(Content(string.Format(CultureInfo.InvariantCulture, "An error occurred while attempting to start the email queue: {0}", baseException.Message)));
     }
 }
Exemplo n.º 5
0
        public SqlCommand CreateCommand(CommandType commandType, string commandText, params SqlParameter[] parameters)
        {
            var command = new SqlCommand();

            command.Connection     = CreateConnection();
            command.CommandType    = commandType;
            command.CommandText    = commandText;
            command.CommandTimeout = Convert.ToInt32(CommandTimeout.TotalSeconds);

            if (parameters != null && parameters.Length > 0)
            {
                foreach (var parameter in parameters)
                {
                    // convert empty strings to null
                    if (parameter.DbType == DbType.String)
                    {
                        var value = parameter.Value as string;
                        if (string.IsNullOrWhiteSpace(value))
                        {
                            parameter.Value = null;
                        }
                        else
                        {
                            parameter.Value = value.Trim();
                        }
                    }

                    // convert null parameters to DBNull
                    parameter.Value = parameter.Value ?? DBNull.Value;

                    command.Parameters.Add(parameter);
                }
            }

            // do not log calls to the logging stored procedure itself
            if (!command.CommandText.Equals("dbo.PSP_InfLog_Insert", StringComparison.OrdinalIgnoreCase))
            {
                InfLogger.Log(InfLogLevel.Debug, command.ToSqlString());
            }

            // validate for possible SQL injection
            if (command.CommandType == CommandType.Text || !SafeStoredProcedures.Any(sp => sp.Equals(command.CommandText, StringComparison.OrdinalIgnoreCase)))
            {
                command.Validate();
            }

            return(command);
        }
Exemplo n.º 6
0
        protected void InfBaseGlobal_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            InfLogger.Log(exception);

            // HttpRequestValidationException is thrown by ASP.Net when a potentially malicious input string
            // is received from the client as part of the request data.
            // We want to handle it more gracefully than just displaying the default ASP.Net error page.
            // We also want to handle SQL injection validation exceptions the same way.
            if (exception is HttpRequestValidationException ||
                exception is InfSqlValidationException)
            {
                HandleValidationException(Context);
            }
        }
Exemplo n.º 7
0
        private static void InitEmail()
        {
            InfEmail.AutoStartQueue   = ConfigurationManager.AppSettings["Inf:AutoStartEmailQueue"].TryConvertTo <bool>(false);
            InfEmail.QueueInterval    = TimeSpan.FromSeconds(ConfigurationManager.AppSettings["Inf:EmailQueueIntervalSeconds"].TryConvertTo <int>(10));
            InfEmail.MaxRetryAttempts = ConfigurationManager.AppSettings["Inf:MaxEmailRetryAttempts"].TryConvertTo <int>(5);

            if (InfEmail.AutoStartQueue)
            {
                try
                {
                    InfEmail.StartQueue();
                }
                catch (Exception exception)
                {
                    InfLogger.Log(exception);
                }
            }
        }
Exemplo n.º 8
0
 public SqlDataReader ExecuteReaderCommand(SqlCommand command)
 {
     try
     {
         if (command.Connection.State != ConnectionState.Open)
         {
             command.Connection.Open();
             return(command.ExecuteReader(CommandBehavior.CloseConnection));
         }
         else
         {
             return(command.ExecuteReader());
         }
     }
     catch (Exception exception)
     {
         InfLogger.Log(exception);
         throw;
     }
 }
Exemplo n.º 9
0
        public object ExecuteScalarCommand(SqlCommand command)
        {
            var cachedResult = GetCachedResult(command);

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

            try
            {
                if (command.Connection.State != ConnectionState.Open)
                {
                    try
                    {
                        command.Connection.Open();
                        var scalar = command.ExecuteScalar();

                        SetCachedResult(command, scalar);
                        return(scalar);
                    }
                    finally
                    {
                        try { command.Connection.Close(); }
                        catch { }
                    }
                }
                else
                {
                    var scalar = command.ExecuteScalar();

                    SetCachedResult(command, scalar);
                    return(scalar);
                }
            }
            catch (Exception exception)
            {
                InfLogger.Log(exception);
                throw;
            }
        }
Exemplo n.º 10
0
        private static void SendQueuedEmails()
        {
            using (var emailQueue = InfEmailDataAccess.GetQueuedEmails(MaxRetryAttempts))
            {
                foreach (DataRow emailRow in emailQueue.Rows)
                {
                    var infEmailId = (long)emailRow["InfEmailId"];
                    var from       = emailRow["FromAddress"].ToString();
                    var to         = emailRow["ToAddress"].ToString().Replace(';', ',');
                    var cc         = emailRow["CcAddress"].ToString().Replace(';', ',');
                    var bcc        = emailRow["BccAddress"].ToString().Replace(';', ',');
                    var subject    = emailRow["Subject"].ToString();
                    var body       = emailRow["Body"].ToString();
                    var priority   = emailRow["Priority"].ToString();
                    var htmlInd    = emailRow["HtmlInd"].ToString().StartsWith("Y", StringComparison.OrdinalIgnoreCase);

                    using (var email = new MailMessage(from, to, subject, body))
                    {
                        email.IsBodyHtml = htmlInd;

                        if (!string.IsNullOrWhiteSpace(cc))
                        {
                            email.CC.Add(cc);
                        }

                        if (!string.IsNullOrWhiteSpace(bcc))
                        {
                            email.Bcc.Add(bcc);
                        }

                        if (!string.IsNullOrWhiteSpace(priority))
                        {
                            email.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), priority, true);
                        }

                        using (var attachmentsTable = InfEmailDataAccess.GetAttachmentsForEmail(infEmailId))
                        {
                            foreach (DataRow attachmentRow in attachmentsTable.Rows)
                            {
                                var attachmentName  = attachmentRow["AttachmentName"].ToString();
                                var attachmentBytes = attachmentRow["AttachmentBytes"] as byte[];

                                using (var memoryStream = new MemoryStream(attachmentBytes))
                                {
                                    using (var attachment = new Attachment(memoryStream, attachmentName))
                                    {
                                        email.Attachments.Add(attachment);
                                    }
                                }
                            }
                        }

                        try
                        {
                            Send(email);
                            InfEmailDataAccess.SaveSuccessStatus(infEmailId);
                        }
                        catch (Exception ex)
                        {
                            var baseException = ex.GetBaseException();
                            InfLogger.Log(baseException);

                            var lastError = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", baseException.GetType().FullName, baseException.Message);
                            InfEmailDataAccess.SaveErrorStatus(infEmailId, lastError);
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        public InfReportOutput Render(InfReportFormat format)
        {
            if (string.IsNullOrWhiteSpace(FileName))
            {
                throw new InvalidOperationException("The report file name property has not been set.");
            }

            if (FileName.StartsWith("/", StringComparison.Ordinal) && HttpContext.Current != null)
            {
                FileName = HttpContext.Current.Server.MapPath(FileName);
            }

            if (!File.Exists(FileName))
            {
                throw new FileNotFoundException("The specified report file name does not exist. Be sure to provide the full path, and set the \"Build Action\" of the report file to \"Content\".", FileName);
            }

            try
            {
                using (var report = new LocalReport())
                {
                    report.ReportPath = FileName;

                    foreach (var dataSourceName in report.GetDataSourceNames())
                    {
                        if (!DataTables.Any(dt => dt.Key.Equals(dataSourceName, StringComparison.OrdinalIgnoreCase)))
                        {
                            var message = string.Format(CultureInfo.InvariantCulture, "No data table has been added for the report data source name \"{0}\".", dataSourceName);
                            throw new InvalidOperationException(message);
                        }
                    }

                    foreach (var parameter in report.GetParameters())
                    {
                        if (!Parameters.Any(p => p.Key.Equals(parameter.Name, StringComparison.OrdinalIgnoreCase)))
                        {
                            var message = string.Format(CultureInfo.InvariantCulture, "No parameter has been added for the report parameter \"{0}\".", parameter.Name);
                            throw new InvalidOperationException(message);
                        }
                    }

                    report.EnableExternalImages = true;
                    report.EnableHyperlinks     = true;
                    report.DataSources.Clear();

                    foreach (var item in DataTables)
                    {
                        report.DataSources.Add(new ReportDataSource(item.Key, item.Value));
                    }

                    foreach (var item in Parameters)
                    {
                        report.SetParameters(new ReportParameter(item.Key, item.Value));
                    }

                    if (!report.IsReadyForRendering)
                    {
                        throw new InvalidOperationException("The report is not ready for rendering. Check that all required data tables and parameters have been added.");
                    }

                    var reportBytes   = new byte[0];
                    var mimeType      = string.Empty;
                    var fileExtension = string.Empty;
                    var encoding      = string.Empty;
                    var streams       = new string[0];
                    var warnings      = new Warning[0];

                    report.Refresh();
                    reportBytes = report.Render(
                        format.ToString(),
                        string.Empty, // device info
                        out mimeType,
                        out encoding,
                        out fileExtension,
                        out streams,
                        out warnings);

                    if (warnings != null && warnings.Length > 0 && warnings.Any(w => w.Severity == Severity.Error))
                    {
                        var message = new StringBuilder();
                        message.Append("The following error(s) occurred during report rendering: ");

                        foreach (var warning in warnings.Where(w => w.Severity == Severity.Error))
                        {
                            message.AppendFormat(
                                CultureInfo.InvariantCulture,
                                "code = \"{0}\"; object name = \"{1}\"; object type = \"{2}\"; message = \"{3}\".",
                                warning.Code,
                                warning.ObjectName,
                                warning.ObjectType,
                                warning.Message);
                        }
                    }

                    return(new InfReportOutput
                    {
                        FileExtension = fileExtension,
                        MimeType = mimeType,
                        Encoding = encoding,
                        ReportBytes = reportBytes
                    });
                }
            }
            catch (Exception ex)
            {
                InfLogger.Log(ex);
                throw;
            }
        }
Exemplo n.º 12
0
 protected void InfBaseGlobal_PreRequestHandlerExecute(object sender, EventArgs e)
 {
     InfLogger.Log(InfLogLevel.Debug, HttpContext.Current.Request.ToLogString());
 }