public RFServiceEnvironment(string environment, RFEngineDefinition config, string dbConnection)
        {
            _context = new RFComponentContext
            {
                CancellationTokenSource = new CancellationTokenSource(),
                Catalog      = null,
                UserConfig   = new RFCachedUserConfig(dbConnection, environment),
                SystemConfig = new RFSystemConfig
                {
                    Environment    = environment,
                    IntervalLength = config.IntervalSeconds * 1000,
                    ProcessingMode = RFProcessingMode.RFContinuous,
                    DocumentStoreConnectionString = dbConnection,
                    Downtime = RFSettings.GetDowntime()
                }
            };

            RFStatic.Log = new RFLog4NetLog(dbConnection);

            var engine = new RFSimpleEngine(config, _context);

            _context.Engine        = engine;
            _context.Catalog       = new RFSQLCatalog(_context);
            _context.UserLog       = new RFSQLUserLog(_context);
            _context.UserRole      = new RFSQLUserRole(dbConnection);
            _context.DispatchStore = new RFDispatchStoreSQL(_context);

            _workQueue = new RFGraphDispatchQueue(engine.GetWeights(), engine.GetDependencies(), engine.GetExclusiveProcesses(), _context);
            RFEnvironments.LogLicenseInfo(config);
        }
Exemplo n.º 2
0
        public RFDispatchQueueMonitorMSMQ(RFComponentContext context, IRFInstructionSink instructionSink, IRFEventSink eventSink, IRFDispatchQueue dispatchQueue)
            : base(context, instructionSink, eventSink, dispatchQueue)
        {
            var localSuffix = RIFF.Core.RFCore.sShortVersion;

            _workerThreadsCount = RFSettings.GetAppSetting("MSMQWorkerThreads", 4);
            _workerQueue        = GetOrCreateQueue("WorkerQueue_" + localSuffix, _context.SystemConfig.Environment);
            _eventQueue         = GetOrCreateQueue("EventQueue_" + localSuffix, _context.SystemConfig.Environment);
            _workerQueue.DefaultPropertiesToSend.ResponseQueue = _eventQueue;
            Log.Debug(this, "Using MSMQ Queues");
        }
        public override IRFSystemContext Start()
        {
            var useMSMQ = RFSettings.GetAppSetting("UseMSMQ", true);
            var manager = new RFDispatchQueueSink(_context, _workQueue);

            _workQueueMonitor = useMSMQ ? (RFDispatchQueueMonitorBase) new RFDispatchQueueMonitorMSMQ(_context, manager, manager, _workQueue) : (RFDispatchQueueMonitorBase) new RFDispatchQueueMonitorInProc(_context, manager, manager, _workQueue);
            _workQueueMonitor.StartThread();

            _processingContext = _context.GetProcessingContext(null, manager, manager, _workQueueMonitor);
            _context.Engine.Initialize(_processingContext);
            return(_processingContext); // this is the root environment (time triggers) which doesn't have a tracker
        }
Exemplo n.º 4
0
 public bool RequiresPermission(string username)
 {
     // check for global flag
     if (RFSettings.GetAppSetting("DisablePermissions", false))
     {
         return(false);
     }
     // or global admin
     if (GetPermissions(username, "All")
         .Any(p => p.Controller == "All" && p.Area == "All" && p.Permission == "All" && p.IsAllowed))
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 5
0
        public RFSQLCatalog(RFComponentContext context)
            : base(context)
        {
            _connectionString = context.SystemConfig.DocumentStoreConnectionString;
            if (_firstInit && _connectionString.NotBlank())
            {
                var sqlConnection = new SqlConnection(_connectionString);
                sqlConnection.Open();
                context.Log.Info(this, "Connected to SQL Server database [{0}] on server {1} (v{2}).", sqlConnection.Database, sqlConnection.DataSource, sqlConnection.ServerVersion);
                sqlConnection.Close();
                _firstInit = false;

                _useTransactions = RFSettings.GetAppSetting("UseTransactions", true);
                _trackKeyHash    = RFSettings.GetAppSetting("TrackKeyHash", true);
                _maxResults      = RFSettings.GetAppSetting("MaxResults", _maxResults);
                _commandTimeout  = RFSettings.GetAppSetting("CommandTimeout", _commandTimeout);
                _maxKeyLength    = RFSettings.GetAppSetting("MaxKeyLength", _maxKeyLength);

                context.Log.Debug(this, "UseTransactions: {0}, CommandTimeout: {1}s, KeyHash: {2}", _useTransactions, _commandTimeout, _trackKeyHash);
            }
        }
Exemplo n.º 6
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.º 7
0
        public static string GetUserName(System.Security.Principal.IPrincipal principal)
        {
            lock (_cahceLock)
            {
                if (_userNameCache.ContainsKey(principal.Identity.Name))
                {
                    return(_userNameCache[principal.Identity.Name]);
                }
            }
            if (principal != null && principal.Identity != null && !string.IsNullOrWhiteSpace(principal.Identity.Name))
            {
                var localUser = IsLocalUser(principal);
                if (!string.IsNullOrWhiteSpace(localUser))
                {
                    return(localUser);
                }
                else
                {
                    // try AD
                    try
                    {
                        var adRoot     = RFSettings.GetAppSetting("ActiveDomainRoot", null);
                        var adUsername = RFSettings.GetAppSetting("ActiveDomainUsername", null);
                        var adPassword = RFSettings.GetAppSetting("ActiveDomainPassword", null);
                        if (!string.IsNullOrWhiteSpace(adRoot))
                        {
                            PrincipalContext context = null;
                            if (!string.IsNullOrWhiteSpace(adUsername))
                            {
                                context = new PrincipalContext(ContextType.Domain, null, adRoot, adUsername, adPassword);
                            }
                            else
                            {
                                context = new PrincipalContext(ContextType.Domain, null, adRoot);
                            }

                            var user = UserPrincipal.FindByIdentity(context, principal.Identity.Name);
                            if (user != null)
                            {
                                var displayName = String.Format("{0} {1}", user.GivenName, user.Surname);
                                lock (_cahceLock)
                                {
                                    if (!_userNameCache.ContainsKey(principal.Identity.Name))
                                    {
                                        _userNameCache[principal.Identity.Name] = displayName;
                                    }
                                }
                                return(displayName);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        RFStatic.Log.Debug(typeof(RFUser), "Error retrieving username: {0}", ex.Message);
                    }
                }

                // fallback to NT username
                var name = principal.Identity.Name;
                if (name.Contains('\\'))
                {
                    name = name.Substring(name.IndexOf('\\') + 1);
                }
                // replace dots with spaces
                name = name.Replace('.', ' ');

                // remove underscore
                if (name.Contains('_'))
                {
                    name = name.Substring(0, name.IndexOf('_'));
                }

                return(name.ToLower());
            }
            return("guest");
        }