Ejemplo n.º 1
0
        public LoggerViewModel(IConfigManager config)
        {
            _selectedLogLevel = config.Get("enslaver", "debug", "Trace");
            var memoryTarget = LogManager.Configuration.AllTargets.FirstOrDefault(t => t.Name == "m1") as ObservableTarget;

            if (memoryTarget == null)
            {
                memoryTarget = new ObservableTarget
                {
                    Layout = new SimpleLayout("${longdate}|${level:uppercase=true}|${logger}|${message}")
                };
                LogManager.Configuration.AddTarget("m1", memoryTarget);
                var rule = new LoggingRule("*", LogLevel.Trace, memoryTarget);
                LogManager.Configuration.LoggingRules.Add(rule);
                LogManager.ReconfigExistingLoggers();
            }

            internalLogEvents = new ObservableCollection <LogEventInfo>();
            LogEvents         = new ObservableCollection <LogEventInfo>();

            this.ObservableForProperty(_ => _.SelectedLogLevel)
            .Select(_ => _.Value)
            .DistinctUntilChanged()
            .ObserveOnUI()
            .Subscribe(_ => FilterLogs());

            memoryTarget.WhenLogWrite
            .ObserveOnUI()
            .SubscribeOn(ThreadPoolScheduler.Instance)
            .Subscribe(l =>
            {
                if (internalLogEvents.Count > 2000)
                {
                    internalLogEvents.Clear();
                }
                internalLogEvents.Add(l);
                if (l.Level.Ordinal >= LogLevel.FromString(SelectedLogLevel).Ordinal)
                {
                    if (LogEvents.Count > 2000)
                    {
                        LogEvents.Clear();
                    }
                    LogEvents.Add(l);
                }
            });

            config.WhenConfigChanges
            .Throttle(TimeSpan.FromMilliseconds(200), ThreadPoolScheduler.Instance)
            .Where(p => p.Keys.Contains("enslaver_debug"))
            .DistinctUntilChanged()
            .ObserveOnUI()
            .Subscribe(p =>
            {
                SelectedLogLevel = config.Get("enslaver", "debug", SelectedLogLevel);
            });

            LogLevels = new List <string>(new[] { "Trace", "Debug", "Info", "Warn", "Error", "Fatal", "Off" });
            FilterLogs();
        }
Ejemplo n.º 2
0
        public IEnumerable <ApplicationUser> GetAdAccounts(string searchTerm = null)
        {
            var users = new List <ApplicationUser>();
            var numberOfSuggestions = _config.Get <int>(ConfigKeys.AdUsersSuggestionSize);

            using (var directoryEntry = new DirectoryEntry(
                       _config.Get <string>(ConfigKeys.ActiveDirectoryEntryPath),
                       _config.Get <string>(ConfigKeys.ActiveDirectoryUser),
                       _config.Get <string>(ConfigKeys.ActiveDirectoryPassword)))
            {
                using (var searcher = new DirectorySearcher(directoryEntry))
                {
                    searcher.PageSize = 10000;
                    searchTerm        = string.IsNullOrWhiteSpace(searchTerm) ? string.Empty : searchTerm + "*";

                    searcher.Filter = string.Format("(&(objectCategory=Person)(objectClass=user)(displayName=*{0})(!displayName=*System*)(!displayName=*Admin*))", searchTerm);

                    searcher.PropertiesToLoad.Add("samAccountName");
                    searcher.PropertiesToLoad.Add("displayName");
                    searcher.PropertiesToLoad.Add("mail");
                    searcher.PropertiesToLoad.Add("givenName");
                    searcher.PropertiesToLoad.Add("sn");

                    var results = searcher.FindAll();

                    for (int i = 0; i < results.Count; i++)
                    {
                        try
                        {
                            if (numberOfSuggestions > 0 && users.Count >= numberOfSuggestions)
                            {
                                break;
                            }

                            users.Add(new ApplicationUser
                            {
                                UserName    = results[i].Properties["samAccountName"][0].ToString(),
                                Email       = results[i].Properties["mail"][0].ToString(),
                                Forename    = results[i].Properties["givenName"][0].ToString(),
                                Surname     = results[i].Properties["sn"][0].ToString(),
                                DisplayName = results[i].Properties["displayName"][0].ToString()
                            });
                        }
                        catch (Exception)
                        {
                            //an account might not have email. hence index out of range exception will be throw
                            //safely ignore such accounts
                        }
                    }
                }
            }

            return(users);
        }
Ejemplo n.º 3
0
        public void Send(string from, string to, string subject, string body)
        {
            MailMessage message = new MailMessage(from, to);

            message.Subject = subject; //"Automated Email";
            message.Body    = body;    //@"Hi, You are received this as you exist in my contacts list.";
            var        serverName = _configManager.Get("yourservername");
            SmtpClient client     = new SmtpClient(_configManager.Get("yourservername"));

            client.UseDefaultCredentials = true;

            client.Send(message);
        }
Ejemplo n.º 4
0
 /// <summary>
 ///     Default construtor used by IoC builder.
 /// </summary>
 /// <param name="context">NetMQ context</param>
 /// <param name="logger">System logger</param>
 /// <param name="plugman">PluginManager</param>
 /// <param name="config"></param>
 public NyxHub(
     ILogger <NyxHub> logger,
     PluginManager plugman,
     IConfigManager config)
 {
     _serverCancelToken = _serverCancelationSource.Token;
     config.WhenConfigChanges.Where(m => m.Keys.Contains(HubConfigMultithread)).Subscribe(ConfigReload);
     _receiveMultithread = config.Get(HubConfigMultithread, false);
     _logger             = logger;
     _plugman            = plugman;
     _disposables.Add(NyxMessageStream.Subscribe(x =>
     {
         if (TotalInMessages == long.MaxValue)
         {
             TotalInMessages = 0;
         }
         TotalInMessages++;
     }));
     _disposables.Add(OutMessageStream.Subscribe(x =>
     {
         if (TotalInMessages == long.MaxValue)
         {
             TotalOutMessages = 0;
         }
         TotalOutMessages++;
     }));
 }
        public BuildsOverviewViewModel(IBuildsProvider buildsProvider, IProjectMapper projectMapper, IBuildsMapper buildsMapper, IConfigManager configManager)
        {
            _buildsProvider = buildsProvider;
            _projectMapper  = projectMapper;
            _buildsMapper   = buildsMapper;
            _configManager  = configManager;

            _serverConfig = _configManager.Get <DevOpsServerConfig>();
            _lastRefresh  = DateTimeOffset.Now - _serverConfig.AgeOfBuilds;

            BindingOperations.EnableCollectionSynchronization(Projects, _projectsLock);
            BindingOperations.EnableCollectionSynchronization(Builds, _buildLock);

            BuildsCollectionView = new ListCollectionView(Builds)
            {
                Filter           = FilterBuild,
                SortDescriptions =
                {
                    new SortDescription(nameof(BuildViewModel.ChangedAt), ListSortDirection.Descending)
                }
            };

            _buildRefreshTimer.Tick += BuildRefreshTimerTickHandler;

            _refreshTimePropertiesTimer.Interval = TimeSpan.FromSeconds(1);
            _refreshTimePropertiesTimer.Tick    += RefreshTimePropertiesTickHandler;
            _refreshTimePropertiesTimer.Start();
        }
Ejemplo n.º 6
0
        public string GetInstallationLicenceId()
        {
            var currentLicenceId = _configManager.Get(Properties.Settings.Default.SystemLicenceId);

            _log.Trace($"Installation licence Id resolved. Licence Id='{currentLicenceId}'");

            return(currentLicenceId);
        }
        public void Execute(object parameter)
        {
            var serverConfig = _configManager.Get <DevOpsServerConfig>();

            // this will trigger checking if the url is valid
            _configurationViewModel.DevOpsServerUrl     = serverConfig.Url;
            _configurationViewModel.SelectedRefreshTime = serverConfig.BuildRefreshTime;
            _configurationViewModel.SelectedBuildAge    = serverConfig.AgeOfBuilds;

            var autostartConfig = _configManager.Get <AutostartConfig>();

            _configurationViewModel.AutostartEnabled = autostartConfig.Enabled;
            _configurationViewModel.AutostartHidden  = autostartConfig.Hidden;


            // now switch to configuration page.
            _pageViewModel.CurrentPage = Page.Configuration;
            MainWindowViewModel.Instance.Show();
        }
Ejemplo n.º 8
0
        public MassTransitBus(List<BusConsumer> consumers )
        {
            _configManager = new RequiredConfigManager();
            _bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {

                cfg.Host(new Uri(_configManager.Get("Bus.Url")), h =>
                {
                    h.Username(_configManager.Get("Bus.UserName"));
                    h.Password(_configManager.Get("Bus.Password"));
                });

                foreach (BusConsumer consumer in consumers)
                {
                    cfg.ReceiveEndpoint(consumer.QueueName, consumer.ConsumerAction);
                }
            });

            _bus.Start();
        }
Ejemplo n.º 9
0
        public async Task SendEmail(EmailModel model)
        {
            var host     = _config.Get <string>(ConfigKeys.SmtpHost);
            var port     = _config.Get <int>(ConfigKeys.SmtpPort);
            var userName = _config.Get <string>(ConfigKeys.SmtpUserName);
            var password = _config.Get <string>(ConfigKeys.SmtpPassword);
            var ssl      = _config.Get <bool>(ConfigKeys.SmtpEnableSsl);

            var smtpClient = new SmtpClient(host, port);

            using (var mailMessage = new MailMessage(new MailAddress(model.From, model.SenderDisplayName), new MailAddress(model.Recipients.FirstOrDefault())))
            {
                mailMessage.Subject = model.Subject;
                //var emailBody = EmailTemplate.Replace("{0}", title).Replace("{1}", body);
                AlternateView item = AlternateView.CreateAlternateViewFromString(model.Body, null, "text/html");
                mailMessage.AlternateViews.Add(item);
                mailMessage.IsBodyHtml = true;

                if (model.CcRecipients != null && model.CcRecipients.Any())
                {
                    model.CcRecipients.ForEach(mailMessage.CC.Add);
                }
                if (!string.IsNullOrWhiteSpace(model.ReplyTo))
                {
                    mailMessage.ReplyToList.Add(model.ReplyTo);
                }
                if (model.Attachments != null && model.Attachments.Any())
                {
                    model.Attachments.ForEach(mailMessage.Attachments.Add);
                }

                smtpClient.UseDefaultCredentials = true;
                smtpClient.Credentials           = new System.Net.NetworkCredential(userName, password);
                smtpClient.EnableSsl             = ssl;
                smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtpClient.Timeout = 300000;

                await smtpClient.SendMailAsync(mailMessage);
            }
        }
Ejemplo n.º 10
0
        private void InitializeConfigs()
        {
            var globalConfigFile = Path.Combine(ConfigsDirectory, "global.hjson");

            if (!File.Exists(globalConfigFile))
            {
                configManager.SaveDefault <GlobalConfig>(globalConfigFile);
            }

            configManager.Load <GlobalConfig>("global", globalConfigFile);

            GlobalConfig = configManager.Get <GlobalConfig>("global");
        }
        public void Execute(object parameter)
        {
            if ((string)parameter == "OK")
            {
                var devOpsServerConfig = _configManager.Get <DevOpsServerConfig>();
                var urlChanged         = devOpsServerConfig.Url != _configurationViewModel.DevOpsServerUrl;
                var ageChanged         = devOpsServerConfig.AgeOfBuilds != _configurationViewModel.SelectedBuildAge;
                devOpsServerConfig.Url = _configurationViewModel.DevOpsServerUrl;
                devOpsServerConfig.BuildRefreshTime = _configurationViewModel.SelectedRefreshTime;
                devOpsServerConfig.AgeOfBuilds      = _configurationViewModel.SelectedBuildAge;

                var completeRefresh = urlChanged || ageChanged;
                _buildsOverviewViewModel.RestartTimer(completeRefresh);

                var autostartConfig = _configManager.Get <AutostartConfig>();
                autostartConfig.Enabled = _configurationViewModel.AutostartEnabled;
                autostartConfig.Hidden  = _configurationViewModel.AutostartHidden;
                AutoStartHelper.SetAutoStart(autostartConfig.Enabled, autostartConfig.Hidden);
            }

            _pageViewModel.CurrentPage = Page.Builds;
        }
Ejemplo n.º 12
0
        public ICollection <string> GetGlobalArgs()
        {
            ICollection <ConfigItem> configItems = _configManager.Get(ConfigurationType.Global);
            OrderedSet <string>      list        = new OrderedSet <string>();

            if (!CollectionUtils.IsNullOrEmpty(configItems))
            {
                foreach (ConfigItem configItem in configItems)
                {
                    list.Add(configItem.Id);
                }
            }
            return(list);
        }
Ejemplo n.º 13
0
        public TestControlsViewModel(
            INyxBorg borg,
            IConfigManager config
            )
        {
            PingCommand = ReactiveCommand.Create <object, Unit>(_ =>
            {
                for (int i = 0; i < PingCount; i++)
                {
                    borg.SendMessage(NyxMessage.Create("nyx", BasicHubAction.Ping, borg.NodeId));
                }
                return(Unit.Default);
            });

            SendActionCommand = ReactiveCommand.Create <object, Unit>(_ =>
            {
                borg.SendMessage(NyxMessage.Create(ActionTarget, ActionText, string.IsNullOrWhiteSpace(ActionSource) ? borg.NodeId : ActionSource));
                return(Unit.Default);
            });

            ConnectCommand = ReactiveCommand.Create <object, Unit>(_ =>
            {
                borg.Connect(ConnectionIp);
                return(Unit.Default);
            });

            _connectionIp = config.Get("borg_hubIp", "127.0.0.1");

            config.WhenConfigChanges
            .Throttle(TimeSpan.FromMilliseconds(200), ThreadPoolScheduler.Instance)
            .Where(k => k.Keys.Contains("borg_hubIp"))
            .Select(k => k.Sender.Get("borg_hubIp", "127.0.0.1"))
            .DistinctUntilChanged()
            .ObserveOnDispatcher()
            .Subscribe(s => ConnectionIp = s);

            borg.ConnectionStatusStream
            .ObserveOnDispatcher()
            .Subscribe(c =>
            {
                IsConnected = c.HasFlag(ConnectionStatus.Connected);
            });

            ValidActions = PluginManager.Instance
                           .GetExtensions()
                           .OfType <INyxMessageActions>()
                           .SelectMany(_ => _.SupportedActions).ToList();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MockConfig"/> class.
        /// </summary>
        public MockConfig()
        {
            Config.Get(Arg.Any <string>(), Arg.Any <string>()).Returns(FunGet);

            Config.When(x => x.Set(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>()))
            .Do(ActSet);


            Config.Set(Remote, Url, "http://dflink.sandbox.demandforced3.com");
            Config.Set(Remote, Login, "/servlet/dflogin");
            Config.Set(Remote, Details, "/servlet/details");
            Config.Set(Entitle, UserName, "*****@*****.**");
            Config.Set(Entitle, Password, AESEncryption.EncryptString("optondemand!1"));
            Config.Set(Entitle, Installid, "61D13359-C3A6-301C-8B17-9283A2188A9A");
            Config.Set(Entitle, Industry, "optometry");
        }
        public string Get()
        {
            var agentId = _configManager.Get("AgentId");

            // ReSharper disable once InvertIf
            if (string.IsNullOrEmpty(agentId))
            {
                agentId = _scanAgentIdGenerator.Generate();

                _configManager.Set("AgentId", agentId);

                _log.Info($"New Agent Id generated. Id='{agentId}'");
            }

            return(agentId);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Load directory path from config file
        /// if key-value doesn't exist, the default value is returned
        /// </summary>
        /// <param name="key"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private DirectoryInfo LoadDirectoryPath(string key, string name)
        {
            DirectoryInfo dir = null;

            _configs
            .Get <string>(key)
            .Some(path =>
            {
                dir = CreateDirectoryIfNew(path);
            })
            .None(() =>
            {
                dir = GetRootDirectory(name);
            });

            return(dir);
        }
Ejemplo n.º 17
0
        public async Task <IHttpActionResult> SendContactEmail(string fromName, string fromEmail, bool ccUser, string message)
        {
            try
            {
                var subject   = string.Format("Message from {0} to Shree Venkat", fromName);
                var bodyTitle = string.Format("Message from {0}", fromName);

                var template = await _email.GetTemplate("contact-us-template");

                var body = template.Replace("*|MC:TITLE|*", bodyTitle)
                           .Replace("*|MC:SUBJECT|*", subject)
                           .Replace("*|MC:EMAILTOBROWSERLINK|*", "http://www.ShreeVenkat.co.uk")
                           .Replace("{0}", fromName)
                           .Replace("{1}", fromEmail)
                           .Replace("{2}", message.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>"))
                           .Replace("*|CURRENT_YEAR|*", DateTime.Now.Year.ToString())
                           .Replace("*|LIST:COMPANY|*", "www.ShreeVenkat.co.uk");

                var shree = _config.Get <string>(ConfigKeys.SmtpUserName);

                var messageModel = new EmailModel
                {
                    From = shree,
                    SenderDisplayName = "Shree Venkat",
                    Recipients        = new List <string> {
                        shree
                    },
                    CcRecipients = (ccUser && !string.IsNullOrWhiteSpace(fromEmail) ? new List <string> {
                        fromEmail
                    } : null),
                    Subject      = subject,
                    Body         = body,
                    IsHtml       = true
                };

                await _email.SendEmail(messageModel);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(WebApiErrorHandler.Throw(ex));
            }
        }
        public string GetDirectory(bool writeToConfig = false)
        {
            var folderName = _configManager.Get(Settings.Default.PluginsFolderSettingName);

            if (!string.IsNullOrEmpty(folderName))
            {
                return(folderName);
            }

            var localPath = HttpContext.Current?.Server.MapPath("/Plugins");

            if (string.IsNullOrEmpty(localPath))
            {
                localPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
            }

            if (writeToConfig)
            {
                _configManager.Set(Settings.Default.PluginsFolderSettingName, localPath);
            }

            return(localPath);
        }
Ejemplo n.º 19
0
 /// <summary>
 ///     Load the configuration, or sets the defaults
 /// </summary>
 /// <param name="configChanged"></param>
 private void LoadConfig(ConfigChanged configChanged)
 {
     _lastHubIp           = _config.Get("borg", "hubIp", _lastHubIp);
     _port                = _config.Get("hub", "port", _port);
     _timeOut             = _config.Get("borg", "timeout", _timeOut);
     _keepAliveTimeOut    = _config.Get("borg", "keepAliveTimeOut", _keepAliveTimeOut);
     _timeOutRetries      = _config.Get("borg", "timeoutRetries", _timeOutRetries);
     _autoReconnect       = _config.Get("borg", "autoReconnect", _autoReconnect);
     _autostart           = _config.Get("borg", "autostart", _autostart);
     _dequeueOnFail       = _config.Get("borg", "dequeueOnFail", _dequeueOnFail);
     _clearQueueOnFail    = _config.Get("borg", "clearQueueOnFail", _clearQueueOnFail);
     _queueOnDisconnected = _config.Get("borg", "queueOnDisconnected", _queueOnDisconnected);
     _multithread         = _config.Get("borg", "experimentalmultithread", false);
     _maxFailedRetries    = _config.Get("borg", "maxFailedRetries", _maxFailedRetries);
 }
        private void InitializeAppConfig(IConfigManager manager)
        {
            var config = manager.Get<AppConfig>();
            if (config.Modules.Count > 1)
                throw new InvalidOperationException($@"Module {nameof(ConfigInitializerModule)} found other modules registered besides itself.");

            foreach (var module in ConfigInitializerModule.Modules)
            {
                var element = ModuleConfigElement.Create(module);
                if (ConfigInitializerModule.DisabledModules.Contains(module))
                    element.Status = ModuleStatus.Disabled;
                config.Modules.Add(element);
            }
        }
Ejemplo n.º 21
0
 private void ReloadConfig(ConfigChanged keys)
 {
     _hubPort   = _config.Get("hub", "port", 4015);
     _hubLastIp = _config.Get("borg", "hubIp", "127.0.0.1");
     _start     = _config.Get("hubdiscovery", "enabled", true);
 }
Ejemplo n.º 22
0
 /// <summary>
 /// 获取参数值
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key">对应的键</param>
 /// <returns></returns>
 public T Get <T>(string key)
 {
     return(_ConfigManager.Get <T>(key));
 }
Ejemplo n.º 23
0
 public void Execute()
 {
     _resources.Root   = _config.Get("ResourceRoot");
     _resources.Locale = _config.Get("Locale");
 }
Ejemplo n.º 24
0
 private void ReloadConfig(ConfigChanged message)
 {
     _extractPath = Environment.ExpandEnvironmentVariables(_config.Get("borg", "depot", _extractPath));
 }
Ejemplo n.º 25
0
 /// <summary>
 /// 获取默认的文件系统名字
 /// </summary>
 /// <returns>默认的文件系统名字</returns>
 protected override string GetDefaultName()
 {
     return(configManager == null ? "local" : configManager.Get().Get("filesystems.default", "local"));
 }