/// <summary> /// The default constructor. /// </summary> /// <param name="configuration">The application configuration.</param> public EncoderFactory(IConfigurationProvider configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); _configuration = configuration; }
private void CreateConnectionData(IConfigurationProvider configurationProvider) { string serviceBusConnectionString = configurationProvider.GetValue("serviceBusConnectionString"); if (string.IsNullOrWhiteSpace(serviceBusConnectionString)) { throw new ConfigurationErrorsException( "Configuration parameter 'serviceBusConnectionString' must be set to a valid Service Bus connection string"); } string eventHubName = configurationProvider.GetValue("eventHubName"); if (string.IsNullOrWhiteSpace(eventHubName)) { throw new ConfigurationErrorsException("Configuration parameter 'eventHubName' must not be empty"); } this.connectionData = new EventHubConnectionData(); this.connectionData.EventHubName = eventHubName; ServiceBusConnectionStringBuilder connStringBuilder = new ServiceBusConnectionStringBuilder(serviceBusConnectionString); connStringBuilder.TransportType = TransportType.Amqp; this.connectionData.MessagingFactories = new MessagingFactory[ConcurrentConnections]; for (uint i = 0; i < ConcurrentConnections; i++) { this.connectionData.MessagingFactories[i] = MessagingFactory.CreateFromConnectionString(connStringBuilder.ToString()); } }
public void Initialize() { if (sfs.Count != 0) { return; } log.Debug("Initialize new session factories reading the configuration."); foreach (Configuration cfg in mfc.Configure()) { var sf = (ISessionFactoryImplementor)cfg.BuildSessionFactory(); string sessionFactoryName = sf.Settings.SessionFactoryName; if (!string.IsNullOrEmpty(sessionFactoryName)) { sessionFactoryName = sessionFactoryName.Trim(); } else { throw new ArgumentException("The session-factory-id was not register; you must assign the name of the factory, example: <session-factory name='HereTheFactoryName'>"); } if (string.IsNullOrEmpty(defaultSessionFactoryName)) { defaultSessionFactoryName = sessionFactoryName; } sfs.Add(sessionFactoryName, sf); } mfc = null; // after built the SessionFactories the configuration is not needed }
public DobermanConfiguration(IConfigurationProvider configurationProvider) : this() { CheckMongo(configurationProvider.GetMongoConnectionString()); CheckEmail(configurationProvider.GetSmtpMailSettings()); CheckSql(configurationProvider.GetSqlConnectionString()); }
public Configuration(IConfigurationProvider configurationProvider) { if (configurationProvider == null) throw new ArgumentNullException("configurationProvider"); _configurationProvider = configurationProvider; }
public ConsoleViewModel( ISyncThingManager syncThingManager, IConfigurationProvider configurationProvider) { this.syncThingManager = syncThingManager; this.LogMessages = new Queue<string>(); // Display log messages 100ms after the previous message, or every 500ms if they're arriving thick and fast this.logMessagesBuffer = new Buffer<string>(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(500)); this.logMessagesBuffer.Delivered += (o, e) => { foreach (var message in e.Items) { this.LogMessages.Enqueue(message); if (this.LogMessages.Count > maxLogMessages) this.LogMessages.Dequeue(); } this.NotifyOfPropertyChange(() => this.LogMessages); }; this.syncThingManager.MessageLogged += (o, e) => { this.logMessagesBuffer.Add(e.LogMessage); }; }
public override void Arrange() { ConfigurationProvider = new ConfigurationProvider(@".\Configuration"); UnityContainerUnderTest = new UnityContainer(); UnityContainerUnderTest.LoadUnityConfiguration(ConfigurationProvider); }
public AutoMapperConfigurationStartupTask(IConfigurationProvider configurationProvider, IProfileExpression profileExpression, IMapCreator[] mapCreators) { if (configurationProvider == null) { throw new ArgumentNullException("configurationProvider"); } if (profileExpression == null) { throw new ArgumentNullException("profileExpression"); } if (mapCreators == null) { throw new ArgumentNullException("mapCreators"); } if (mapCreators.Length == 0) { throw new ArgumentException("Cannot be an empty array", "mapCreators"); } _configurationProvider = configurationProvider; _profileExpression = profileExpression; _mapCreators = mapCreators; }
public IotHubTransportFactory(ISerialize serializer, ILogger logger, IConfigurationProvider configurationProvider) { _serializer = serializer; _logger = logger; _configurationProvider = configurationProvider; }
public IDevice CreateDevice(ILogger logger, ITransportFactory transportFactory, ITelemetryFactory telemetryFactory, IConfigurationProvider configurationProvider, InitialDeviceConfig config) { var device = new DeviceBase(logger, transportFactory, telemetryFactory, configurationProvider); device.Init(config); return device; }
public ShippingMethodAdminService(IEnumerable<IShippingMethod> shippingMethods, UrlHelper urlHelper, IConfigurationProvider configurationProvider) { _shippingMethods = shippingMethods; _urlHelper = urlHelper; _configurationProvider = configurationProvider; }
public void ConfigureAuth(IAppBuilder app, IConfigurationProvider configProvider) { string aadClientId = configProvider.GetConfigurationSettingValue("ida.AADClientId"); string aadInstance = configProvider.GetConfigurationSettingValue("ida.AADInstance"); string aadTenant = configProvider.GetConfigurationSettingValue("ida.AADTenant"); string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, aadTenant); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = aadClientId, Authority = authority, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = context => { string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; context.ProtocolMessage.RedirectUri = appBaseUrl + "/"; context.HandleResponse(); context.Response.Redirect(context.ProtocolMessage.RedirectUri); return Task.FromResult(0); } } }); }
public ConflictResolutionViewModel( ISyncthingManager syncthingManager, IConflictFileManager conflictFileManager, IProcessStartProvider processStartProvider, IConflictFileWatcher conflictFileWatcher, IWindowManager windowManager, IConfigurationProvider configurationProvider) { this.syncthingManager = syncthingManager; this.conflictFileManager = conflictFileManager; this.processStartProvider = processStartProvider; this.conflictFileWatcher = conflictFileWatcher; this.configurationProvider = configurationProvider; this.windowManager = windowManager; this.DeleteToRecycleBin = this.configurationProvider.Load().ConflictResolverDeletesToRecycleBin; this.Bind(s => s.DeleteToRecycleBin, (o, e) => this.configurationProvider.AtomicLoadAndSave(c => c.ConflictResolverDeletesToRecycleBin = e.NewValue)); this.Conflicts.CollectionChanged += (o, e) => { if ((e.Action == NotifyCollectionChangedAction.Add && (e.OldItems?.Count ?? 0) == 0) || (e.Action == NotifyCollectionChangedAction.Remove && (e.NewItems?.Count ?? 0) == 0) || (e.Action == NotifyCollectionChangedAction.Reset)) { this.NotifyOfPropertyChange(nameof(this.Conflicts)); this.NotifyOfPropertyChange(nameof(this.IsLoadingAndNoConflictsFound)); this.NotifyOfPropertyChange(nameof(this.HasFinishedLoadingAndNoConflictsFound)); if (this.SelectedConflict == null && this.Conflicts.Count > 0) this.SelectedConflict = this.Conflicts[0]; } }; }
public SendGridEmailer(IConfigurationProvider configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); _smtp = SMTP.GenerateInstance(new NetworkCredential(configuration.SendGridUserName, configuration.SendGridPassword)); }
public IoTHubTransport(ISerialize serializer, ILogger logger, IConfigurationProvider configurationProvider, IDevice device) { _serializer = serializer; _logger = logger; _configurationProvider = configurationProvider; _device = device; }
public ViewerViewModel( IWindowManager windowManager, ISyncThingManager syncThingManager, IConfigurationProvider configurationProvider, IProcessStartProvider processStartProvider, IApplicationPathsProvider pathsProvider) { this.windowManager = windowManager; this.syncThingManager = syncThingManager; this.processStartProvider = processStartProvider; this.configurationProvider = configurationProvider; this.pathsProvider = pathsProvider; var configuration = this.configurationProvider.Load(); this.zoomLevel = configuration.SyncthingWebBrowserZoomLevel; this.syncThingManager.StateChanged += (o, e) => { this.syncThingState = e.NewState; this.RefreshBrowser(); }; this.callback = new JavascriptCallbackObject(this.OpenFolder); this.Bind(x => x.WebBrowser, (o, e) => { if (e.NewValue != null) this.InitializeBrowser(e.NewValue); }); this.SetCulture(configuration); configurationProvider.ConfigurationChanged += (o, e) => this.SetCulture(e.NewConfiguration); }
private void CreateContainer(HttpConfiguration configuration,IApplicationHost applicationHost,IConfigurationProvider configurationProvider) { var assemblies = applicationHost.Assemblies.ToArray(); var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterModelBinderProvider(); //containerBuilder.RegisterFilterProvider(); TODO: Seems to be an autofac MVC4 integration issue containerBuilder.RegisterModelBinders(assemblies); containerBuilder.RegisterApiControllers(assemblies); containerBuilder.RegisterControllers(assemblies); containerBuilder.RegisterWebApiFilterProvider(configuration); containerBuilder.RegisterWebApiModelBinders(assemblies); containerBuilder.RegisterModule(new AutofacWebTypesModule()); containerBuilder.RegisterAssemblyModules(assemblies); containerBuilder.RegisterAssemblyTypes(assemblies).Where(t => t.IsAssignableTo<IRouteProvider>()).As<IRouteProvider>(); containerBuilder.RegisterAssemblyTypes(assemblies).Where(t => t.IsAssignableTo<IBootTask>()).As<IBootTask>(); containerBuilder.RegisterAssemblyTypes(assemblies).Where(t => t.IsAssignableTo<AreaRegistration>()).As<AreaRegistration>(); containerBuilder.RegisterInstance(applicationHost).As<IApplicationHost>(); containerBuilder.RegisterInstance(configurationProvider).As<IConfigurationProvider>(); var container = containerBuilder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); SignalR.GlobalHost.DependencyResolver = new AutofacSignalRDependencyResolver(container); }
public PasswordRecoveryByResetLink(IAccountContext accountContext, IEmailSender eMailSender, ISystemContext systemContext, IConfigurationProvider configProvider) { this.accountContext = accountContext; this.eMailSender = eMailSender; this.systemContext = systemContext; this.configProvider = configProvider; }
public ReportService(ILog log, IConfigurationProvider configurationProvider, IScheduleProvider scheduleProvider, IReportGenerator reportGenerator) { _log = log; _configurationProvider = configurationProvider; _scheduleProvider = scheduleProvider; _reportGenerator = reportGenerator; }
private void CreateTableClient(IConfigurationProvider configurationProvider) { string accountConnectionString = configurationProvider.GetValue("StorageAccountConnectionString"); string sasToken = configurationProvider.GetValue("StorageAccountSasToken"); if (string.IsNullOrWhiteSpace(sasToken) && string.IsNullOrWhiteSpace(accountConnectionString)) { throw new ConfigurationErrorsException( "Configuration must specify either the storage account connection string ('StorageAccountConnectionString' parameter) or SAS token ('StorageAccountSasToken' paramteter)"); } string storageTableName = configurationProvider.GetValue("StorageTableName"); if (string.IsNullOrWhiteSpace(storageTableName)) { throw new ConfigurationErrorsException("Configuration must specify the target storage name ('storageTableName' parameter)"); } CloudStorageAccount storageAccount = string.IsNullOrWhiteSpace(sasToken) ? CloudStorageAccount.Parse(accountConnectionString) : new CloudStorageAccount(new StorageCredentials(sasToken), useHttps: true); this.cloudTable = storageAccount.CreateCloudTableClient().GetTableReference(storageTableName); try { this.cloudTable.CreateIfNotExists(); } catch (Exception e) { this.ReportListenerProblem("Could not ensure that destination Azure storage table exists" + Environment.NewLine + e.ToString()); throw; } }
/// <summary> /// Initializes a new instance of the TelemetryApiController class. /// </summary> /// <param name="deviceTelemetryLogic"> /// The IDeviceRegistryListLogic implementation that the new instance /// will use. /// </param> /// <param name="alertsLogic"> /// The IAlertsLogic implementation that the new instance will use. /// </param> /// <param name="deviceLogic"> /// The IDeviceLogic implementation that the new instance will use. /// </param> public TelemetryApiController( IDeviceTelemetryLogic deviceTelemetryLogic, IAlertsLogic alertsLogic, IDeviceLogic deviceLogic, IConfigurationProvider configProvider) { if (deviceTelemetryLogic == null) { throw new ArgumentNullException("deviceTelemetryLogic"); } if (alertsLogic == null) { throw new ArgumentNullException("alertsLogic"); } if(deviceLogic == null) { throw new ArgumentNullException("deviceLogic"); } if (configProvider == null) { throw new ArgumentNullException("configProvider"); } _deviceTelemetryLogic = deviceTelemetryLogic; _alertsLogic = alertsLogic; _deviceLogic = deviceLogic; _configProvider = configProvider; }
/// <summary> /// The default constructor. /// </summary> /// <param name="configuration">The application configuration.</param> public TabletHandbrakeEncoder(IConfigurationProvider configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); _tabletHandbrakeCommand = configuration.TabletHandbrakeCommand; }
protected override void InitializeConfigurationProvider(string sectionName, IConfigurationProvider provider) { StorageProviderData storageProviderData = GetStorageProviderData(sectionName); provider.ConfigurationName = storageProviderData.Name; ((IStorageProviderReader)provider).CurrentSectionName = sectionName; base.InitializeConfigurationProvider (sectionName, provider); }
public RabbitMqConfigurationSettings(IConfigurationProvider configurationProvider) { string host; if (false == configurationProvider.TryGetSetting("RabbitMQHost", out host)) throw new ConfigurationErrorsException("The RabbitMQHost was not configured"); string username; if (false == configurationProvider.TryGetSetting("RabbitMQUsername", out username)) throw new ConfigurationErrorsException("The RabbitMQUsername was not configured"); string password; if (false == configurationProvider.TryGetSetting("RabbitMQPassword", out password)) throw new ConfigurationErrorsException("The RabbitMQPassword was not configured"); Host = host; Username = username; Password = password; Heartbeat = (ushort)configurationProvider.GetSetting("RabbitMQHeartbeat", 30); Port = configurationProvider.GetSetting("RabbitMQPort", 5672); VirtualHost = configurationProvider.GetSetting("RabbitMQVirtualHost", ""); Options = configurationProvider.GetSetting("RabbitMQOptions", ""); HighAvailabilityQueuePrefix = configurationProvider.GetSetting("RabbitMQHAPrefix", ""); }
public AboutViewModel( IWindowManager windowManager, ISyncThingManager syncThingManager, IConfigurationProvider configurationProvider, IUpdateManager updateManager, Func<ThirdPartyComponentsViewModel> thirdPartyComponentsViewModelFactory, IProcessStartProvider processStartProvider) { this.windowManager = windowManager; this.syncThingManager = syncThingManager; this.updateManager = updateManager; this.thirdPartyComponentsViewModelFactory = thirdPartyComponentsViewModelFactory; this.processStartProvider = processStartProvider; this.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(3); this.HomepageUrl = Properties.Settings.Default.HomepageUrl; this.SyncthingVersion = this.syncThingManager.Version == null ? Resources.AboutView_UnknownVersion : this.syncThingManager.Version.Version; this.syncThingManager.DataLoaded += (o, e) => { this.SyncthingVersion = this.syncThingManager.Version == null ? Resources.AboutView_UnknownVersion : this.syncThingManager.Version.Version; }; this.CheckForNewerVersionAsync(); }
public DocDbRestHelper(IConfigurationProvider configProvider) { this._docDbEndpoint = configProvider.GetConfigurationSettingValue("docdb.EndpointUrl"); this._docDbKey = configProvider.GetConfigurationSettingValue("docdb.PrimaryAuthorizationKey"); this._dbName = configProvider.GetConfigurationSettingValue("docdb.DatabaseId"); this._collectionName = configProvider.GetConfigurationSettingValue("docdb.DocumentCollectionId"); }
public AssemblyByConfigurationBootstrap(IConfigurationProvider configurationProvider, ISessionProvider sessionProvider) { if (configurationProvider == null) throw new ArgumentNullException(nameof(configurationProvider)); if (sessionProvider == null) throw new ArgumentNullException(nameof(sessionProvider)); _configurationProvider = configurationProvider; _sessionProvider = sessionProvider; }
public Expression MapExpression(TypeMapRegistry typeMapRegistry, IConfigurationProvider configurationProvider, PropertyMap propertyMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) => typeMapRegistry.MapCollectionExpression(configurationProvider, propertyMap, sourceExpression, destExpression, contextExpression, CollectionMapperExtensions.IfNotNull, typeof(Dictionary<,>), CollectionMapperExtensions.MapItemExpr);
public UmbracoCodeGeneratorConfigurationProvider(string path) { using (var reader = File.OpenText(path)) { provider = new CodeGeneratorConfigurationProvider(reader.ReadToEnd()); } }
public TableStorageEventListener(IConfigurationProvider configurationProvider, IHealthReporter healthReporter) : base(configurationProvider, healthReporter) { if (this.Disabled) { return; } Debug.Assert(configurationProvider != null); this.CreateTableClient(configurationProvider); Random randomNumberGenerator = new Random(); this.instanceId = randomNumberGenerator.Next(100000000).ToString("D8"); this.nextEntityId = 0; this.identityIdResetLock = new object(); this.Sender = new ConcurrentEventSender<EventData>( eventBufferSize: 1000, maxConcurrency: MaxConcurrentPartitions, batchSize: 50, noEventsDelay: TimeSpan.FromMilliseconds(1000), transmitterProc: this.SendEventsAsync, healthReporter: healthReporter); }
public MemberAssignment Build(IConfigurationProvider configuration, PropertyMap propertyMap, TypeMap propertyTypeMap, ExpressionRequest request, ExpressionResolutionResult result, IDictionary <ExpressionRequest, int> typePairCount, LetPropertyMaps letPropertyMaps) { var defaultDestination = Activator.CreateInstance(propertyMap.DestinationType); return(Bind(propertyMap.DestinationMember, Coalesce(result.ResolutionExpression, Constant(defaultDestination)))); }
public static IQueryable <TResponse> ProjectTo <TResponse, TEntity>(this IQueryable <TEntity> query, IConfigurationProvider config, params string[] expandMembers) => expandMembers == null || expandMembers.Length == 0 ? query.ProjectTo <TResponse>(config) : query.ProjectTo <TResponse>(config, null, expandMembers);
public MappingTests(MappingTestsFixture fixture) { _configuration = fixture.ConfigurationProvider; _mapper = fixture.Mapper; }
public void RegisterProvider(IConfigurationProvider provider) { _configProviders.Add(provider); _configVersions.Add(0); }
public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, IMemberMap memberMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) => Expression.Call(null, MapMethodInfo.MakeGenericMethod(sourceExpression.Type, destExpression.Type), sourceExpression);
public QueryOrderBuilder(IConfigurationProvider config) : base(config) { // intentionally left blank }
public WcStats(ClusterServiceLocator clusterServiceLocator, IConfigurationProvider <ClusterConfiguration> configurationProvider) { _clusterServiceLocator = clusterServiceLocator; this.configurationProvider = configurationProvider; }
public async Task UnconfigureAsync(CommandSettings command) { ArgUtil.Equal(RunMode.Normal, HostContext.RunMode, nameof(HostContext.RunMode)); string currentAction = string.Empty; try { //stop, uninstall service and remove service config file if (_store.IsServiceConfigured()) { currentAction = StringUtil.Loc("UninstallingService"); _term.WriteLine(currentAction); #if OS_WINDOWS var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>(); serviceControlManager.UnconfigureService(); _term.WriteLine(StringUtil.Loc("Success") + currentAction); #elif OS_LINUX // unconfig system D service first throw new Exception(StringUtil.Loc("UnconfigureServiceDService")); #elif OS_OSX // unconfig osx service first throw new Exception(StringUtil.Loc("UnconfigureOSXService")); #endif } else { #if OS_WINDOWS //running as process, unconfigure autologon if it was configured if (_store.IsAutoLogonConfigured()) { currentAction = StringUtil.Loc("UnconfigAutologon"); _term.WriteLine(currentAction); var autoLogonConfigManager = HostContext.GetService <IAutoLogonManager>(); autoLogonConfigManager.Unconfigure(); _term.WriteLine(StringUtil.Loc("Success") + currentAction); } else { Trace.Info("AutoLogon was not configured on the agent."); } #endif } //delete agent from the server currentAction = StringUtil.Loc("UnregisteringAgent"); _term.WriteLine(currentAction); bool isConfigured = _store.IsConfigured(); bool hasCredentials = _store.HasCredentials(); if (isConfigured && hasCredentials) { AgentSettings settings = _store.GetSettings(); var credentialManager = HostContext.GetService <ICredentialManager>(); // Get the credentials var credProvider = GetCredentialProvider(command, settings.ServerUrl); VssCredentials creds = credProvider.GetVssCredentials(HostContext); Trace.Info("cred retrieved"); bool isDeploymentGroup = (settings.MachineGroupId > 0) || (settings.DeploymentGroupId > 0); Trace.Info("Agent configured for deploymentGroup : {0}", isDeploymentGroup.ToString()); string agentType = isDeploymentGroup ? Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration : Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration; var extensionManager = HostContext.GetService <IExtensionManager>(); IConfigurationProvider agentProvider = (extensionManager.GetExtensions <IConfigurationProvider>()).FirstOrDefault(x => x.ConfigurationProviderType == agentType); ArgUtil.NotNull(agentProvider, agentType); // Determine the service deployment type based on connection data. (Hosted/OnPremises) bool isHostedServer = await IsHostedServer(settings.ServerUrl, creds); await agentProvider.TestConnectionAsync(settings, creds, isHostedServer); TaskAgent agent = await agentProvider.GetAgentAsync(settings); if (agent == null) { _term.WriteLine(StringUtil.Loc("Skipping") + currentAction); } else { await agentProvider.DeleteAgentAsync(settings); _term.WriteLine(StringUtil.Loc("Success") + currentAction); } } else { _term.WriteLine(StringUtil.Loc("MissingConfig")); } //delete credential config files currentAction = StringUtil.Loc("DeletingCredentials"); _term.WriteLine(currentAction); if (hasCredentials) { _store.DeleteCredential(); var keyManager = HostContext.GetService <IRSAKeyManager>(); keyManager.DeleteKey(); _term.WriteLine(StringUtil.Loc("Success") + currentAction); } else { _term.WriteLine(StringUtil.Loc("Skipping") + currentAction); } //delete settings config file currentAction = StringUtil.Loc("DeletingSettings"); _term.WriteLine(currentAction); if (isConfigured) { // delete proxy setting (HostContext.GetService <IVstsAgentWebProxy>() as VstsAgentWebProxy).DeleteProxySetting(); // delete agent cert setting (HostContext.GetService <IAgentCertificateManager>() as AgentCertificateManager).DeleteCertificateSetting(); // delete agent runtime option _store.DeleteAgentRuntimeOptions(); _store.DeleteSettings(); _term.WriteLine(StringUtil.Loc("Success") + currentAction); } else { _term.WriteLine(StringUtil.Loc("Skipping") + currentAction); } } catch (Exception) { _term.WriteLine(StringUtil.Loc("Failed") + currentAction); throw; } }
public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, IMemberMap memberMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) => sourceExpression;
public async Task ConfigureAsync(CommandSettings command) { ArgUtil.Equal(RunMode.Normal, HostContext.RunMode, nameof(HostContext.RunMode)); Trace.Info(nameof(ConfigureAsync)); if (IsConfigured()) { throw new InvalidOperationException(StringUtil.Loc("AlreadyConfiguredError")); } // Populate proxy setting from commandline args var vstsProxy = HostContext.GetService <IVstsAgentWebProxy>(); bool saveProxySetting = false; string proxyUrl = command.GetProxyUrl(); if (!string.IsNullOrEmpty(proxyUrl)) { if (!Uri.IsWellFormedUriString(proxyUrl, UriKind.Absolute)) { throw new ArgumentOutOfRangeException(nameof(proxyUrl)); } Trace.Info("Reset proxy base on commandline args."); string proxyUserName = command.GetProxyUserName(); string proxyPassword = command.GetProxyPassword(); (vstsProxy as VstsAgentWebProxy).SetupProxy(proxyUrl, proxyUserName, proxyPassword); saveProxySetting = true; } // Populate cert setting from commandline args var agentCertManager = HostContext.GetService <IAgentCertificateManager>(); bool saveCertSetting = false; bool skipCertValidation = command.GetSkipCertificateValidation(); string caCert = command.GetCACertificate(); string clientCert = command.GetClientCertificate(); string clientCertKey = command.GetClientCertificatePrivateKey(); string clientCertArchive = command.GetClientCertificateArchrive(); string clientCertPassword = command.GetClientCertificatePassword(); // We require all Certificate files are under agent root. // So we can set ACL correctly when configure as service if (!string.IsNullOrEmpty(caCert)) { caCert = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), caCert); ArgUtil.File(caCert, nameof(caCert)); } if (!string.IsNullOrEmpty(clientCert) && !string.IsNullOrEmpty(clientCertKey) && !string.IsNullOrEmpty(clientCertArchive)) { // Ensure all client cert pieces are there. clientCert = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCert); clientCertKey = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCertKey); clientCertArchive = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCertArchive); ArgUtil.File(clientCert, nameof(clientCert)); ArgUtil.File(clientCertKey, nameof(clientCertKey)); ArgUtil.File(clientCertArchive, nameof(clientCertArchive)); } else if (!string.IsNullOrEmpty(clientCert) || !string.IsNullOrEmpty(clientCertKey) || !string.IsNullOrEmpty(clientCertArchive)) { // Print out which args are missing. ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCert, Constants.Agent.CommandLine.Args.SslClientCert); ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCertKey, Constants.Agent.CommandLine.Args.SslClientCertKey); ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCertArchive, Constants.Agent.CommandLine.Args.SslClientCertArchive); } if (skipCertValidation || !string.IsNullOrEmpty(caCert) || !string.IsNullOrEmpty(clientCert)) { Trace.Info("Reset agent cert setting base on commandline args."); (agentCertManager as AgentCertificateManager).SetupCertificate(skipCertValidation, caCert, clientCert, clientCertKey, clientCertArchive, clientCertPassword); saveCertSetting = true; } AgentSettings agentSettings = new AgentSettings(); // TEE EULA agentSettings.AcceptTeeEula = false; switch (Constants.Agent.Platform) { case Constants.OSPlatform.OSX: case Constants.OSPlatform.Linux: // Write the section header. WriteSection(StringUtil.Loc("EulasSectionHeader")); // Verify the EULA exists on disk in the expected location. string eulaFile = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), Constants.Path.TeeDirectory, "license.html"); ArgUtil.File(eulaFile, nameof(eulaFile)); // Write elaborate verbiage about the TEE EULA. _term.WriteLine(StringUtil.Loc("TeeEula", eulaFile)); _term.WriteLine(); // Prompt to acccept the TEE EULA. agentSettings.AcceptTeeEula = command.GetAcceptTeeEula(); break; case Constants.OSPlatform.Windows: // Warn and continue if .NET 4.6 is not installed. if (!NetFrameworkUtil.Test(new Version(4, 6), Trace)) { WriteSection(StringUtil.Loc("PrerequisitesSectionHeader")); // Section header. _term.WriteLine(StringUtil.Loc("MinimumNetFrameworkTfvc")); // Warning. } break; default: throw new NotSupportedException(); } // Create the configuration provider as per agent type. string agentType; if (command.DeploymentGroup) { agentType = Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration; } else if (command.DeploymentPool) { agentType = Constants.Agent.AgentConfigurationProvider.SharedDeploymentAgentConfiguration; } else { agentType = Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration; } var extensionManager = HostContext.GetService <IExtensionManager>(); IConfigurationProvider agentProvider = (extensionManager.GetExtensions <IConfigurationProvider>()) .FirstOrDefault(x => x.ConfigurationProviderType == agentType); ArgUtil.NotNull(agentProvider, agentType); bool isHostedServer = false; // Loop getting url and creds until you can connect ICredentialProvider credProvider = null; VssCredentials creds = null; WriteSection(StringUtil.Loc("ConnectSectionHeader")); while (true) { // Get the URL agentProvider.GetServerUrl(agentSettings, command); // Get the credentials credProvider = GetCredentialProvider(command, agentSettings.ServerUrl); creds = credProvider.GetVssCredentials(HostContext); Trace.Info("cred retrieved"); try { // Determine the service deployment type based on connection data. (Hosted/OnPremises) isHostedServer = await IsHostedServer(agentSettings.ServerUrl, creds); // Get the collection name for deployment group agentProvider.GetCollectionName(agentSettings, command, isHostedServer); // Validate can connect. await agentProvider.TestConnectionAsync(agentSettings, creds, isHostedServer); Trace.Info("Test Connection complete."); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("FailedToConnect")); } } _agentServer = HostContext.GetService <IAgentServer>(); // We want to use the native CSP of the platform for storage, so we use the RSACSP directly RSAParameters publicKey; var keyManager = HostContext.GetService <IRSAKeyManager>(); using (var rsa = keyManager.CreateKey()) { publicKey = rsa.ExportParameters(false); } // Loop getting agent name and pool name WriteSection(StringUtil.Loc("RegisterAgentSectionHeader")); while (true) { try { await agentProvider.GetPoolId(agentSettings, command); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(agentProvider.GetFailedToFindPoolErrorString()); } } TaskAgent agent; while (true) { agentSettings.AgentName = command.GetAgentName(); // Get the system capabilities. // TODO: Hook up to ctrl+c cancellation token. _term.WriteLine(StringUtil.Loc("ScanToolCapabilities")); Dictionary <string, string> systemCapabilities = await HostContext.GetService <ICapabilitiesManager>().GetCapabilitiesAsync(agentSettings, CancellationToken.None); _term.WriteLine(StringUtil.Loc("ConnectToServer")); agent = await agentProvider.GetAgentAsync(agentSettings); if (agent != null) { if (command.GetReplace()) { // Update existing agent with new PublicKey, agent version and SystemCapabilities. agent = UpdateExistingAgent(agent, publicKey, systemCapabilities); try { agent = await agentProvider.UpdateAgentAsync(agentSettings, agent, command); _term.WriteLine(StringUtil.Loc("AgentReplaced")); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("FailedToReplaceAgent")); } } else if (command.Unattended) { // if not replace and it is unattended config. agentProvider.ThrowTaskAgentExistException(agentSettings); } } else { // Create a new agent. agent = CreateNewAgent(agentSettings.AgentName, publicKey, systemCapabilities); try { agent = await agentProvider.AddAgentAsync(agentSettings, agent, command); _term.WriteLine(StringUtil.Loc("AgentAddedSuccessfully")); break; } catch (Exception e) when(!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("AddAgentFailed")); } } } // Add Agent Id to settings agentSettings.AgentId = agent.Id; // respect the serverUrl resolve by server. // in case of agent configured using collection url instead of account url. string agentServerUrl; if (agent.Properties.TryGetValidatedValue <string>("ServerUrl", out agentServerUrl) && !string.IsNullOrEmpty(agentServerUrl)) { Trace.Info($"Agent server url resolve by server: '{agentServerUrl}'."); // we need make sure the Schema/Host/Port component of the url remain the same. UriBuilder inputServerUrl = new UriBuilder(agentSettings.ServerUrl); UriBuilder serverReturnedServerUrl = new UriBuilder(agentServerUrl); if (Uri.Compare(inputServerUrl.Uri, serverReturnedServerUrl.Uri, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0) { inputServerUrl.Path = serverReturnedServerUrl.Path; Trace.Info($"Replace server returned url's scheme://host:port component with user input server url's scheme://host:port: '{inputServerUrl.Uri.AbsoluteUri}'."); agentSettings.ServerUrl = inputServerUrl.Uri.AbsoluteUri; } else { agentSettings.ServerUrl = agentServerUrl; } } // See if the server supports our OAuth key exchange for credentials if (agent.Authorization != null && agent.Authorization.ClientId != Guid.Empty && agent.Authorization.AuthorizationUrl != null) { // We use authorizationUrl as the oauth endpoint url by default. // For TFS, we need make sure the Schema/Host/Port component of the oauth endpoint url also match configuration url. (Incase of customer's agent configure URL and TFS server public URL are different) // Which means, we will keep use the original authorizationUrl in the VssOAuthJwtBearerClientCredential (authorizationUrl is the audience), // But might have different Url in VssOAuthCredential (connection url) // We can't do this for VSTS, since its SPS/TFS urls are different. UriBuilder configServerUrl = new UriBuilder(agentSettings.ServerUrl); UriBuilder oauthEndpointUrlBuilder = new UriBuilder(agent.Authorization.AuthorizationUrl); if (!isHostedServer && Uri.Compare(configServerUrl.Uri, oauthEndpointUrlBuilder.Uri, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0) { oauthEndpointUrlBuilder.Scheme = configServerUrl.Scheme; oauthEndpointUrlBuilder.Host = configServerUrl.Host; oauthEndpointUrlBuilder.Port = configServerUrl.Port; Trace.Info($"Set oauth endpoint url's scheme://host:port component to match agent configure url's scheme://host:port: '{oauthEndpointUrlBuilder.Uri.AbsoluteUri}'."); } var credentialData = new CredentialData { Scheme = Constants.Configuration.OAuth, Data = { { "clientId", agent.Authorization.ClientId.ToString("D") }, { "authorizationUrl", agent.Authorization.AuthorizationUrl.AbsoluteUri }, { "oauthEndpointUrl", oauthEndpointUrlBuilder.Uri.AbsoluteUri }, }, }; // Save the negotiated OAuth credential data _store.SaveCredential(credentialData); } else { switch (Constants.Agent.Platform) { case Constants.OSPlatform.OSX: case Constants.OSPlatform.Linux: // Save the provided admin cred for compat with previous agent. _store.SaveCredential(credProvider.CredentialData); break; case Constants.OSPlatform.Windows: // Not supported against TFS 2015. _term.WriteError(StringUtil.Loc("Tfs2015NotSupported")); return; default: throw new NotSupportedException(); } } // Testing agent connection, detect any protential connection issue, like local clock skew that cause OAuth token expired. _term.WriteLine(StringUtil.Loc("TestAgentConnection")); var credMgr = HostContext.GetService <ICredentialManager>(); VssCredentials credential = credMgr.LoadCredentials(); var agentSvr = HostContext.GetService <IAgentServer>(); try { await agentSvr.ConnectAsync(new Uri(agentSettings.ServerUrl), credential); } catch (VssOAuthTokenRequestException ex) when(ex.Message.Contains("Current server time is")) { // there are two exception messages server send that indicate clock skew. // 1. The bearer token expired on {jwt.ValidTo}. Current server time is {DateTime.UtcNow}. // 2. The bearer token is not valid until {jwt.ValidFrom}. Current server time is {DateTime.UtcNow}. Trace.Error("Catch exception during test agent connection."); Trace.Error(ex); throw new Exception(StringUtil.Loc("LocalClockSkewed")); } // We will Combine() what's stored with root. Defaults to string a relative path agentSettings.WorkFolder = command.GetWork(); // notificationPipeName for Hosted agent provisioner. agentSettings.NotificationPipeName = command.GetNotificationPipeName(); agentSettings.MonitorSocketAddress = command.GetMonitorSocketAddress(); agentSettings.NotificationSocketAddress = command.GetNotificationSocketAddress(); _store.SaveSettings(agentSettings); if (saveProxySetting) { Trace.Info("Save proxy setting to disk."); (vstsProxy as VstsAgentWebProxy).SaveProxySetting(); } if (saveCertSetting) { Trace.Info("Save agent cert setting to disk."); (agentCertManager as AgentCertificateManager).SaveCertificateSetting(); } _term.WriteLine(StringUtil.Loc("SavedSettings", DateTime.UtcNow)); bool saveRuntimeOptions = false; var runtimeOptions = new AgentRuntimeOptions(); #if OS_WINDOWS if (command.GitUseSChannel) { saveRuntimeOptions = true; runtimeOptions.GitUseSecureChannel = true; } #endif if (saveRuntimeOptions) { Trace.Info("Save agent runtime options to disk."); _store.SaveAgentRuntimeOptions(runtimeOptions); } #if OS_WINDOWS // config windows service bool runAsService = command.GetRunAsService(); if (runAsService) { Trace.Info("Configuring to run the agent as service"); var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>(); serviceControlManager.ConfigureService(agentSettings, command); } // config auto logon else if (command.GetRunAsAutoLogon()) { Trace.Info("Agent is going to run as process setting up the 'AutoLogon' capability for the agent."); var autoLogonConfigManager = HostContext.GetService <IAutoLogonManager>(); await autoLogonConfigManager.ConfigureAsync(command); //Important: The machine may restart if the autologon user is not same as the current user //if you are adding code after this, keep that in mind } #elif OS_LINUX || OS_OSX // generate service config script for OSX and Linux, GenerateScripts() will no-opt on windows. var serviceControlManager = HostContext.GetService <ILinuxServiceControlManager>(); serviceControlManager.GenerateScripts(agentSettings); #endif }
public Source(IConfigurationProvider configurationProvider) { this.configurationProvider = configurationProvider; }
public ProductRepository(DbContext dbDbContext, IConfigurationProvider configuration) : base(dbDbContext, configuration) { }
public MemberAssignment Build(IConfigurationProvider configuration, PropertyMap propertyMap, TypeMap propertyTypeMap, ExpressionRequest request, ExpressionResolutionResult result, IDictionary <ExpressionRequest, int> typePairCount, LetPropertyMaps letPropertyMaps) => BindAssignableExpression(propertyMap, result);
protected RepositoriesBaseClass() { dataContext = new Technology_SolutionsEntities(); mappingConfig = CreateMappingConfiguration(); mapper = mappingConfig.CreateMapper(); }
public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, IMemberMap memberMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) { return(Call(sourceExpression, typeof(object).GetDeclaredMethod("ToString"))); }
public Handler(SchoolContext db, IConfigurationProvider configuration) { _db = db; _configuration = configuration; }
public ExpressionBuilder(IConfigurationProvider configurationProvider) { _configurationProvider = configurationProvider; _expressionCache = new LockingConcurrentDictionary <ExpressionRequest, LambdaExpression>(CreateMapExpression); }
public QueryHandler(SchoolContext context, IConfigurationProvider configuration) { _context = context; _configuration = configuration; }
public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, PropertyMap propertyMap, Expression sourceExpression, Expression destExpression, Expression contextExpression) => MapCollectionExpression(configurationProvider, profileMap, propertyMap, Call(MembersDictionaryMethodInfo, sourceExpression, Constant(profileMap)), destExpression, contextExpression, _ => null, typeof(Dictionary <,>), MapKeyPairValueExpr);
public AuthorizationExecutor(IConfigurationProvider config, WridoAccessTokenProvider tokenProvider, ILogger logger) { _config = config.GetAppConfiguration(); _tokenProvider = tokenProvider; _logger = logger; }
public SamlMessageFactory(IConfigurationProvider configurationProvider) { _configurationProvider = configurationProvider; }
public ItemsController(FeedService feedService, IFeedsRepository feedRepository, ISubscribersRepository subscribersRepository, IdentityService identityService, IConfigurationProvider configurationProvider) { this.feedService = feedService; this.feedRepository = feedRepository; this.subscribersRepository = subscribersRepository; this.identityService = identityService; this.configurationProvider = configurationProvider; }
public static Task <List <TDestination> > ProjectToListAsync <TDestination>(this IQueryable queryable, IConfigurationProvider configuration) => queryable.ProjectTo <TDestination>(configuration).ToListAsync();
public VectorDb(IConfigurationProvider config) { _db = new RocksDbStore(config); }
public TestConfigurationSource(IConfigurationProvider provider) { _provider = provider; }
public RulesetScheduleProvider(IConfigurationProvider configurationProvider, IRepository <VersionSchedule> scheduleRepository) : this(configurationProvider.GetConfigurationAsync <BranchConfiguration>().GetAwaiter().GetResult().ActiveBranchId, scheduleRepository) { }
public IDataSource CreateSource(string typeName = "", IDataSource inSource = null, IConfigurationProvider configurationProvider = null) { return(AppAndDataHelpers.CreateSource(typeName, inSource, configurationProvider)); }
public string GetProxyXmlDocumentContent(OdcmModel model, IConfigurationProvider configurationProvider = null, IEnumerable <string> internalsVisibleTo = null) { var proxySources = GetProxySources(model, configurationProvider, internalsVisibleTo); return(GetXmlDocumentContent(ReferencedAssemblies, proxySources.Select(f => f.Contents).ToArray())); }
public MappingTest(MappingTestFixture mappingTestFixture) { _configurationProvider = mappingTestFixture.ConfigurationProvider; _mapper = mappingTestFixture.Mapper; }
public T CreateSource <T>(IDataSource inSource = null, IConfigurationProvider configurationProvider = null) { return(AppAndDataHelpers.CreateSource <T>(inSource, configurationProvider)); }