public SiteBuilderFactoryDispatcher(IDeploymentSettingsManager settingsManager, IBuildPropertyProvider propertyProvider, IEnvironment environment)
        {
            _settingsManager = settingsManager;

            _originalSiteBuilderFactory = new SiteBuilderFactory(settingsManager, propertyProvider, environment);
            _generatorSiteBuilderFactory = new Generator.SiteBuilderFactory(settingsManager, propertyProvider, environment);
        }
Beispiel #2
0
 public LibGit2SharpRepository(IEnvironment environment, IDeploymentSettingsManager settings, ITraceFactory tracerFactory)
 {
     _tracerFactory = tracerFactory;
     _settings = settings;
     RepositoryPath = environment.RepositoryPath;
     _legacyGitExeRepository = new GitExeRepository(environment, settings, tracerFactory);
 }
Beispiel #3
0
        public virtual IDynamic Call(IEnvironment environment, IDynamic thisBinding, IArgs args)
        {
            var oldContext = environment.Context;
            var newEnvironment = Scope.NewDeclarativeEnvironment();
            using (var newContext = environment.EnterContext())
            {
                newContext.LexicalEnviroment = newEnvironment;
                newContext.VariableEnviroment = newEnvironment;
                newContext.Strict = ExecutableCode.Strict;
                if (ExecutableCode.Strict)
                {
                    newContext.ThisBinding = thisBinding;
                }
                else
                {
                    switch (thisBinding.TypeCode)
                    {
                        case LanguageTypeCode.Undefined:
                        case LanguageTypeCode.Null:
                            newContext.ThisBinding = Environment.GlobalObject;
                            break;
                        default:
                            newContext.ThisBinding = thisBinding.ConvertToObject();
                            break;
                    }
                }

                BindFormalParameters(args);
                Environment.BindFunctionDeclarations(ExecutableCode.FunctionDeclarations, ExecutableCode.Strict, true);
                BindArgumentsObject(args);
                Environment.BindVariableDeclarations(ExecutableCode.VariableDeclarations, ExecutableCode.Strict, true);
                return ExecutableCode.Code(environment, args);
            }
        }
Beispiel #4
0
        IHost IIsolator.Build(IEnvironment environment)
        {
            var domainName = _options.DomainName ?? Guid.NewGuid().ToString();
            var strongName = typeof (Jail).Assembly.Evidence.GetHostEvidence<StrongName>();

            var domain = System.AppDomain.CreateDomain(domainName, null, _options.Setup, _options.Permissions, strongName, typeof(object).Assembly.Evidence.GetHostEvidence<StrongName>());

            var host = (AppDomainHost) Activator.CreateInstanceFrom(domain,
                typeof (AppDomainHost).Assembly.CodeBase,
                typeof (AppDomainHost).FullName)
                .Unwrap();

            host.AddAssembly(typeof (Jail).Assembly.GetName());

            foreach (var registration in environment.GetRegistrations())
            {
                if (registration is AssemblyName)
                {
                    host.AddAssembly((AssemblyName) registration);
                }
                else if (registration is InMemoryAssembly)
                {
                    host.AddAssembly((InMemoryAssembly) registration);
                }
            }

            return host;
        }
        public SessionHandler(ILogger<SessionHandler> logger,
            IEnvironment environment,
            IFileSystem fileSystem,
            IKeyValueStore keyValueStore,
            IMessageBus messageBus,
            ISession session,
            ITorrentInfoRepository torrentInfoRepository,
            ITorrentMetadataRepository metadataRepository)
        {
            if (logger == null) throw new ArgumentNullException("logger");
            if (environment == null) throw new ArgumentNullException("environment");
            if (fileSystem == null) throw new ArgumentNullException("fileSystem");
            if (keyValueStore == null) throw new ArgumentNullException("keyValueStore");
            if (messageBus == null) throw new ArgumentNullException("messageBus");
            if (session == null) throw new ArgumentNullException("session");
            if (torrentInfoRepository == null) throw new ArgumentNullException("torrentInfoRepository");
            if (metadataRepository == null) throw new ArgumentNullException("metadataRepository");

            _logger = logger;
            _environment = environment;
            _fileSystem = fileSystem;
            _keyValueStore = keyValueStore;
            _messageBus = messageBus;
            _session = session;
            _torrentInfoRepository = torrentInfoRepository;
            _metadataRepository = metadataRepository;
            _muted = new List<string>();
            _alertsThread = new Thread(ReadAlerts);
        }
 public DeploymentStatusManager(IEnvironment environment,
                                IFileSystem fileSystem)
 {
     _environment = environment;
     _fileSystem = fileSystem;
     _activeFile = Path.Combine(environment.DeploymentCachePath, Constants.ActiveDeploymentFile);
 }
        public ExternalCommandFactory(IEnvironment environment, IDeploymentSettingsManager settings, string repositoryPath)
        {
            _environment = environment;

            _deploymentSettings = settings;
            _repositoryPath = repositoryPath;
        }
        // Return a list of folders that need to be on the %PATH%
        public virtual List<string> GetPathFolders(IEnvironment environment)
        {
            // Add the msbuild path and git path to the %PATH% so more tools are available
            var toolsPaths = new List<string> {
                environment.DeploymentToolsPath, // Add /site/deployments/tools to the path to allow users to drop tools in there
                environment.ScriptPath,
                Path.GetDirectoryName(ResolveMSBuildPath()),
                Path.GetDirectoryName(ResolveGitPath()),
                Path.GetDirectoryName(ResolveVsTestPath()),
                Path.GetDirectoryName(ResolveSQLCmdPath()),
                Path.GetDirectoryName(ResolveFSharpCPath())
            };

            toolsPaths.AddRange(ResolveGitToolPaths());
            toolsPaths.AddRange(ResolveNodeNpmPaths());
            toolsPaths.Add(ResolveNpmGlobalPrefix());

            toolsPaths.AddRange(new[]
            {
                ResolveBowerPath(),
                ResolveGruntPath(),
                ResolveGulpPath()
            }.Where(p => !String.IsNullOrEmpty(p)).Select(Path.GetDirectoryName));

            return toolsPaths;
        }
 public HGeneratorIterator(IEnvironment environment, Generator generator, ReadOnlyList<string> variableDeclarations, ILexicalEnvironment scope)
     : base(environment)
 {
     Generator = generator;
     VariableDeclarations = variableDeclarations;
     Scope = scope;
 }
 public override IDynamic CreateIterator(IEnvironment environment, IArgs args)
 {
     var scope = Scope.NewDeclarativeEnvironment();
     var generator = new Generator(new GeneratorSteps(Steps));
     var iterator = new HGeneratorIterator(environment, generator, VariableDeclarations, scope);
     return iterator;
 }
        public static void MyClassInitialize(TestContext testContext)
        {
            ObjectFactory.Inject<IEnvironment>(new Environment());
            ObjectFactory.Inject<IDatabaseConnection>(new DatabaseConnection());

            _environment = ObjectFactory.GetInstance<IEnvironment>();
        }
Beispiel #12
0
        private static void OldRunsCleanup(string jobName, IFileSystem fileSystem, IEnvironment environment, ITraceFactory traceFactory, IDeploymentSettingsManager settings)
        {
            // if max is 5 and we have 5 we still want to remove one to make room for the next
            // that's why we decrement max value by 1
            int maxRuns = settings.GetMaxJobRunsHistoryCount() - 1;

            string historyPath = Path.Combine(environment.JobsDataPath, Constants.TriggeredPath, jobName);
            DirectoryInfoBase historyDirectory = fileSystem.DirectoryInfo.FromDirectoryName(historyPath);
            if (!historyDirectory.Exists)
            {
                return;
            }

            DirectoryInfoBase[] historyRunsDirectories = historyDirectory.GetDirectories();
            if (historyRunsDirectories.Length <= maxRuns)
            {
                return;
            }

            var directoriesToRemove = historyRunsDirectories.OrderByDescending(d => d.Name).Skip(maxRuns);
            foreach (DirectoryInfoBase directory in directoriesToRemove)
            {
                try
                {
                    directory.Delete(true);
                }
                catch (Exception ex)
                {
                    traceFactory.GetTracer().TraceError(ex);
                }
            }
        }
 public HGeneratorIterable(IEnvironment environment, ReadOnlyList<GeneratorStep> steps, ReadOnlyList<string> variableDeclarations, ILexicalEnvironment scope)
     : base(environment)
 {
     Steps = steps;
     VariableDeclarations = variableDeclarations;
     Scope = scope;
 }
Beispiel #14
0
 public void SetHomePath(IEnvironment environment)
 {
     if (!String.IsNullOrEmpty(environment.RootPath))
     {
         SetHomePath(environment.RootPath);
     }
 }
Beispiel #15
0
 public AppVeyor(Logger logger, IEnvironment environment, IHttpClientFactory httpClientFactory)
 {
     _logger = logger;
     _environment = environment;
     _httpClientFactory = httpClientFactory;
     _appVeyorApiUrl = _environment.GetEnvironmentVariable("APPVEYOR_API_URL");
 }
Beispiel #16
0
 public RepositoryFactory(IEnvironment environment, IDeploymentSettingsManager settings, ITraceFactory traceFactory, HttpContextBase httpContext)
 {
     _environment = environment;
     _settings = settings;
     _traceFactory = traceFactory;
     _httpContext = httpContext;
 }
// ReSharper disable MemberCanBePrivate.Global
        public ResharperIntegrationService(IPackageDescriptorMonitor monitor, IEnvironment env)
// ReSharper restore MemberCanBePrivate.Global
        {
            _monitor = monitor;
            _env = env;
            _refreshTimer = new Timer(_ => Refresh(), null, Timeout.Infinite, Timeout.Infinite);
        }
Beispiel #18
0
 public InfoRefsService(ITracer tracer, IGitServer gitServer, IEnvironment environment, RepositoryConfiguration configuration)
 {
     _gitServer = gitServer;
     _tracer = tracer;
     _deploymentTargetPath = environment.DeploymentTargetPath;
     _configuration = configuration;
 }
Beispiel #19
0
        public DTECheckFrm(IEnvironment env)
        {
            _dteo = new DTEOperation(env, vsCE.Events.SolutionEventType.General);

            InitializeComponent();
            Icon = Resource.Package_32;
        }
Beispiel #20
0
        internal static IDynamic IsArray(IEnvironment environment, IArgs args)
        {
            // 15.4.3.2 Array.isArray ( arg )

            var arg = args[0] as IObject;
            return environment.CreateBoolean(arg != null && arg.Class == "Array");
        }
Beispiel #21
0
 public MSBuildBuildEngine(IFileSystem fileSystem, IEnvironment environment)
     : base(fileSystem,environment)
 {
     Profile = new List<string> { environment.ExecutionEnvironment.Profile };
     Platform = new List<string> { environment.ExecutionEnvironment.Platform };
     Project = new List<string>();
 }
Beispiel #22
0
 public AspNet5Builder(IEnvironment environment, IDeploymentSettingsManager settings, IBuildPropertyProvider propertyProvider, string sourcePath, string projectPath, bool isConsoleApp)
     : base(environment, settings, propertyProvider, sourcePath)
 {
     _projectPath = projectPath;
     _sourcePath = sourcePath;
     _isConsoleApp = isConsoleApp;
 }
        /// <summary>
        /// Setup constructor
        /// </summary>
        public CompositeEditorController(
            IEnvironment env,
            ICompositeEditorView view,
            object composite,
            IComponentUiElementFactory uiFactory,
            IComponentDependencies dependencies,
            IComponentAggregator aggregator
            )
            : base(view)
        {
            Arguments.CheckNotNull( env, "env" );
            Arguments.CheckNotNull( uiFactory, "uiFactory" );
            Arguments.CheckNotNull( dependencies, "dependencies" );
            Arguments.CheckNotNull( aggregator, "aggregator" );

            m_View = view;
            m_Environment = env;
            m_UiFactory = uiFactory;
            m_Dependencies = dependencies;
            m_Aggregator = aggregator;

            m_View.SelectionChanged += OnSelectionChanged;
            m_View.EditComponent += OnEditComponent;
            m_View.RemoveSelectedComponent += OnRemoveComponent;
            m_View.AddToComponent += OnAddComponent;

            ResetView( composite );
        }
Beispiel #24
0
 public NullRepository(IEnvironment environment, ITraceFactory traceFactory, HttpContextBase httpContext)
 {
     _environment = environment;
     _traceFactory = traceFactory;
     _httpContext = httpContext;
     _changeSetKey = Path.Combine(_environment.RepositoryPath, "changeset");
 }
Beispiel #25
0
        private static void startTheEnvironment(IList<LogEntry> list, IEnvironment environment, params Action<IInstaller, IPackageLog>[] actions)
        {
            var log = new PackageLog();

            try
            {
                var installers = environment.StartUp(log);

                // This needs to happen regardless, but we want these logs put in before
                // logs for the installers, so we don't do it in the finally{}
                AddPackagingLogEntries(list);

                executeInstallers(list, installers, actions);

            }
            catch (Exception ex)
            {
                AddPackagingLogEntries(list);
                log.MarkFailure(ex.ToString());
            }
            finally
            {
                list.Add(LogEntry.FromPackageLog(environment, log));
                environment.SafeDispose();
            }
        }
 public static IEnumerable<IGrouping<string, Exports.ICommand>> CommandExports(this IPackageManager manager, IEnvironment environment)
 {
     var projectCommands = manager.GetProjectExports<Exports.ICommand>(environment.Descriptor, environment.ProjectRepository, environment.ExecutionEnvironment).SelectMany(x=>x).GroupBy(x=>x.Package.Name);
     var consumedPackages = projectCommands.Select(x => x.Key).ToList();
     var systemCommands = manager.GetSystemExports<Exports.ICommand>(environment.SystemRepository, environment.ExecutionEnvironment).SelectMany(x => x).GroupBy(x => x.Package.Name);
     return projectCommands.Concat(systemCommands.Where(x => consumedPackages.ContainsNoCase(x.Key) == false));
 }
Beispiel #27
0
 public static IQueryValue CClamp(IEnvironment env, IQueryValue[] args)
 {
     FunctionUtils.CheckArgumentCountEqual("cclamp", 1, args.Length);
     Color color = args[0].Color;
     color.Clamp();
     return new ColorValue() {Color = color};
 }
        public static DeploymentStatusFile Open(string id, IEnvironment environment, IAnalytics analytics, IOperationLock statusLock)
        {
            return statusLock.LockOperation(() =>
            {
                string path = Path.Combine(environment.DeploymentsPath, id, StatusFile);

                if (!FileSystemHelpers.FileExists(path))
                {
                    return null;
                }

                try
                {
                    XDocument document = null;
                    using (var stream = FileSystemHelpers.OpenRead(path))
                    {
                        document = XDocument.Load(stream);
                    }

                    return new DeploymentStatusFile(id, environment, statusLock, document);
                }
                catch (Exception ex)
                {
                    // in the scenario where w3wp is abruptly terminated while xml is being written,
                    // we may end up with corrupted xml.  we will handle the error and remove the problematic directory.
                    analytics.UnexpectedException(ex);

                    FileSystemHelpers.DeleteDirectorySafe(Path.GetDirectoryName(path), ignoreErrors: true);

                    // it is ok to return null as callers already handle null.
                    return null;
                }
            }, DeploymentStatusManager.LockTimeout);
        }
        public static string GetAvatarPreselection(this Avatar avatar, IEnvironment env)
        {
            if (avatar.isDefault)
                return "checked=\"checked\"";

            return string.Empty;
        }
 /// <inheritdoc />
 /// <summary>
 /// </summary>
 /// <param name="environment"></param>
 public void Register(IEnvironment environment)
 {
     this.Register(environment, environment.Identifier);
 }
Beispiel #31
0
 private static void RemoveTempFileFromUserDrive(IEnvironment environment)
 {
     FileSystemHelpers.DeleteDirectorySafe(Path.Combine(environment.RootPath, "data", "Temp"), ignoreErrors: true);
 }
Beispiel #32
0
 /// <summary>
 /// Creates the new instance of <see cref="IAlpacaDataClient"/> interface
 /// implementation for specific environment provided as <paramref name="environment"/> argument.
 /// </summary>
 /// <param name="environment">Target environment for new object.</param>
 /// <param name="securityKey">Alpaca API security key.</param>
 /// <returns>The new instance of <see cref="IAlpacaDataClient"/> interface implementation.</returns>
 public static IAlpacaDataClient GetAlpacaDataClient(
     this IEnvironment environment,
     SecurityKey securityKey) =>
 new AlpacaDataClient(environment.GetAlpacaDataClientConfiguration(securityKey));
 public BuildServer(IEnvironment environment, ILog log) : base(environment, log)
 {
 }
 public SearchContext(bool includeHistory, IEnvironment environment)
 {
     this.includeHistory = includeHistory;
     Environment         = environment;
 }
Beispiel #35
0
 public Environment(IEnvironment parent)
 {
     Parent = parent;
 }
Beispiel #36
0
 private static string GetSettingsPath(IEnvironment environment)
 {
     return(Path.Combine(environment.DeploymentsPath, Constants.DeploySettingsPath));
 }
Beispiel #37
0
        private static void RegisterServices(IKernel kernel)
        {
            var serverConfiguration = new ServerConfiguration();

            // Make sure %HOME% is correctly set
            EnsureHomeEnvironmentVariable();

            EnsureSiteBitnessEnvironmentVariable();

            IEnvironment environment = GetEnvironment();

            EnsureDotNetCoreEnvironmentVariable(environment);

            // Add various folders that never change to the process path. All child processes will inherit
            PrependFoldersToPath(environment);

            // Per request environment
            kernel.Bind <IEnvironment>().ToMethod(context => GetEnvironment(context.Kernel.Get <IDeploymentSettingsManager>()))
            .InRequestScope();

            // General
            kernel.Bind <HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current))
            .InRequestScope();
            kernel.Bind <IServerConfiguration>().ToConstant(serverConfiguration);

            kernel.Bind <IBuildPropertyProvider>().ToConstant(new BuildPropertyProvider());

            System.Func <ITracer> createTracerThunk = () => GetTracer(environment, kernel);
            System.Func <ILogger> createLoggerThunk = () => GetLogger(environment, kernel);

            // First try to use the current request profiler if any, otherwise create a new one
            var traceFactory = new TracerFactory(() => TraceServices.CurrentRequestTracer ?? createTracerThunk());

            kernel.Bind <ITracer>().ToMethod(context => TraceServices.CurrentRequestTracer ?? NullTracer.Instance);
            kernel.Bind <ITraceFactory>().ToConstant(traceFactory);
            TraceServices.SetTraceFactory(createTracerThunk, createLoggerThunk);

            // Setup the deployment lock
            string lockPath           = Path.Combine(environment.SiteRootPath, Constants.LockPath);
            string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile);
            string statusLockPath     = Path.Combine(lockPath, Constants.StatusLockFile);
            string sshKeyLockPath     = Path.Combine(lockPath, Constants.SSHKeyLockFile);
            string hooksLockPath      = Path.Combine(lockPath, Constants.HooksLockFile);

            _deploymentLock = new DeploymentLockFile(deploymentLockPath, kernel.Get <ITraceFactory>());
            _deploymentLock.InitializeAsyncLocks();

            var statusLock = new LockFile(statusLockPath, kernel.Get <ITraceFactory>());
            var sshKeyLock = new LockFile(sshKeyLockPath, kernel.Get <ITraceFactory>());
            var hooksLock  = new LockFile(hooksLockPath, kernel.Get <ITraceFactory>());

            kernel.Bind <IOperationLock>().ToConstant(sshKeyLock).WhenInjectedInto <SSHKeyController>();
            kernel.Bind <IOperationLock>().ToConstant(statusLock).WhenInjectedInto <DeploymentStatusManager>();
            kernel.Bind <IOperationLock>().ToConstant(hooksLock).WhenInjectedInto <WebHooksManager>();
            kernel.Bind <IOperationLock>().ToConstant(_deploymentLock);

            var shutdownDetector = new ShutdownDetector();

            shutdownDetector.Initialize();

            IDeploymentSettingsManager noContextDeploymentsSettingsManager =
                new DeploymentSettingsManager(new XmlSettings.Settings(GetSettingsPath(environment)));

            TraceServices.TraceLevel = noContextDeploymentsSettingsManager.GetTraceLevel();

            var noContextTraceFactory = new TracerFactory(() => GetTracerWithoutContext(environment, noContextDeploymentsSettingsManager));

            kernel.Bind <IAnalytics>().ToMethod(context => new Analytics(context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                         context.Kernel.Get <IServerConfiguration>(),
                                                                         noContextTraceFactory));

            // Trace unhandled (crash) exceptions.
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                var ex = args.ExceptionObject as Exception;
                if (ex != null)
                {
                    kernel.Get <IAnalytics>().UnexpectedException(ex);
                }
            };

            // Trace shutdown event
            // Cannot use shutdownDetector.Token.Register because of race condition
            // with NinjectServices.Stop via WebActivator.ApplicationShutdownMethodAttribute
            Shutdown += () => TraceShutdown(environment, noContextDeploymentsSettingsManager);

            // LogStream service
            // The hooks and log stream start endpoint are low traffic end-points. Re-using it to avoid creating another lock
            var logStreamManagerLock = hooksLock;

            kernel.Bind <LogStreamManager>().ToMethod(context => new LogStreamManager(Path.Combine(environment.RootPath, Constants.LogFilesPath),
                                                                                      context.Kernel.Get <IEnvironment>(),
                                                                                      context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                                      context.Kernel.Get <ITracer>(),
                                                                                      shutdownDetector,
                                                                                      logStreamManagerLock));

            kernel.Bind <InfoRefsController>().ToMethod(context => new InfoRefsController(t => context.Kernel.Get(t)))
            .InRequestScope();

            kernel.Bind <CustomGitRepositoryHandler>().ToMethod(context => new CustomGitRepositoryHandler(t => context.Kernel.Get(t)))
            .InRequestScope();

            // Deployment Service
            kernel.Bind <ISettings>().ToMethod(context => new XmlSettings.Settings(GetSettingsPath(environment)))
            .InRequestScope();
            kernel.Bind <IDeploymentSettingsManager>().To <DeploymentSettingsManager>()
            .InRequestScope();

            kernel.Bind <IDeploymentStatusManager>().To <DeploymentStatusManager>()
            .InRequestScope();

            kernel.Bind <ISiteBuilderFactory>().To <SiteBuilderFactory>()
            .InRequestScope();

            kernel.Bind <IWebHooksManager>().To <WebHooksManager>()
            .InRequestScope();

            ITriggeredJobsManager triggeredJobsManager = new TriggeredJobsManager(
                noContextTraceFactory,
                kernel.Get <IEnvironment>(),
                kernel.Get <IDeploymentSettingsManager>(),
                kernel.Get <IAnalytics>(),
                kernel.Get <IWebHooksManager>());

            kernel.Bind <ITriggeredJobsManager>().ToConstant(triggeredJobsManager)
            .InTransientScope();

            TriggeredJobsScheduler triggeredJobsScheduler = new TriggeredJobsScheduler(
                triggeredJobsManager,
                noContextTraceFactory,
                environment,
                kernel.Get <IAnalytics>());

            kernel.Bind <TriggeredJobsScheduler>().ToConstant(triggeredJobsScheduler)
            .InTransientScope();

            IContinuousJobsManager continuousJobManager = new ContinuousJobsManager(
                noContextTraceFactory,
                kernel.Get <IEnvironment>(),
                kernel.Get <IDeploymentSettingsManager>(),
                kernel.Get <IAnalytics>());

            OperationManager.SafeExecute(triggeredJobsManager.CleanupDeletedJobs);
            OperationManager.SafeExecute(continuousJobManager.CleanupDeletedJobs);

            kernel.Bind <IContinuousJobsManager>().ToConstant(continuousJobManager)
            .InTransientScope();

            kernel.Bind <ILogger>().ToMethod(context => GetLogger(environment, context.Kernel))
            .InRequestScope();

            kernel.Bind <IDeploymentManager>().To <DeploymentManager>()
            .InRequestScope();
            kernel.Bind <IAutoSwapHandler>().To <AutoSwapHandler>()
            .InRequestScope();
            kernel.Bind <ISSHKeyManager>().To <SSHKeyManager>()
            .InRequestScope();

            kernel.Bind <IRepositoryFactory>().ToMethod(context => _deploymentLock.RepositoryFactory = new RepositoryFactory(context.Kernel.Get <IEnvironment>(),
                                                                                                                             context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                                                                             context.Kernel.Get <ITraceFactory>()))
            .InRequestScope();

            kernel.Bind <IApplicationLogsReader>().To <ApplicationLogsReader>()
            .InSingletonScope();

            // Git server
            kernel.Bind <IDeploymentEnvironment>().To <DeploymentEnvrionment>();

            kernel.Bind <IGitServer>().ToMethod(context => new GitExeServer(context.Kernel.Get <IEnvironment>(),
                                                                            _deploymentLock,
                                                                            GetRequestTraceFile(context.Kernel),
                                                                            context.Kernel.Get <IRepositoryFactory>(),
                                                                            context.Kernel.Get <IDeploymentEnvironment>(),
                                                                            context.Kernel.Get <IDeploymentSettingsManager>(),
                                                                            context.Kernel.Get <ITraceFactory>()))
            .InRequestScope();

            // Git Servicehook parsers
            kernel.Bind <IServiceHookHandler>().To <GenericHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <GitHubHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <BitbucketHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <BitbucketHandlerV2>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <DropboxHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <CodePlexHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <CodebaseHqHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <GitlabHqHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <GitHubCompatHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <KilnHgHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <VSOHandler>().InRequestScope();
            kernel.Bind <IServiceHookHandler>().To <OneDriveHandler>().InRequestScope();

            // SiteExtensions
            kernel.Bind <ISiteExtensionManager>().To <SiteExtensionManager>().InRequestScope();

            // Functions
            kernel.Bind <IFunctionManager>().To <FunctionManager>().InRequestScope();

            // Command executor
            kernel.Bind <ICommandExecutor>().To <CommandExecutor>().InRequestScope();

            MigrateSite(environment, noContextDeploymentsSettingsManager);
            RemoveOldTracePath(environment);
            RemoveTempFileFromUserDrive(environment);

            // Temporary fix for https://github.com/npm/npm/issues/5905
            EnsureNpmGlobalDirectory();
            EnsureUserProfileDirectory();

            // Skip SSL Certificate Validate
            OperationClient.SkipSslValidationIfNeeded();

            // Make sure webpages:Enabled is true. Even though we set it in web.config, it could be overwritten by
            // an Azure AppSetting that's supposed to be for the site only but incidently affects Kudu as well.
            ConfigurationManager.AppSettings["webpages:Enabled"] = "true";

            // Kudu does not rely owin:appStartup.  This is to avoid Azure AppSetting if set.
            if (ConfigurationManager.AppSettings["owin:appStartup"] != null)
            {
                // Set the appSetting to null since we cannot use AppSettings.Remove(key) (ReadOnly exception!)
                ConfigurationManager.AppSettings["owin:appStartup"] = null;
            }

            RegisterRoutes(kernel, RouteTable.Routes);

            // Register the default hubs route: ~/signalr
            GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel);
            GlobalConfiguration.Configuration.Filters.Add(
                new TraceDeprecatedActionAttribute(
                    kernel.Get <IAnalytics>(),
                    kernel.Get <ITraceFactory>()));
            GlobalConfiguration.Configuration.Filters.Add(new EnsureRequestIdHandlerAttribute());
        }
        /// <param name="env">Used environment</param>
        /// <param name="uvariable">Instance of used user-variables</param>
        public UserVariableComponent(IEnvironment env, IUserVariable uvariable)
            : base(env, uvariable)
        {

        }
Beispiel #39
0
 // remove old LogFiles/Git trace
 private static void RemoveOldTracePath(IEnvironment environment)
 {
     FileSystemHelpers.DeleteDirectorySafe(Path.Combine(environment.LogFilesPath, "Git"), ignoreErrors: true);
 }
Beispiel #40
0
 public VsoAgent(IEnvironment environment) : base(environment)
 {
 }
Beispiel #41
0
        public BlobStorageSecretsRepository(string secretSentinelDirectoryPath, string accountConnection, string siteSlotName, ILogger logger, IEnvironment environment, IAzureBlobStorageProvider azureBlobStorageProvider)
            : base(secretSentinelDirectoryPath, logger, environment)
        {
            ArgumentNullException.ThrowIfNull(secretSentinelDirectoryPath);
            ArgumentNullException.ThrowIfNull(accountConnection);
            ArgumentNullException.ThrowIfNull(siteSlotName);

            _secretsBlobPath          = siteSlotName.ToLowerInvariant();
            _hostSecretsBlobPath      = string.Format("{0}/{1}", _secretsBlobPath, ScriptConstants.HostMetadataFileName);
            _accountConnection        = accountConnection;
            _azureBlobStorageProvider = azureBlobStorageProvider;
        }
Beispiel #42
0
        public static void Run(Arguments arguments, IFileSystem fileSystem, IEnvironment environment)
        {
            Logger.WriteInfo($"Running on {(runningOnUnix ? "Unix" : "Windows")}.");

            var noFetch                   = arguments.NoFetch;
            var authentication            = arguments.Authentication;
            var targetPath                = arguments.TargetPath;
            var targetUrl                 = arguments.TargetUrl;
            var dynamicRepositoryLocation = arguments.DynamicRepositoryLocation;
            var targetBranch              = arguments.TargetBranch;
            var commitId                  = arguments.CommitId;
            var overrideConfig            = arguments.HasOverrideConfig ? arguments.OverrideConfig : null;
            var noCache                   = arguments.NoCache;
            var noNormalize               = arguments.NoNormalize;

            var executeCore = new ExecuteCore(fileSystem, environment, arguments.ConfigFileLocator);
            var variables   = executeCore.ExecuteGitVersion(targetUrl, dynamicRepositoryLocation, authentication, targetBranch, noFetch, targetPath, commitId, overrideConfig, noCache, noNormalize);

            switch (arguments.Output)
            {
            case OutputType.BuildServer:
            {
                BuildServerList.Init(environment);
                foreach (var buildServer in BuildServerList.GetApplicableBuildServers())
                {
                    buildServer.WriteIntegration(Console.WriteLine, variables);
                }

                break;
            }

            case OutputType.Json:
                switch (arguments.ShowVariable)
                {
                case null:
                    Console.WriteLine(JsonOutputFormatter.ToJson(variables));
                    break;

                default:
                    if (!variables.TryGetValue(arguments.ShowVariable, out var part))
                    {
                        throw new WarningException($"'{arguments.ShowVariable}' variable does not exist");
                    }
                    Console.WriteLine(part);
                    break;
                }

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (arguments.UpdateWixVersionFile)
            {
                using (var wixVersionFileUpdater = new WixVersionFileUpdater(targetPath, variables, fileSystem))
                {
                    wixVersionFileUpdater.Update();
                }
            }

            using (var assemblyInfoUpdater = new AssemblyInfoFileUpdater(arguments.UpdateAssemblyInfoFileName, targetPath, variables, fileSystem, arguments.EnsureAssemblyInfo))
            {
                if (arguments.UpdateAssemblyInfo)
                {
                    assemblyInfoUpdater.Update();
                }

                var execRun    = RunExecCommandIfNeeded(arguments, targetPath, variables);
                var msbuildRun = RunMsBuildIfNeeded(arguments, targetPath, variables);

                if (!execRun && !msbuildRun)
                {
                    assemblyInfoUpdater.CommitChanges();
                    //TODO Put warning back
                    //if (!context.CurrentBuildServer.IsRunningInBuildAgent())
                    //{
                    //    Console.WriteLine("WARNING: Not running in build server and /ProjectFile or /Exec arguments not passed");
                    //    Console.WriteLine();
                    //    Console.WriteLine("Run GitVersion.exe /? for help");
                    //}
                }
            }
        }
Beispiel #43
0
        public HostJsonFileConfigurationSource(ScriptApplicationHostOptions applicationHostOptions, IEnvironment environment, ILoggerFactory loggerFactory, IMetricsLogger metricsLogger)
        {
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            HostOptions    = applicationHostOptions;
            Environment    = environment;
            _metricsLogger = metricsLogger;
            _logger        = loggerFactory.CreateLogger(LogCategories.Startup);
        }
Beispiel #44
0
 public static IEnvironment NewCachingEnvironmentFor(IEnvironment environment)
 {
     return(new _IEnvironment_48(environment));
 }
Beispiel #45
0
        public async Task <IAgentAction <IReadOnlyCollection <ElementData> > > GetNextAction(IEnvironment <IReadOnlyCollection <ElementData> > environment, IState <IReadOnlyCollection <ElementData> > state)
        {
            var actions = await environment.GetPossibleActions(state);

            Debug.Assert(state.Data.Count > 0, $"A state reached {nameof(SeleniumQLearningStepPolicy)} that has no data");

            // TODO: exploration mode?
            var stateAndActionPairs = actions
                                      .Select(x =>
            {
                var pair = new StateAndActionPair <IReadOnlyCollection <ElementData> >(state, x);
                return(QualityMatrix.ContainsKey(pair)
                        ? (Action: x, Score: QualityMatrix[pair])
                        : (Action: x, Score: 0D));
            })
                                      .OrderByDescending(x => x.Score)
                                      .ToList();

            // Take all the items that compete for the maximum value
            var maxStateAndActionPairs = stateAndActionPairs
                                         .Where(x => x.Score == stateAndActionPairs[0].Score)
                                         .ToList();

            return(maxStateAndActionPairs.ElementAt(random.Next(0, maxStateAndActionPairs.Count)).Action);
        }
Beispiel #46
0
 public _IEnvironment_48(IEnvironment environment)
 {
     this.environment = environment;
     _bindings        = new Hashtable();
 }
Beispiel #47
0
 public HttpOptionsSetup(IEnvironment environment)
 {
     _environment = environment;
 }
        internal static bool IsSyncTriggersEnvironment(IScriptWebHostEnvironment webHostEnvironment, IEnvironment environment)
        {
            if (environment.IsCoreToolsEnvironment())
            {
                // don't sync triggers when running locally or not running in a cloud
                // hosted environment
                return(false);
            }

            if (environment.GetEnvironmentVariable(EnvironmentSettingNames.WebSiteAuthEncryptionKey) == null)
            {
                // We don't have the encryption key required for SetTriggers,
                // so sync calls would fail auth anyways.
                // This might happen in when running locally for example.
                return(false);
            }

            if (webHostEnvironment.InStandbyMode)
            {
                // don’t sync triggers when in standby mode
                return(false);
            }

            // Windows (Dedicated/Consumption)
            // Linux Consumption
            if ((environment.IsAppServiceWindowsEnvironment() || environment.IsLinuxContainerEnvironment()) &&
                !environment.IsContainerReady())
            {
                // container ready flag not set yet – site not fully specialized/initialized
                return(false);
            }

            return(true);
        }
Beispiel #49
0
 public static void RunWith(IEnvironment environment, IRunnable runnable)
 {
     _current.With(environment, runnable);
 }
Beispiel #50
0
        public SiteExtensionManager(IContinuousJobsManager continuousJobManager, ITriggeredJobsManager triggeredJobManager, IEnvironment environment, IDeploymentSettingsManager settings, ITraceFactory traceFactory, HttpContextBase context, IAnalytics analytics)
        {
            _rootPath = Path.Combine(environment.RootPath, "SiteExtensions");
            _baseUrl  = context.Request.Url == null ? String.Empty : context.Request.Url.GetLeftPart(UriPartial.Authority).TrimEnd('/');

            _localRepository      = GetSourceRepository(_rootPath);
            _continuousJobManager = continuousJobManager;
            _triggeredJobManager  = triggeredJobManager;
            _environment          = environment;
            _settings             = settings;
            _traceFactory         = traceFactory;
            _analytics            = analytics;
        }
 public FunctionsSyncManager(IConfiguration configuration, IHostIdProvider hostIdProvider, IOptionsMonitor <ScriptApplicationHostOptions> applicationHostOptions, IOptions <LanguageWorkerOptions> languageWorkerOptions, ILogger <FunctionsSyncManager> logger, HttpClient httpClient, ISecretManagerProvider secretManagerProvider, IScriptWebHostEnvironment webHostEnvironment, IEnvironment environment, HostNameProvider hostNameProvider)
 {
     _applicationHostOptions = applicationHostOptions;
     _logger                = logger;
     _workerConfigs         = languageWorkerOptions.Value.WorkerConfigs;
     _httpClient            = httpClient;
     _secretManagerProvider = secretManagerProvider;
     _configuration         = configuration;
     _hostIdProvider        = hostIdProvider;
     _webHostEnvironment    = webHostEnvironment;
     _environment           = environment;
     _hostNameProvider      = hostNameProvider;
 }
 /// <summary>
 /// Creates new instance of <see cref="PolygonDataClientConfiguration"/> for specific
 /// environment provided as <paramref name="environment"/> argument.
 /// </summary>
 /// <param name="environment">Target environment for new object.</param>
 /// <param name="keyId">Alpaca API key identifier.</param>
 /// <returns>New instance of <see cref="PolygonDataClientConfiguration"/> object.</returns>
 public static PolygonDataClientConfiguration GetPolygonDataClientConfiguration(
     this IEnvironment environment,
     String keyId) =>
Beispiel #53
0
 public AppVeyor(IEnvironment environment, ILog log) : base(environment, log)
 {
 }
Beispiel #54
0
 public LinuxContainerInitializationHostService(IEnvironment environment, IInstanceManager instanceManager, ILogger <LinuxContainerInitializationHostService> logger)
 {
     _environment     = environment;
     _instanceManager = instanceManager;
     _logger          = logger;
 }
Beispiel #55
0
 public static string GetScriptsDirectoryAbsolutePath(IEnvironment environment)
 {
     return(Path.Combine(environment.RootPath, ScriptsDirectoryRelativePath));
 }
Beispiel #56
0
 public static IPolygonDataClient GetPolygonDataClient(
     this IEnvironment environment,
     String keyId) =>
 new PolygonDataClient(environment.GetPolygonDataClientConfiguration(keyId));
 /// <summary>
 /// </summary>
 /// <param name="neodroid_environment"></param>
 public void UnRegister(IEnvironment neodroid_environment)
 {
     this.UnRegister(neodroid_environment, neodroid_environment.Identifier);
 }
 public AdapterDataSetWarehouseOrderOutput(IEnvironment pEnv)
     : base(pEnv)
 {
     lineIOCode = docIOCode = (short)ConstIOCode.outputFromWarehouse;
     lineTrCode = docTrCode = (short)ConstDocTypeMaterial.marerialDefinedOutput20;
 }
        private async Task InitializeTestHostAsync(string testDirName, IEnvironment environment)
        {
            var httpConfig         = new HttpConfiguration();
            var uniqueTestRootPath = Path.Combine(_testRootPath, testDirName, Guid.NewGuid().ToString());
            var scriptRootPath     = Path.Combine(uniqueTestRootPath, "wwwroot");

            FileUtility.EnsureDirectoryExists(scriptRootPath);
            string proxyConfigPath = Path.Combine(scriptRootPath, "proxies.json");

            File.WriteAllText(proxyConfigPath, "{}");
            await TestHelpers.Await(() => File.Exists(proxyConfigPath));

            _loggerProvider = new TestLoggerProvider();

            if (environment.IsAppServiceEnvironment())
            {
                // if the test is mocking App Service environment, we need
                // to also set the HOME and WEBSITE_SITE_NAME variables
                environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHomePath, uniqueTestRootPath);
                environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteName, "test-host-name");
            }

            var webHostBuilder = Program.CreateWebHostBuilder()
                                 .ConfigureAppConfiguration(c =>
            {
                // This source reads from AzureWebJobsScriptRoot, which does not work
                // with the custom paths that these tests are using.
                var source = c.Sources.OfType <WebScriptHostConfigurationSource>().SingleOrDefault();
                if (source != null)
                {
                    c.Sources.Remove(source);
                }
                c.AddTestSettings();
            })
                                 .ConfigureLogging(c =>
            {
                c.AddProvider(_loggerProvider);
            })
                                 .ConfigureServices(c =>
            {
                c.ConfigureAll <ScriptApplicationHostOptions>(o =>
                {
                    o.IsSelfHost  = true;
                    o.LogPath     = Path.Combine(uniqueTestRootPath, "logs");
                    o.SecretsPath = Path.Combine(uniqueTestRootPath, "secrets");
                    o.ScriptPath  = _expectedScriptPath = scriptRootPath;
                });

                c.AddSingleton <IEnvironment>(_ => environment);
                c.AddSingleton <IConfigureBuilder <ILoggingBuilder> >(new DelegatedConfigureBuilder <ILoggingBuilder>(b => b.AddProvider(_loggerProvider)));
            });

            _httpServer             = new TestServer(webHostBuilder);
            _httpClient             = _httpServer.CreateClient();
            _httpClient.BaseAddress = new Uri("https://localhost/");

            TestHelpers.WaitForWebHost(_httpClient);

            var traces = _loggerProvider.GetAllLogMessages().ToArray();

            Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode")));

            _expectedHostId = await _httpServer.Host.Services.GetService <IHostIdProvider>().GetHostIdAsync(CancellationToken.None);
        }
Beispiel #60
-1
        public FetchHandler(ITracer tracer,
                            IDeploymentManager deploymentManager,
                            IDeploymentSettingsManager settings,
                            IDeploymentStatusManager status,
                            IOperationLock deploymentLock,
                            IEnvironment environment,
                            IEnumerable<IServiceHookHandler> serviceHookHandlers,
                            IRepositoryFactory repositoryFactory,
                            IAutoSwapHandler autoSwapHandler)
        {
            _tracer = tracer;
            _deploymentLock = deploymentLock;
            _environment = environment;
            _deploymentManager = deploymentManager;
            _settings = settings;
            _status = status;
            _serviceHookHandlers = serviceHookHandlers;
            _repositoryFactory = repositoryFactory;
            _autoSwapHandler = autoSwapHandler;
            _markerFilePath = Path.Combine(environment.DeploymentsPath, "pending");

            // Prefer marker creation in ctor to delay create when needed.
            // This is to keep the code simple and avoid creation synchronization.
            if (!FileSystemHelpers.FileExists(_markerFilePath))
            {
                try
                {
                    FileSystemHelpers.WriteAllText(_markerFilePath, String.Empty);
                }
                catch (Exception ex)
                {
                    tracer.TraceError(ex);
                }
            }
        }