public void DeleteTableData() { using (SqlConnection dbConnection = new SqlConnection(configurationProvider.GetConfiguration(ConfigName.SqlConnectionString))) { dbConnection.Open(); // delete table data. using (SqlCommand deleteTable = dbConnection.CreateCommand()) { deleteTable.CommandText = "delete from externalinvestorexternalindustry"; deleteTable.CommandType = CommandType.Text; deleteTable.ExecuteNonQuery(); } using (SqlCommand deleteTable = dbConnection.CreateCommand()) { deleteTable.CommandText = "delete from externalinvestor"; deleteTable.CommandType = CommandType.Text; deleteTable.ExecuteNonQuery(); } using (SqlCommand deleteTable = dbConnection.CreateCommand()) { deleteTable.CommandText = "delete from externalindustry"; deleteTable.CommandType = CommandType.Text; deleteTable.ExecuteNonQuery(); } } }
/// <summary> /// Update /// </summary> /// <param name="customInfoBarMessage">Optional. If provided than this will be the message that will appear in info bar, otherwise a standard one will appear instead</param> private void UpdateRequired(string customInfoBarMessage = null) { this.AssertOnUIThread(); IInfoBarManager manager = this.host.GetMefService <IInfoBarManager>(); if (manager == null) { Debug.Fail("Cannot find IInfoBarManager"); return; } this.currentErrorWindowInfoBar = manager.AttachInfoBarWithButton( ErrorListToolWindowGuid, customInfoBarMessage ?? Strings.SonarLintInfoBarUnboundProjectsMessage, Strings.SonarLintInfoBarUpdateCommandText, KnownMonikers.RuleWarning); if (this.currentErrorWindowInfoBar == null) { this.OutputMessage(Strings.SonarLintFailedToAttachInfoBarToErrorList); Debug.Fail("Failed to add an info bar to the error list tool window"); } else { var componentModel = host.GetService <SComponentModel, IComponentModel>(); TelemetryLoggerAccessor.GetLogger(componentModel)?.ReportEvent(TelemetryEvent.ErrorListInfoBarShow); this.currentErrorWindowInfoBar.Closed += this.CurrentErrorWindowInfoBar_Closed; this.currentErrorWindowInfoBar.ButtonClick += this.CurrentErrorWindowInfoBar_ButtonClick; // Need to capture the current binding information since the user can change the binding // and running the Update should just no-op in that case. this.infoBarBinding = configProvider.GetConfiguration().Project; } }
public UserRepository( Func <string, IDatabase> databaseFactory, IConfigurationProvider configurationProvider) : base(databaseFactory) { _configuration = configurationProvider.GetConfiguration <RepositoryConfiguration>(); }
private Dictionary <string, string> CreateConfigDictionary(string json, string jsonFileName, IConfigurationProvider configProvider) { json = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, jsonFileName); configProvider = new ConfigurationFromConfigProvider(json); return(configProvider.GetConfiguration()); }
public void LoadConfiguration_Tests() { IConfigurationProvider provider = IocManager.Instance.IocContainer.Resolve <IConfigurationProvider>(); MongoDBConfig config = provider.GetConfiguration <MongoDBConfig>(); int i = 0; }
public void SetUp() { _ConfigurationProvider = Substitute.For <IConfigurationProvider>(); _ConfigurationProvider.GetConfiguration().Returns(new JObject()); _JsonSerializer = new JsonSerializer(); }
public WikipediaProvider(IConfigurationProvider configProvider, HttpClient httpClient, JsonSerializer serializer, ILogger logger) { _httpClient = httpClient; _serializer = serializer; _logger = logger; _config = configProvider.GetConfiguration <WikipediaPluginConfiguration>() ?? WikipediaPluginConfiguration.Fallback; }
public async void Execute() { while (true) { NotificationQueueEntity message = null; do { message = await queueProvider.DequeueAsync <NotificationQueueEntity>(configurationProvider.GetString("notificationsQueue")); if (message != null) { var users = await tableStorageProvider.RetrieveTableAsync <UserEntity>("users"); Parallel.ForEach(users, (user) => { var conversationReference = JsonConvert.DeserializeObject <ConversationReference>(user.ConversationReference); var client = new ConnectorClient(new Uri(conversationReference.ServiceUrl)); var messageActivity = Activity.CreateMessageActivity(); messageActivity.Conversation = new ConversationAccount(id: conversationReference.Conversation.Id); messageActivity.Recipient = new ChannelAccount(id: conversationReference.User.Id, name: conversationReference.User.Name); messageActivity.From = new ChannelAccount(id: conversationReference.Bot.Id, name: conversationReference.Bot.Name); messageActivity.ChannelId = conversationReference.ChannelId; messageActivity.Text = string.Format(messageProvider.GetMessage("NewNotification"), message.Text); client.Conversations.SendToConversation((Activity)messageActivity); }); } } while (message != null); Thread.Sleep(TimeSpan.FromMinutes(configurationProvider.GetConfiguration <int>("NotificationPollInterval"))); } }
public async void Execute() { while (true) { IssueQueueEntity message = null; do { var channels = await GetChannels(); if (channels.Any()) { message = await queueProvider.DequeueAsync <IssueQueueEntity>(configurationProvider.GetString("issueQueue")); if (message != null) { await tableStorageProvider.SendToTableAsync("openIssues", message); foreach (var channel in channels) { var messageActivity = Activity.CreateMessageActivity(); messageActivity.Type = ActivityTypes.Message; messageActivity.Text = string.Format(messageProvider.GetMessage("NewIssue"), message.Text); await channel.SendToChannel(messageActivity); } } } } while (message != null); Thread.Sleep(TimeSpan.FromMinutes(configurationProvider.GetConfiguration <int>("IssuePollInterval"))); } }
private static TemplateWriterSettings LoadSettingsForLanguage() { TemplateWriterSettings mainTWS = _configurationProvider.GetConfiguration <TemplateWriterSettings>(); if (targetLanguage != null) { mainTWS.TargetLanguage = targetLanguage; } if (properties != null) { mainTWS.Properties = properties; } mainTWS.DefaultBaseEndpointUrl = String.Format("https://graph.microsoft.com/{0}", endpointVersion); //Call the generic GetConfiguration method with our new type. var languageSettings = (_configurationProvider .GetType() .GetConstructor(new [] { typeof(string) }) .Invoke(new[] { targetLanguage }) as IConfigurationProvider) .GetConfiguration <TemplateWriterSettings>(); mainTWS.CopyLanguageSettings(languageSettings); return(mainTWS); }
public async void Execute() { while (true) { IEnumerable <StillInterestedEntity> messages = null; do { var day = DateTimeOffset.UtcNow.AddDays(-configurationProvider.GetConfiguration <int>("stillInterestedTimeoutDays")); TableQuery <StillInterestedEntity> tableQuery = new TableQuery <StillInterestedEntity>().Where(TableQuery.CombineFilters( TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.LessThanOrEqual, day), TableOperators.And, TableQuery.GenerateFilterConditionForBool("ReceivedAnswer", QueryComparisons.Equal, false))); messages = await tableStorageProvider.RetrieveFromTableAsync("stillInterested", tableQuery); if (messages.Any(x => !x.ReceivedAnswer)) { foreach (var message in messages.Where(x => !x.ReceivedAnswer)) { var conversationReference = JsonConvert.DeserializeObject <ConversationReference>(message.ConversationReference).GetPostToBotMessage(); var client = new ConnectorClient(new Uri(conversationReference.ServiceUrl)); using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, conversationReference)) { var botData = scope.Resolve <IBotData>(); await botData.LoadAsync(CancellationToken.None); var task = scope.Resolve <IDialogTask>(); //interrupt the stack var dialog = new StillInterestedDialog(message); task.Call(dialog.Void <object, IMessageActivity>(), null); await task.PollAsync(CancellationToken.None); //flush dialog stack await botData.FlushAsync(CancellationToken.None); } } await tableStorageProvider.DeleteFromTableAsync("stillInterested", messages); } } while (messages.Any()); Thread.Sleep(TimeSpan.FromHours(configurationProvider.GetConfiguration <int>("stillInterestedPollIntervalHours"))); } }
public void Start() { // Creating ping timer _mTimerPing = new Timer(Ping, null, 0, 15000); // Creating stats timer if (configurationProvider.GetConfiguration().StatsEnabled) { _mTimerStats = new Timer( _clusterServiceLocator.WcStats.GenerateStats, null, configurationProvider.GetConfiguration().StatsTimer, configurationProvider.GetConfiguration().StatsTimer); } // Creating CPU check timer _mTimerCpu = new Timer(_clusterServiceLocator.WcStats.CheckCpu, null, 1000, 1000); }
public void SaveConfiguration_Tests() { IConfigurationProvider provider = IocManager.Instance.IocContainer.Resolve <IConfigurationProvider>(); MongoDBConfig config = provider.GetConfiguration <MongoDBConfig>(); config.DatabaseName = "huang"; provider.SaveConfiguration(config); int i = 0; }
public EventRepository( Func <string, IDatabase> databaseFactory, IConfigurationProvider configurationProvider) : base(databaseFactory) { var configuration = configurationProvider.GetConfiguration <RepositoryConfiguration>(); DatabaseFileName = configuration.GeneralDatabaseFile; }
/// <summary> /// Attempts to provide a <see cref="Naninovel.Configuration"/> object of the provided type /// via <see cref="IConfigurationProvider"/> used to initialize the engine. /// </summary> /// <param name="type">Type of the requested configuration object.</param> public static Configuration GetConfiguration(Type type) { if (configurationProvider is null) { throw new Exception($"Failed to provide `{type.Name}` configuration object: Configuration provider is not available or the engine is not initialized."); } return(configurationProvider.GetConfiguration(type)); }
public async Task <IActionResult> GetByKey(string key) { try { var resp = await configurationProvider.GetConfiguration(key); return(Ok(resp)); } catch (Exception) { return(BadRequest()); } }
public async Task SynchronizeWithServer() { var bindingConfiguration = configurationProvider.GetConfiguration(); if (bindingConfiguration.Mode == SonarLintMode.Standalone) { logger.WriteLine(TaintResources.Synchronizer_NotInConnectedMode); ClearStore(); UpdateTaintIssuesUIContext(false); return; } if (!sonarQubeService.IsConnected) { logger.WriteLine(TaintResources.Synchronizer_ServerNotConnected); UpdateTaintIssuesUIContext(false); return; } try { var projectKey = bindingConfiguration.Project.ProjectKey; var taintVulnerabilities = await sonarQubeService.GetTaintVulnerabilitiesAsync(projectKey, CancellationToken.None); logger.WriteLine(TaintResources.Synchronizer_NumberOfServerIssues, taintVulnerabilities.Count); var hasTaintIssues = taintVulnerabilities.Count > 0; if (!hasTaintIssues) { ClearStore(); UpdateTaintIssuesUIContext(false); } else { var analysisInformation = await GetAnalysisInformation(projectKey); var taintIssueVizs = taintVulnerabilities.Select(converter.Convert).ToArray(); taintStore.Set(taintIssueVizs, analysisInformation); UpdateTaintIssuesUIContext(true); // We need the tool window content to exist so the issues are filtered and the // tool window caption is updated. See the "EnsureToolWindowExists" method comment // for more information. toolWindowService.EnsureToolWindowExists(TaintToolWindow.ToolWindowId); } } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { logger.WriteLine(TaintResources.Synchronizer_Failure, ex); ClearStore(); } }
public BindingConfiguration GetConfiguration() { var project = legacySerializer.ReadSolutionBinding(); if (project != null) { return(BindingConfiguration.CreateBoundConfiguration(project, isLegacy: true)); } return(wrappedProvider.GetConfiguration()); }
/// <summary> /// Initializes a new instance of the <see cref="WithPollingBuilder"/> class. /// </summary> /// <param name="configurationProvider">The configuration provider.</param> public WithPollingBuilder(IConfigurationProvider configurationProvider) { var defaultPollingConfiguration = configurationProvider.GetConfiguration().PollingConfiguration; this.PollingConfiguration = new PollingRequestConfiguration { Enabled = true, Interval = defaultPollingConfiguration.DefaultTimeInterval, Attempts = defaultPollingConfiguration.DefaultAttemptsCount }; }
public void Should_get_ServiceSettings_for_dev() { // Act var config = _sut.GetConfiguration <ServiceSettings>(EnvironmentType.Development); // Assert config.Should().NotBeNull(); config.ConnectionString.Should().Be("(localhost)/mssql"); config.Port.Should().Be(5600); config.EnableLogging.Should().BeFalse(); }
public MainForm(IConfigurationProvider configurationProvider) { _configuration = configurationProvider.GetConfiguration(); foreach (ServerConfigurationElement project in _configuration.Servers) _projects.Add(new SourceControlProject(_configuration, project.Id)); InitializeComponent(); ConfigureCommitNotifier(); ConfigureCheckUpdateTimer(); }
private static TemplateWriterSettings LoadSettingsForLanguage() { TemplateWriterSettings mainTWS = _configurationProvider.GetConfiguration <TemplateWriterSettings>(); if (targetLanguage != null) { mainTWS.TargetLanguage = targetLanguage; } if (properties != null) { mainTWS.Properties = properties; } mainTWS.DefaultBaseEndpointUrl = String.Format("https://graph.microsoft.com/{0}", endpointVersion); TemplateWriterSettings.mainSettingsObject = mainTWS; //First dynamically create a new class that holds settings for the target language //We store a reference on the default constructor to the mainTWS and then copy //all properties on it. var targetLanguageTypeName = mainTWS.TargetLanguage + "Settings"; var targetLanguageAN = new AssemblyName(targetLanguageTypeName); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(targetLanguageAN, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule"); TypeBuilder tb = moduleBuilder.DefineType(targetLanguageTypeName , TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout , typeof(TemplateWriterSettings)); ConstructorBuilder ctor = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); ILGenerator ctorIL = ctor.GetILGenerator(); ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Call, typeof(TemplateWriterSettings).GetConstructor(Type.EmptyTypes)); ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Call, typeof(TemplateWriterSettings).GetMethod("CopyPropertiesFromMainSettings")); ctorIL.Emit(OpCodes.Ret); Type targetLanguageType = tb.CreateType(); //Call the generic GetConfiguration method with our new type. return((TemplateWriterSettings)typeof(IConfigurationProvider) .GetMethod("GetConfiguration") .MakeGenericMethod(targetLanguageType) .Invoke(_configurationProvider, new object[] { })); }
public void ValueOrDefault_OfElementOfTheWrongType_ReturnsDefaultValue() { JObject obj = JObject.Parse("{ }"); _ConfigurationProvider.GetConfiguration().Returns(obj); var configuration = new RootConfiguration(_ConfigurationProvider, string.Empty, _JsonSerializer); var value = configuration.Element <string>().ValueOrDefault(); Assert.That(value, Is.Null); }
public MainForm(IConfigurationProvider configurationProvider) { _configuration = configurationProvider.GetConfiguration(); foreach (ServerConfigurationElement project in _configuration.Servers) { _projects.Add(new SourceControlProject(_configuration, project.Id)); } InitializeComponent(); ConfigureCommitNotifier(); ConfigureCheckUpdateTimer(); }
public void OnPacket(PacketClass p) { if (_socket is null) { throw new ApplicationException("socket is Null!"); } if (_clusterServiceLocator.WorldCluster.ClienTs is null) { throw new ApplicationException("Clients doesn't exist!"); } if (_clusterServiceLocator.WorldCluster.GetPacketHandlers() is null) { throw new ApplicationException("PacketHandler is empty!"); } ClientClass client = this; if (configurationProvider.GetConfiguration().PacketLogging) { ClientClass argclient = this; _clusterServiceLocator.Packets.LogPacket(p.Data, false, client); } if (!_clusterServiceLocator.WorldCluster.GetPacketHandlers().ContainsKey(p.OpCode)) { if (Character is null || !Character.IsInWorld) { _socket?.Dispose(); _socket?.Close(); _clusterServiceLocator.WorldCluster.Log.WriteLine(LogType.WARNING, "[{0}:{1}] Unknown Opcode 0x{2:X} [{2}], DataLen={4}", IP, Port, p.OpCode, Environment.NewLine, p.Length); _clusterServiceLocator.Packets.DumpPacket(p.Data, client); } else { try { Character.GetWorld.ClientPacket(Index, p.Data); } catch { _clusterServiceLocator.WcNetwork.WorldServer.Disconnect("NULL", new List <uint> { Character.Map }); } } }
public BindingConfiguration GetConfiguration() { var project = legacySerializer.ReadSolutionBinding(); if (project != null) { var config = BindingConfiguration.CreateBoundConfiguration(project, isLegacy: true); // Make sure the new config has the same value wrappedProvider.WriteConfiguration(config); return(config); } return(wrappedProvider.GetConfiguration()); }
// ReSharper disable once UnusedMember.Global // Called by the runtime public async Task Invoke(HttpContext context) { var config = _configurationProvider.GetConfiguration(context); // If there's no matching configuration, let the request through. if (config == null) { await _next(context); return; } var identityProvider = _configurationProvider.GetIdentityProvider(context); if (identityProvider == null) { await _next(context); return; } var identity = identityProvider.GetCurrentIdentity(); if (_strategy.ShouldAddHeaders(config)) { var headers = _strategy.GetResponseHeaders(identity, config); context.Response.OnStarting(() => { foreach (var header in headers) { context.Response.Headers.Add(header.Key, new StringValues(header.Value)); } return(Task.FromResult(0)); }); } if (_strategy.HasRemainingAllowance(identity, config)) { _strategy.ReduceAllowanceBy(identity, config); await _next(context); } else { context.Response.StatusCode = 429; } }
public async Task <SolverCheckResult> SendSolutionAsync(ISolver solver) { var serverConfiguration = _serverConfigurationProvider.GetConfiguration(); var userCongfiguration = _userCongfigurationProvider.GetConfiguration(); var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler { CookieContainer = cookieContainer }) using (var client = new HttpClient(handler) { BaseAddress = serverConfiguration.GetHost() }) { var loginUri = serverConfiguration.GetLoginUri(); var request = new HttpRequestMessage(HttpMethod.Get, loginUri); await client.SendAsync(request); var token = cookieContainer.GetCookies(loginUri)["csrftoken"]?.Value; request = new HttpRequestMessage(HttpMethod.Post, loginUri) { Content = new FormUrlEncodedContent(new Dictionary <string, string> { { "csrfmiddlewaretoken", token }, { "username", userCongfiguration.Username }, { "password", userCongfiguration.Password }, //{ "next", "/problems/fibo/dataset/" }, }) }; var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); var dataset = await GetDatasetAsync(client, serverConfiguration.GetDatasetUri(solver.Key)); var answer = await solver.SolveAsync(dataset); var code = await solver.GetSourceCodeAsync(); var isCorrect = await SendResultAsync(client, token, serverConfiguration.GetResultUri(solver.Key), answer, code); return(new SolverCheckResult(solver.Key, isCorrect, dataset, answer)); } }
public void ShowIssue(string issueKey) { if (string.IsNullOrEmpty(issueKey)) { throw new ArgumentNullException(nameof(issueKey)); } var bindingConfiguration = configurationProvider.GetConfiguration(); if (bindingConfiguration.Equals(BindingConfiguration.Standalone)) { return; } var projectKey = bindingConfiguration.Project.ProjectKey; var viewIssueUrl = sonarQubeService.GetViewIssueUrl(projectKey, issueKey); vsBrowserService.Navigate(viewIssueUrl.ToString()); }
private void LoadConfiguration() { Log.Debug("Starting Loading/Reloading Configuration"); try { Configuration = ConfigurationProvider.GetConfiguration(); } catch (ConfigurationErrorsException ex) { Configuration = null; Log.Error(ex.Message); return; } CheckLastQueryDate(); ConnectToLeanKit(); ConfigureDefaults(); Log.Debug("Finished Loading Configuration"); }
private string GetFailureMessage(Uri serverUri, string projectKey, string organizationKey) { var configuration = configurationProvider.GetConfiguration(); var isRequestForSonarCloud = !string.IsNullOrEmpty(organizationKey); var instructions = isRequestForSonarCloud ? string.Format(OpenInIDEResources.RequestValidator_Instructions_SonarCloud, serverUri, organizationKey, projectKey) : string.Format(OpenInIDEResources.RequestValidator_Instructions_SonarQube, serverUri, projectKey); if (configuration.Mode == SonarLintMode.Standalone) { return(string.Format(OpenInIDEResources.RequestValidator_InvalidState_NotInConnectedMode, instructions)); } if (IsCorrectServer(serverUri, configuration.Project.ServerUri) && IsCorrectOrganization() && IsCorrectSonarProject()) { return(null); } var currentConfiguration = isRequestForSonarCloud ? string.Format(OpenInIDEResources.RequestValidator_CurrentState_SonarCloud, configuration.Project.ServerUri, configuration.Project.Organization?.Key, configuration.Project.ProjectKey) : string.Format(OpenInIDEResources.RequestValidator_CurrentState_SonarQube, configuration.Project.ServerUri, configuration.Project.ProjectKey); return(string.Format(OpenInIDEResources.RequestValidator_InvalidState_WrongConnection, instructions, currentConfiguration)); bool IsCorrectOrganization() { return(string.IsNullOrEmpty(organizationKey) || organizationKey.Equals(configuration.Project.Organization?.Key, StringComparison.OrdinalIgnoreCase)); } bool IsCorrectSonarProject() { return(projectKey.Equals(configuration.Project.ProjectKey, StringComparison.OrdinalIgnoreCase)); } }