Exemplo n.º 1
0
        protected static SqlCommand LoadEntryCommand(RFCatalogKey itemKey, int version, SqlConnection connection, SqlTransaction transaction = null)
        {
            if (itemKey.StoreType != RFStoreType.Document)
            {
                throw new Exception(String.Format("Unrecognized store type {0}", itemKey.StoreType));
            }

            SqlCommand sqlCommand = null;

            if (transaction != null)
            {
                sqlCommand = CreateCommand("[RIFF].[GetDocument]", connection, transaction);
            }
            else
            {
                sqlCommand = CreateCommand("[RIFF].[GetDocument]", connection);
            }

            var keyString = itemKey.ToString();

            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Parameters.AddWithValue("@KeyType", itemKey.GetType().FullName);
            sqlCommand.Parameters.AddWithValue("@SerializedKey", keyString);
            sqlCommand.Parameters.AddWithValue("@KeyHash", RFStringHelpers.QuickHash(keyString));
            sqlCommand.Parameters.AddWithValue("@Version", version);
            return(sqlCommand);
        }
Exemplo n.º 2
0
 public void LogProcess(object caller, RFProcessEntry p)
 {
     if (p != null)
     {
         try
         {
             using (var connection = new SqlConnection(_connectionString))
             {
                 connection.Open();
                 using (var insertCommand = new SqlCommand("INSERT INTO RIFF.ProcessLog( [Timestamp],[Hostname],[GraphName],[ProcessName],[Instance],[ValueDate],[IOTime],[ProcessingTime],[Success],[Message],[NumUpdates] ) VALUES " +
                                                           "( @Timestamp,@Hostname,@GraphName,@ProcessName,@Instance,@ValueDate,@IOTime,@ProcessingTime,@Success,@Message,@NumUpdates )", connection))
                 {
                     insertCommand.Parameters.AddWithValue("@Timestamp", new DateTimeOffset(DateTime.Now));
                     insertCommand.Parameters.AddWithValue("@Hostname", RFStringHelpers.StringToSQL(Environment.MachineName.ToLower(), false, 50, false));
                     insertCommand.Parameters.AddWithValue("@GraphName", RFStringHelpers.StringToSQL(p.GraphName, true, 50, false));
                     insertCommand.Parameters.AddWithValue("@ProcessName", RFStringHelpers.StringToSQL(p.ProcessName, false, 100, false));
                     insertCommand.Parameters.AddWithValue("@Instance", RFStringHelpers.StringToSQL(p.GraphInstance?.Name, true, 30, false));
                     insertCommand.Parameters.AddWithValue("@ValueDate", p.GraphInstance?.ValueDate?.Date ?? (object)DBNull.Value);
                     insertCommand.Parameters.AddWithValue("@IOTime", p.IOTime);
                     insertCommand.Parameters.AddWithValue("@ProcessingTime", p.ProcessingTime);
                     insertCommand.Parameters.AddWithValue("@Success", p.Success);
                     insertCommand.Parameters.AddWithValue("@Message", RFStringHelpers.StringToSQL(p.Message, true, 1014, true));
                     insertCommand.Parameters.AddWithValue("@NumUpdates", p.NumUpdates);
                     insertCommand.ExecuteNonQuery();
                 }
             }
         }
         catch (Exception ex)
         {
             Exception(this, ex, "Error logging in Process Log");
         }
     }
 }
Exemplo n.º 3
0
        protected virtual void PrepareSubject(LoggingEvent[] events)
        {
            var errors = events.Where(e => e.Level >= Level.Error);

            if (errors.Any())
            {
                var    evt = errors.First();
                string msg = evt.ExceptionObject == null ? evt.RenderedMessage : evt.ExceptionObject.Message;

                Subject = RFStringHelpers.Limit(string.Format("[{0}] {1}", evt.Level, msg), 125);

                if (errors.Count() > 1)
                {
                    Subject += $" (+{errors.Count() - 1})";
                }
            }
            else
            {
                Subject = "Errors";
            }

            if (Environment != null)
            {
                Subject = Environment + ": " + Subject;
            }
        }
Exemplo n.º 4
0
        public override RFCatalogKeyMetadata GetKeyMetadata(RFCatalogKey key)
        {
            var keyType   = key.GetType().FullName;
            var keyString = key.ToString();
            var keyHash   = RFStringHelpers.QuickHash(keyString);

            //Log.Debug(this, "GetKeyMetadata {0}", keyType);
            try
            {
                var dataTable = new DataTable();
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();

                    using (var getCommand = CreateCommand("[RIFF].[GetKeyMetadata]", connection))
                    {
                        getCommand.CommandType = CommandType.StoredProcedure;
                        getCommand.Parameters.AddWithValue("@KeyType", keyType);
                        getCommand.Parameters.AddWithValue("@SerializedKey", keyString);
                        getCommand.Parameters.AddWithValue("@KeyHash", keyHash);

                        using (var reader = getCommand.ExecuteReader(System.Data.CommandBehavior.SingleResult))
                        {
                            dataTable.Load(reader);
                        }
                    }
                }
                if (dataTable != null && dataTable.Rows != null && dataTable.Rows.Count > 0)
                {
                    var dataRow = dataTable.Rows[0];
                    return(new RFCatalogKeyMetadata
                    {
                        ContentType = dataRow["ContentType"].ToString(),
                        KeyType = dataRow["KeyType"].ToString(),
                        Key = RFXMLSerializer.DeserializeContract(dataRow["KeyType"].ToString(), dataRow["SerializedKey"].ToString()) as RFCatalogKey,
                        KeyReference = (long)dataRow["CatalogKeyID"],
                        Metadata = RFMetadata.Deserialize(dataRow["Metadata"].ToString()),
                        UpdateTime = (DateTimeOffset)dataRow["UpdateTime"],
                        IsValid = (bool)dataRow["IsValid"],
                        DataSize = (long)dataRow["DataSize"]
                    });
                }
            }
            catch (Exception ex)
            {
                Log.Exception(this, "Error retrieving key metadata", ex);
            }
            return(null);
        }
Exemplo n.º 5
0
 protected static RFUserLogEntry ExtractLogEntry(DataRow dataRow)
 {
     return(new RFUserLogEntry
     {
         Area = RFStringHelpers.StringFromSQL(dataRow["Area"]),
         Action = RFStringHelpers.StringFromSQL(dataRow["Action"]),
         Description = RFStringHelpers.StringFromSQL(dataRow["Description"]),
         Username = RFStringHelpers.StringFromSQL(dataRow["Username"]),
         Processor = RFStringHelpers.StringFromSQL(dataRow["Processor"]),
         Timestamp = (DateTimeOffset)dataRow["Timestamp"],
         ValueDate = dataRow["ValueDate"] == DBNull.Value ? RFDate.NullDate : new RFDate((DateTime)dataRow["ValueDate"]),
         KeyType = RFStringHelpers.StringFromSQL(dataRow["KeyType"]),
         KeyReference = dataRow["KeyReference"] == DBNull.Value ? 0 : (int)dataRow["KeyReference"],
         IsUserAction = (bool)dataRow["IsUserAction"],
         IsWarning = (bool)dataRow["IsWarning"]
     });
 }
Exemplo n.º 6
0
 public override string ToString()
 {
     if (CalendarDay.HasValue)
     {
         return(string.Format("{0}{1} day of the month {2}", CalendarDay.Value, RFStringHelpers.OrdinalSuffix(CalendarDay.Value), TimeZoneShort()).Trim());
     }
     if (WeekDay.HasValue)
     {
         return(string.Format("{0}{1} weekday of the month {2}", WeekDay.Value, RFStringHelpers.OrdinalSuffix(WeekDay.Value), TimeZoneShort()).Trim());
     }
     return("Monthly (?)");
 }
Exemplo n.º 7
0
        public override Dictionary <RFGraphInstance, RFCatalogKey> GetKeyInstances(RFCatalogKey key)
        {
            var    t       = key.GetType();
            var    keys    = new Dictionary <RFGraphInstance, RFCatalogKey>();
            string keyType = t.FullName;

            Log.Debug(this, "GetKeyInstances {0}", keyType);
            try
            {
                var dataTable = new DataTable();
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();

                    string getKeysSQL = "RIFF.GetKeyInstances";
                    using (var getCommand = CreateCommand(getKeysSQL, connection))
                    {
                        var rootHash = RFStringHelpers.QuickHash(key.RootKey().ToString());

                        getCommand.CommandType = CommandType.StoredProcedure;
                        getCommand.Parameters.AddWithValue("@KeyType", keyType);
                        getCommand.Parameters.AddWithValue("@SerializedKey", RFXMLSerializer.SerializeContract(key));
                        getCommand.Parameters.AddWithValue("@RootHash", rootHash);
                        using (var reader = getCommand.ExecuteReader(System.Data.CommandBehavior.SingleResult))
                        {
                            dataTable.Load(reader);
                        }
                    }
                }
                if (dataTable != null && dataTable.Rows != null && dataTable.Rows.Count > 0)
                {
                    // cache deserializer if key is explicit
                    foreach (DataRow dataRow in dataTable.Rows)
                    {
                        try
                        {
                            var catalogKeyID      = (long)dataRow["CatalogKeyID"];
                            var retrievedKeyType  = dataRow["KeyType"].ToString();
                            var serializedKey     = dataRow["SerializedKey"].ToString();
                            var graphInstanceName = dataRow["GraphInstanceName"].ToString();
                            var graphInstanceDate = new RFDate((int)dataRow["GraphInstanceDate"]);
                            var deserializedKey   = RFXMLSerializer.DeserializeContract(retrievedKeyType, serializedKey);

                            keys.Add(
                                new RFGraphInstance
                            {
                                Name      = graphInstanceName,
                                ValueDate = graphInstanceDate
                            },
                                deserializedKey as RFCatalogKey);
                        }
                        catch (Exception ex)
                        {
                            Log.Exception(this, ex, "Error deserializing key {0}", dataRow["SerializedKey"].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Exception(this, "Error retrieving key instances", ex);
            }

            return(keys);
        }
Exemplo n.º 8
0
        public override bool SaveItem(RFCatalogEntry item, bool overwrite = false)
        {
            if (item == null)
            {
                Log.Warning(this, "SaveItem with null");
                return(false);
            }

            if (item.Key.Plane == RFPlane.User)
            {
                //Log.Debug(this, "SaveItem {0}", entry.Key.ToString());
            }
            try
            {
                var serializedContent = (item is RFDocument && item.IsValid) ? SerializeContent((item as RFDocument).Content) : new byte[0];
                var compressedContent = CompressContent(serializedContent);
                var keyType           = item.Key.GetType().FullName;
                var keyString         = item.Key.ToString();
                var keyHash           = RFStringHelpers.QuickHash(keyString);
                var keyHashResource   = "KH" + keyHash;

                using (var scope = Transaction.Current == null ? new TransactionScope(_useTransactions ? TransactionScopeOption.Required : TransactionScopeOption.Suppress, new TransactionOptions
                {
                    IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromSeconds(30)
                }) : null)
                {
                    using (var connection = new SqlConnection(_connectionString))
                    {
                        connection.Open();

                        // acquire lock on the hash
                        string lockSQL   = "sp_getapplock";
                        string unlockSQL = "sp_releaseapplock @Resource = '" + keyHashResource + "';";
                        using (var lockCommand = new SqlCommand(lockSQL, connection))
                        {
                            lockCommand.CommandType = CommandType.StoredProcedure;
                            lockCommand.Parameters.AddWithValue("@Resource", keyHashResource);
                            lockCommand.Parameters.AddWithValue("@LockMode", "Exclusive");
                            lockCommand.Parameters.AddWithValue("@LockOwner", "Transaction");
                            var retValue = lockCommand.Parameters.Add("@ReturnVal", SqlDbType.Int);
                            retValue.Direction = ParameterDirection.ReturnValue;
                            //RFStatic.Log.Debug(this, "sp_getapplock called...");
                            lockCommand.ExecuteNonQuery();
                            if ((int)retValue.Value < 0)
                            {
                                Log.Error(this, "sp_getapplock returned {0}", retValue.Value);
                            }
                            //RFStatic.Log.Debug(this, "sp_getapplock returned {0}", retValue.Value);
                        }

                        try
                        {
                            // find or create existing key
                            long catalogKeyID = 0;
                            var  getKeySQL    = String.Format("SELECT [CatalogKeyID] FROM [RIFF].[CatalogKey] WHERE [KeyHash] = @KeyHash AND [KeyType] = @KeyType AND CAST([SerializedKey] AS VARCHAR({0})) = CAST(CAST(@SerializedKey AS XML) AS VARCHAR({0}))", _maxKeyLength);
                            if (!_trackKeyHash)
                            {
                                getKeySQL = String.Format("SELECT [CatalogKeyID] FROM [RIFF].[CatalogKey] WHERE [KeyType] = @KeyType AND CAST([SerializedKey] AS VARCHAR({0})) = CAST(CAST(@SerializedKey AS XML) AS VARCHAR({0}))", _maxKeyLength);
                            }
                            using (var getCommand = CreateCommand(getKeySQL, connection))
                            {
                                getCommand.Parameters.AddWithValue("@KeyType", keyType);
                                if (_trackKeyHash)
                                {
                                    getCommand.Parameters.AddWithValue("@KeyHash", keyHash);
                                }
                                getCommand.Parameters.AddWithValue("@SerializedKey", keyString);
                                var result = getCommand.ExecuteScalar();
                                if (result != null)
                                {
                                    catalogKeyID = (long)result;
                                }
                            }

                            if (catalogKeyID == 0)
                            {
                                string createKeySQL = "INSERT INTO [RIFF].[CatalogKey] ( [KeyType], [SerializedKey], [KeyHash], [RootHash], [FriendlyString] )"
                                                      + " VALUES ( @KeyType, @SerializedKey, @KeyHash, @RootHash, @FriendlyString ); SELECT SCOPE_IDENTITY()";
                                using (var createKeyCommand = CreateCommand(createKeySQL, connection))
                                {
                                    var rootHash = RFStringHelpers.QuickHash(item.Key.RootKey().ToString());

                                    createKeyCommand.Parameters.AddWithValue("@KeyType", keyType);
                                    createKeyCommand.Parameters.AddWithValue("@SerializedKey", keyString);
                                    createKeyCommand.Parameters.AddWithValue("@KeyHash", keyHash);
                                    createKeyCommand.Parameters.AddWithValue("@RootHash", rootHash);
                                    createKeyCommand.Parameters.AddWithValue("@FriendlyString", RFStringHelpers.StringToSQL(item.Key.FriendlyString(), true, 100, false));

                                    var result = createKeyCommand.ExecuteScalar();
                                    if (result != null)
                                    {
                                        catalogKeyID = (long)((decimal)result);
                                    }
                                }
                            }

                            if (catalogKeyID == 0)
                            {
                                throw new RFSystemException(this, "Unable to create new catalog key.");
                            }

                            // lookup any existing entries and calculate next version
                            int    version       = 1;
                            string getVersionSQL = "SELECT MAX([Version]) FROM [RIFF].[CatalogEntry] WHERE [CatalogKeyID] = @CatalogKeyID";
                            using (var getVersionCommand = CreateCommand(getVersionSQL, connection))
                            {
                                getVersionCommand.Parameters.AddWithValue("@CatalogKeyID", catalogKeyID);

                                var result = getVersionCommand.ExecuteScalar();
                                if (result != null && result != DBNull.Value)
                                {
                                    version = ((int)result) + 1;
                                }
                            }

                            // there is an existing document - compare content
                            if (version > 1)
                            {
                                long existingEntryID = 0;
                                using (var loadExistingCommand = LoadEntryCommand(item.Key, version - 1, connection))
                                {
                                    using (var reader = loadExistingCommand.ExecuteReader(System.Data.CommandBehavior.SingleResult))
                                    {
                                        var dataTable = new DataTable();
                                        dataTable.Load(reader);
                                        if (dataTable != null && dataTable.Rows != null && dataTable.Rows.Count == 1)
                                        {
                                            switch (item.Key.StoreType)
                                            {
                                            case RFStoreType.Document:
                                                existingEntryID = (long)dataTable.Rows[0]["CatalogEntryID"];
                                                try
                                                {
                                                    var existingType          = dataTable.Rows[0]["ContentType"].ToString();
                                                    var existingBinaryContent = dataTable.Rows[0]["BinaryContent"] as byte[];
                                                    var existingValid         = (bool)dataTable.Rows[0]["IsValid"];

                                                    // decompress binary content to avoid
                                                    // flagging update if only compression changed
                                                    if (existingBinaryContent != null && existingBinaryContent.Length > 0 && existingValid == item.IsValid)
                                                    {
                                                        var rawExistingContent = DecompressContent(existingBinaryContent);
                                                        if (Enumerable.SequenceEqual(serializedContent ?? new byte[0], rawExistingContent ?? new byte[0]))
                                                        {
                                                            //transaction.Rollback(); -- to avoid zombiecheck errors
                                                            if (item.Key.Plane == RFPlane.User)
                                                            {
                                                                Log.Info(this, "Not required to update {0}/{1}/{2}", item.Key.GetType().Name, item.Key.FriendlyString(), item.Key.GetInstance());
                                                            }
                                                            if (!_useTransactions)     // lock will be auto released on transaction which prevents other thread coming in before transaction is completed
                                                            {
                                                                using (var unlockCommand = new SqlCommand(unlockSQL, connection))
                                                                {
                                                                    unlockCommand.ExecuteNonQuery();
                                                                }
                                                            }
                                                            scope.Complete();
                                                            return(false);
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    Log.Exception(this, "Unable to compare to existing", ex);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (overwrite && existingEntryID > 0)
                                {
                                    // update content rather than create new version
                                    var    document          = item as RFDocument;
                                    string updateDocumentSQL = "UPDATE [RIFF].[CatalogDocument] SET [BinaryContent] = @BinaryContent, [ContentType] = @ContentType where [CatalogEntryID] = @CatalogEntryID";
                                    using (var updateDocumentCommand = CreateCommand(updateDocumentSQL, connection))
                                    {
                                        updateDocumentCommand.Parameters.AddWithValue("@CatalogEntryID", existingEntryID);
                                        updateDocumentCommand.Parameters.AddWithValue("@ContentType", document.Type);
                                        if (compressedContent == null || compressedContent.Length == 0)
                                        {
                                            updateDocumentCommand.Parameters.AddWithValue("@BinaryContent", new byte[0]);
                                        }
                                        else
                                        {
                                            updateDocumentCommand.Parameters.AddWithValue("@BinaryContent", compressedContent);
                                        }

                                        var affected = updateDocumentCommand.ExecuteNonQuery();
                                        if (affected != 1)
                                        {
                                            throw new RFSystemException(this, "Unable to update document.");
                                        }
                                    }
                                    string updateEntrySQL = "UPDATE [RIFF].[CatalogEntry] SET [UpdateTime] = @UpdateTime, [Metadata] = @Metadata, [IsValid] = @IsValid where [CatalogEntryID] = @CatalogEntryID";
                                    using (var updateEntryCommand = CreateCommand(updateEntrySQL, connection))
                                    {
                                        updateEntryCommand.Parameters.AddWithValue("@CatalogEntryID", existingEntryID);
                                        updateEntryCommand.Parameters.AddWithValue("@IsValid", item.IsValid);
                                        updateEntryCommand.Parameters.AddWithValue("@Metadata", item.Metadata != null ? ((object)item.Metadata.Serialize() ?? DBNull.Value) : DBNull.Value);
                                        updateEntryCommand.Parameters.AddWithValue("@UpdateTime", item.UpdateTime.Year < 1980 ? new DateTimeOffset(DateTime.Now) : item.UpdateTime);

                                        var affected = updateEntryCommand.ExecuteNonQuery();
                                        if (affected != 1)
                                        {
                                            throw new RFSystemException(this, "Unable to update entry.");
                                        }
                                    }
                                    if (item.Key.Plane == RFPlane.User)
                                    {
                                        Log.Debug(this, "Overwritten item {0}", item.Key.ToString());
                                    }
                                    if (!_useTransactions) // lock will be auto released on transaction which prevents other thread coming in before transaction is completed
                                    {
                                        using (var unlockCommand = new SqlCommand(unlockSQL, connection))
                                        {
                                            unlockCommand.ExecuteNonQuery();
                                        }
                                    }
                                    scope?.Complete();
                                    return(true);
                                }
                            }

                            // create entry
                            long   catalogEntryID = 0;
                            string createEntrySQL = "INSERT INTO [RIFF].[CatalogEntry] ( [CatalogKeyID], [Version], [Metadata], [IsValid], [UpdateTime] )" +
                                                    " VALUES (@CatalogKeyID, @Version, @Metadata, @IsValid, @UpdateTime); SELECT SCOPE_IDENTITY()";
                            using (var createEntryCommand = CreateCommand(createEntrySQL, connection))
                            {
                                createEntryCommand.Parameters.AddWithValue("@CatalogKeyID", catalogKeyID);
                                createEntryCommand.Parameters.AddWithValue("@Metadata", item.Metadata != null ? ((object)item.Metadata.Serialize() ?? DBNull.Value) : DBNull.Value);
                                createEntryCommand.Parameters.AddWithValue("@Version", version);
                                createEntryCommand.Parameters.AddWithValue("@IsValid", item.IsValid);
                                createEntryCommand.Parameters.AddWithValue("@UpdateTime", item.UpdateTime.Year < 1980 ? new DateTimeOffset(DateTime.Now) : item.UpdateTime);

                                var result = createEntryCommand.ExecuteScalar();
                                if (result != null && result != DBNull.Value)
                                {
                                    catalogEntryID = (long)((decimal)result);
                                }
                            }

                            if (catalogEntryID == 0)
                            {
                                throw new RFSystemException(this, "Unable to create new catalog entry.");
                            }

                            // create content
                            switch (item.Key.StoreType)
                            {
                            case RFStoreType.Document:
                            {
                                var    document          = item as RFDocument;
                                string createDocumentSQL = "INSERT INTO [RIFF].[CatalogDocument] ( [CatalogEntryID], [ContentType], [BinaryContent] ) VALUES ( @CatalogEntryID, @ContentType, @BinaryContent )";
                                using (var createDocumentCommand = CreateCommand(createDocumentSQL, connection))
                                {
                                    createDocumentCommand.Parameters.AddWithValue("@CatalogEntryID", catalogEntryID);
                                    createDocumentCommand.Parameters.AddWithValue("@ContentType", document.Type);
                                    if (compressedContent == null || compressedContent.Length == 0)
                                    {
                                        createDocumentCommand.Parameters.AddWithValue("@BinaryContent", new byte[0]);
                                    }
                                    else
                                    {
                                        createDocumentCommand.Parameters.AddWithValue("@BinaryContent", compressedContent);
                                    }

                                    var affected = createDocumentCommand.ExecuteNonQuery();
                                    if (affected != 1)
                                    {
                                        throw new RFSystemException(this, "Unable to create document.");
                                    }
                                }
                            }
                            break;

                            default:
                                throw new RFSystemException(this, "Unknown store type {0}", item.Key.StoreType);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Exception(this, ex, "Error saving entry (inner) {0}", item.Key);
                        }
                        if (!_useTransactions) // lock will be auto released on transaction which prevents other thread coming in before transaction is completed
                        {
                            using (var unlockCommand = new SqlCommand(unlockSQL, connection))
                            {
                                unlockCommand.ExecuteNonQuery();
                            }
                        }
                    }
                    if (scope != null)
                    {
                        scope.Complete();
                    }
                }
                if (item.Key.Plane == RFPlane.User)
                {
                    Log.Info(this, "Saved key {0}/{1}/{2}", item.Key.GetType().Name, item.Key.FriendlyString(), item.Key.GetInstance());
                }
                return(true);
            }
            catch (Exception ex)
            {
                Log.Exception(this, ex, "Error saving entry (outer) {0}", item.Key);
                return(false);
            }
        }
Exemplo n.º 9
0
        public List <RFProcessEntry> GetProcesses(RFDate?date = null, long logID = 0)
        {
            var logs = new List <RFProcessEntry>();

            try
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();
                    var getCommandSQL = "SELECT TOP 500 [LogID],[Timestamp],[Hostname],[GraphName],[ProcessName],[Instance],[ValueDate],[IOTime],[ProcessingTime],[Success],[Message],[NumUpdates] FROM [RIFF].[ProcessLog]";

                    if (date.HasValue)
                    {
                        DateTime valueDate = date.Value;
                        getCommandSQL = getCommandSQL + String.Format(" WHERE [Timestamp] >= '{0} 00:00:00' AND [Timestamp] < '{1}'", valueDate.ToString("yyyy-MM-dd"),
                                                                      valueDate.AddDays(1).ToString("yyyy-MM-dd"));
                    }
                    else if (logID > 0)
                    {
                        getCommandSQL = getCommandSQL + String.Format(" WHERE [LogID] = {0}", logID.ToString());
                    }
                    getCommandSQL = getCommandSQL + " ORDER BY [Timestamp] DESC";

                    using (var getCommand = new SqlCommand(getCommandSQL, connection))
                    {
                        using (var reader = getCommand.ExecuteReader(System.Data.CommandBehavior.SingleResult))
                        {
                            var dataTable = new DataTable();
                            dataTable.Load(reader);
                            if (dataTable != null && dataTable.Rows != null && dataTable.Rows.Count > 0)
                            {
                                foreach (DataRow dataRow in dataTable.Rows)
                                {
                                    try
                                    {
                                        logs.Add(new RFProcessEntry
                                        {
                                            LogID         = (long)dataRow["LogID"],
                                            Timestamp     = (DateTimeOffset)dataRow["Timestamp"],
                                            Message       = dataRow["Message"] != DBNull.Value ? dataRow["Message"].ToString() : String.Empty,
                                            GraphName     = RFStringHelpers.StringFromSQL(dataRow["GraphName"]),
                                            ProcessName   = RFStringHelpers.StringFromSQL(dataRow["ProcessName"]),
                                            GraphInstance = new RFGraphInstance
                                            {
                                                Name      = RFStringHelpers.StringFromSQL(dataRow["Instance"]),
                                                ValueDate = dataRow["ValueDate"] != DBNull.Value ? (RFDate?)new RFDate((DateTime)dataRow["ValueDate"]) : null
                                            },
                                            IOTime         = (int)dataRow["IOTime"],
                                            ProcessingTime = (int)dataRow["ProcessingTime"],
                                            NumUpdates     = (int)dataRow["NumUpdates"],
                                            Success        = (bool)dataRow["Success"]
                                        });
                                    }
                                    catch (Exception ex)
                                    {
                                        Exception(this, "Error retrieving process entry", ex);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exception(this, ex, "Error retrieving Process Log");
            }
            return(logs);
        }
Exemplo n.º 10
0
        public void LogEntry(RFUserLogEntry entry)
        {
            if (entry == null)
            {
                return;
            }
            if (!entry.Description.EndsWith(".", StringComparison.Ordinal))
            {
                entry.Description += "."; // settle once and for all
            }
            try
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();
                    try
                    {
                        string insertUserLogSQL = "INSERT INTO [RIFF].[UserLog] ( [Area], [Action], [Description], [Username], [Processor], [Timestamp], [KeyType], [KeyReference], [IsUserAction], [IsWarning], [ValueDate] ) VALUES ( @Area, @Action, @Description, @Username, @Processor, @Timestamp, @KeyType, @KeyReference, @IsUserAction, @IsWarning, @ValueDate )";
                        using (var insertUserLogCommand = new SqlCommand(insertUserLogSQL, connection))
                        {
                            insertUserLogCommand.Parameters.AddWithValue("@Area", RFStringHelpers.StringToSQL(entry.Area, false, 30, false));
                            insertUserLogCommand.Parameters.AddWithValue("@Action", RFStringHelpers.StringToSQL(entry.Action, false, 50, false));
                            insertUserLogCommand.Parameters.AddWithValue("@Description", RFStringHelpers.StringToSQL(entry.Description, false, 200, true));
                            insertUserLogCommand.Parameters.AddWithValue("@Username", RFStringHelpers.StringToSQL(entry.Username, true, 40, true));
                            insertUserLogCommand.Parameters.AddWithValue("@Processor", RFStringHelpers.StringToSQL(entry.Processor, true, 50, false));
                            insertUserLogCommand.Parameters.AddWithValue("@Timestamp", DateTimeOffset.Now);
                            insertUserLogCommand.Parameters.AddWithValue("@KeyType", RFStringHelpers.StringToSQL(entry.KeyType, true, 50, false));
                            if (entry.KeyReference > 0)
                            {
                                insertUserLogCommand.Parameters.AddWithValue("@KeyReference", entry.KeyReference);
                            }
                            else
                            {
                                insertUserLogCommand.Parameters.AddWithValue("@KeyReference", DBNull.Value);
                            }
                            if (entry.ValueDate != RFDate.NullDate)
                            {
                                insertUserLogCommand.Parameters.AddWithValue("@ValueDate", entry.ValueDate.Date);
                            }
                            else
                            {
                                insertUserLogCommand.Parameters.AddWithValue("@ValueDate", DBNull.Value);
                            }
                            insertUserLogCommand.Parameters.AddWithValue("@IsUserAction", entry.IsUserAction);
                            insertUserLogCommand.Parameters.AddWithValue("@IsWarning", entry.IsWarning);

                            var affected = insertUserLogCommand.ExecuteNonQuery();
                            if (affected != 1)
                            {
                                throw new RFSystemException(this, "Unable to log event in user log.");
                            }

                            if (entry.IsWarning)
                            {
                                try
                                {
                                    var emailTo = RFSettings.GetAppSetting("UserLogWarningsTo", null);
                                    if (!string.IsNullOrWhiteSpace(emailTo))
                                    {
                                        var emailFrom  = RFSettings.GetAppSetting("SmtpSender", "riff@localhost");
                                        var systemName = RFSettings.GetAppSetting("SystemName", "RIFF System");

                                        var message = new MailMessage();
                                        message.From = new MailAddress(emailFrom, systemName);
                                        foreach (var toAddress in emailTo.Split(',', ';').Select(s => s.Trim())
                                                 .Where(s => !string.IsNullOrWhiteSpace(s)).
                                                 Select(s => new MailAddress(s)))
                                        {
                                            message.To.Add(toAddress);
                                        }

                                        var bodyBuilder = new StringBuilder();
                                        bodyBuilder.Append("<html><body style=\"font-family: 'Helvetica Neue', 'Segoe UI', Helvetica, Verdana, sans-serif; font-size: 10pt;\">");
                                        bodyBuilder.AppendFormat("<p>A Warning was raised in {0}:</p>", systemName);
                                        bodyBuilder.Append("<blockquote><table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" style=\"font-family: 'Helvetica Neue', 'Segoe UI', Helvetica, Verdana, sans-serif; font-size: 10pt;\">");
                                        bodyBuilder.AppendFormat("<tr><td style=\"width: 100px;\">Message:</td><td style=\"font-weight: bold;\">{0}</td></tr>", System.Net.WebUtility.HtmlEncode(entry.Description));
                                        bodyBuilder.AppendFormat("<tr><td>Processor:</td><td>{0}</td></tr>", System.Net.WebUtility.HtmlEncode(entry.Processor ?? String.Empty));
                                        bodyBuilder.AppendFormat("<tr><td>Area:</td><td>{0}</td></tr>", System.Net.WebUtility.HtmlEncode(entry.Area));
                                        bodyBuilder.AppendFormat("<tr><td>Action:</td><td>{0}</td></tr>", System.Net.WebUtility.HtmlEncode(entry.Action));
                                        bodyBuilder.AppendFormat("<tr><td>Value Date:</td><td>{0}</td></tr>", entry.ValueDate == RFDate.NullDate ? String.Empty : entry.ValueDate.ToString("d MMM yyyy"));
                                        bodyBuilder.AppendFormat("<tr><td>Username:</td><td>{0}</td></tr>", System.Net.WebUtility.HtmlEncode(entry.Username ?? String.Empty));
                                        bodyBuilder.AppendFormat("<tr><td>Server:</td><td>{0}</td></tr>", Environment.MachineName);
                                        bodyBuilder.AppendFormat("<tr><td>Timestamp:</td><td>{0}</td></tr>", DateTimeOffset.Now.ToString("d MMM yyyy HH:mm:ss (zzz)"));
                                        bodyBuilder.Append("</table></blockquote></body></html>");

                                        var subject = String.Format("Warning: {0}", RFStringHelpers.Limit(entry.Description, 80)).Trim('.', '\r', '\n', ' ');
                                        if (subject.Contains('\r'))
                                        {
                                            subject = subject.Substring(0, subject.IndexOf('\r')).Trim('.', '\r', '\n', ' ') + " (+)";
                                        }
                                        if (subject.Contains('\n'))
                                        {
                                            subject = subject.Substring(0, subject.IndexOf('\n')).Trim('.', '\r', '\n', ' ') + " (+)";
                                        }
                                        message.Subject    = subject;
                                        message.Body       = bodyBuilder.ToString();
                                        message.IsBodyHtml = true;

                                        var smtp = new SmtpClient();
                                        smtp.Send(message);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _context.Log.Warning(this, "Unable to send UserLog warning via email: {0}", ex.Message);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _context.Log.Exception(this, "Error writing to user log (inner)", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                _context.Log.Exception(this, "Error writing to user log (outer)", ex);
            }
        }
Exemplo n.º 11
0
        private void Update(string dispatchKey, string processName, string instanceName, RFDate?valueDate, DispatchState state, long?weight, RFProcessingResult result, RFInstruction instruction)
        {
            try
            {
                using (var conn = new SqlConnection(_context.SystemConfig.DocumentStoreConnectionString))
                {
                    conn.Open();
                    using (var cmd = new SqlCommand("RIFF.UpdateDispatchQueue", conn))
                    {
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Environment", RFStringHelpers.StringToSQL(_context.SystemConfig.Environment, false, 10, false));
                        cmd.Parameters.AddWithValue("@ItemType", (int)ItemType.GraphProcessInstruction);
                        cmd.Parameters.AddWithValue("@DispatchKey", RFStringHelpers.StringToSQL(dispatchKey, false, 140, false));
                        cmd.Parameters.AddWithValue("@ProcessName", RFStringHelpers.StringToSQL(processName, true, 100, false));
                        cmd.Parameters.AddWithValue("@GraphInstance", RFStringHelpers.StringToSQL(instanceName, true, 20, false));
                        if (valueDate != null && valueDate.Value.IsValid())
                        {
                            cmd.Parameters.AddWithValue("@ValueDate", valueDate.Value.Date);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@ValueDate", DBNull.Value);
                        }
                        if (weight.HasValue)
                        {
                            cmd.Parameters.AddWithValue("@Weight", weight.Value);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@Weight", DBNull.Value);
                        }
                        cmd.Parameters.AddWithValue("@DispatchState", (int)state);
                        if (state == DispatchState.Started)
                        {
                            cmd.Parameters.AddWithValue("@LastStart", DateTimeOffset.Now);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@LastStart", DBNull.Value);
                        }
                        if (result?.Messages != null)
                        {
                            cmd.Parameters.AddWithValue("@Message", RFStringHelpers.StringToSQL(String.Join("|", result.Messages), true, 200, false));
                        }
                        else if (state == DispatchState.Finished || state == DispatchState.Skipped || state == DispatchState.Started)
                        {
                            cmd.Parameters.AddWithValue("@Message", String.Empty); // clear past error messages
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@Message", DBNull.Value);
                        }
                        if (result != null)
                        {
                            cmd.Parameters.AddWithValue("@ShouldRetry", result.ShouldRetry);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@ShouldRetry", false);
                        }
                        if (state == DispatchState.Queued && instruction != null)
                        {
                            cmd.Parameters.AddWithValue("@InstructionType", RFStringHelpers.StringToSQL(instruction.GetType().FullName, false, 200, false));
                            cmd.Parameters.AddWithValue("@InstructionContent", RFXMLSerializer.SerializeContract(instruction));
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@InstructionType", DBNull.Value);
                            cmd.Parameters.AddWithValue("@InstructionContent", DBNull.Value);
                        }

                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                _context.Log.Exception(this, "Error updating Dispatch Store", ex);
            }
        }