private CruiseServerClientBase GenerateHttpClient(BuildServer server)
        {
            var client = clientFactory.GenerateHttpClient(server.Url,
                                                          ClientStartUpSettingsExtensions.GenerateStartupSettings(server));

            return(client);
        }
示例#2
0
        public void ShowDialogForInteractiveTesting()
        {
            AddBuildServer addBuildServer = new AddBuildServer(null);
            BuildServer    server         = addBuildServer.ChooseNewBuildServer(null);

            Console.WriteLine(server);
        }
示例#3
0
        public void SetUp()
        {
            serverClient = mocks.DynamicMock <CruiseServerClientBase>();

            buildServer = new BuildServer(SERVER_URL);
            manager     = new HttpCruiseServerManager(serverClient, buildServer);
        }
示例#4
0
        public void TestSetConfiguration()
        {
            var buildServer = new BuildServer("http://test.com");

            Manager.SetConfiguration(buildServer);
            Assert.AreEqual(Manager.Configuration.Url, "http://test.com");
        }
 public HttpCruiseServerManager(CruiseServerClientBase manager,
                                BuildServer buildServer)
 {
     this.manager       = manager;
     this.configuration = buildServer;
     displayName        = GetDisplayNameFromUri(buildServer.Uri);
 }
        public void SetUp()
        {
            serverClient = mocks.Create <CruiseServerClientBase>().Object;

            buildServer = new BuildServer(SERVER_URL);
            manager     = new HttpCruiseServerManager(serverClient, buildServer);
        }
        public static bool Configure(IWin32Window parent, BuildServer server)
        {
            ConfigureServer configureDialog = new ConfigureServer(server);
            bool            hasChanged      = (configureDialog.ShowDialog(parent) == DialogResult.OK);

            return(hasChanged);
        }
        public ICruiseProjectManager Create(CCTrayProject project, IDictionary <BuildServer, ICruiseServerManager> serverManagers)
        {
            BuildServer server = project.BuildServer;

            switch (server.Transport)
            {
            case BuildServerTransport.Remoting:
            {
                var client = GenerateRemotingClient(server);
                return(new RemotingCruiseProjectManager(client, project.ProjectName));
            }

            case BuildServerTransport.Extension:
                ITransportExtension extensionInstance = ExtensionHelpers.RetrieveExtension(server.ExtensionName);
                extensionInstance.Settings      = server.ExtensionSettings;
                extensionInstance.Configuration = server;
                return(extensionInstance.RetrieveProjectManager(project.ProjectName));

            default:
            {
                var client = GenerateHttpClient(server);
                return(new HttpCruiseProjectManager(client, project.ProjectName, serverManagers[server]));
            }
            }
        }
示例#9
0
        public static async Task Main(string[] args)
        {
            var cancel   = new CancellationTokenSource();
            var jobQueue = new JobQueue();

            Console.WriteLine("Helium CI UI");

            var agentManager = await AgentManager.Load(Path.Combine(ConfDir, "agents"), cancel.Token);

            var projectManager = await ProjectManager.Load(Path.Combine(ConfDir, "projects"), jobQueue, cancel.Token);

            var server = new Grpc.Core.Server {
                Services = { BuildServer.BindService(new BuildServerImpl(agentManager, jobQueue)) },
                Ports    = { new ServerPort("0.0.0.0", 6000, ServerCredentials.Insecure) },
            };

            try {
                server.Start();

                try {
                    await CreateHostBuilder(agentManager, projectManager).Build().RunAsync();
                }
                finally {
                    cancel.Cancel();
                }
            }
            finally {
                await server.ShutdownAsync();
            }
        }
        public void SetUp()
        {
            cruiseManagerMock = mocks.Create <CruiseServerClientBase>(MockBehavior.Strict).Object;

            buildServer = new BuildServer(ServerUrl);
            manager     = new RemotingCruiseServerManager(cruiseManagerMock, buildServer);
        }
        public void SetExtensionName()
        {
            BuildServer newServer = new BuildServer();

            newServer.ExtensionName = "new extension";
            Assert.AreEqual("new extension", newServer.ExtensionName);
        }
        private void RetrieveListOfProjects(BuildServer server)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                lbProject.Items.Clear();

                CCTrayProject[] projectList = cruiseProjectManagerFactory.GetProjectList(server, false);

                foreach (CCTrayProject project in projectList)
                {
                    if (!IsProjectAlreadyAdded(project))
                    {
                        lbProject.Items.Add(project.ProjectName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Unable to connect to server " + server.DisplayName + ": " + ex.Message, "Error");
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
示例#13
0
        public void SetUp()
        {
            cruiseManagerMock = mocks.StrictMock <CruiseServerClientBase>();

            buildServer = new BuildServer(ServerUrl);
            manager     = new RemotingCruiseServerManager(cruiseManagerMock, buildServer);
        }
示例#14
0
 public bool Configure(IWin32Window owner)
 {
     if (JenkinsServerManagerFactory.IsServerManagerInitialized)
     {
         DialogService.Show(
             "Monitoring jobs from multiple jenkins servers is unsupported due to the CCTray interface.\n" +
             "If you have previously removed a jenkins server, restart CCTray first.");
         return(false);
     }
     else
     {
         using (var form = ConfigurationFormFactory.Create())
         {
             if (form.ShowDialog(owner) == DialogResult.OK)
             {
                 var server = form.GetServer();
                 Configuration = new BuildServer(server);
                 var settings = new Settings()
                 {
                     Project  = String.Empty,
                     Server   = server,
                     Username = form.GetUsername(),
                     Password = form.GetPassword()
                 };
                 Settings = settings.ToString();
                 //We will need to initialize the server manager again if their information has changed
                 JenkinsServerManagerFactory.IsServerManagerInitialized = false;
                 return(true);
             }
             return(false);
         }
     }
 }
        public void SetExtensionSettings()
        {
            BuildServer newServer = new BuildServer();

            newServer.ExtensionSettings = "new extension";
            Assert.AreEqual("new extension", newServer.ExtensionSettings);
        }
示例#16
0
 public bool TryInit(BuildServer server, Project project)
 {
     _controller = new ConsoleServerController(_loggerFactory, _context, server);
     _view       = new ConsoleServerView(_loggerFactory, _context, server, _messageFormat);
     _loggerFactory.CreateLogger <ConsoleService>().LogDebug("ConsoleService: initialized");
     return(true);
 }
示例#17
0
        /// <summary>Initializes a new instance of the <see cref="BuildServerAdapter"/> class.</summary>
        /// <param name="buildServer">The build server.</param>
        /// <param name="removeServerCommand">The remove server command.</param>
        public BuildServerAdapter(BuildServer buildServer, ICommand removeServerCommand)
        {
            detailBuildUrl   = buildServer.DetailBuildUrl;
            domainName       = buildServer.DomainName;
            login            = buildServer.Login;
            passwordBytes    = buildServer.PasswordBytes;
            serverName       = buildServer.ServerName;
            tfsVersion       = buildServer.TfsVersion;
            url              = buildServer.Url;
            BuildDefinitions = new List <BuildDefinition>(buildServer.BuildDefinitions);

            TfsConnectCommand   = new TfsConnectCommand(this, crypter);
            RemoveServerCommand = removeServerCommand;

            ProjectNames = new ObservableCollection <string>();

            BuildDefinitionResults = new ObservableCollection <BuildDefinitionResult>();
            CollectionViewSourceBuildDefinitions = new CollectionViewSource {
                Source = BuildDefinitionResults
            };
            CollectionViewSourceBuildDefinitions.Filter += CollectionViewSourceBuildDefinitions_Filter;

            if (buildServer.BuildDefinitions.Any())
            {
                OnlySelected = true;
            }

            if (TfsConnectCommand.CanExecute(null))
            {
                TfsConnectCommand.Execute(null);
            }
        }
        public void SetTransport()
        {
            BuildServer newServer = new BuildServer();

            newServer.Transport = BuildServerTransport.Extension;
            Assert.AreEqual(BuildServerTransport.Extension, newServer.Transport);
        }
        private static IEnumerable <BuildInformation> GetBuildsTfs2013(BuildServer buildServer)
        {
            var apiIndex           = buildServer.Url.IndexOf("_apis", StringComparison.OrdinalIgnoreCase);
            var urlNoApi           = buildServer.Url.Substring(0, apiIndex);
            var buildDefinitionUrl = string.Concat(urlNoApi, "_apis/build/Builds?api-version=1.0&definition=");
            var stopBuildUrl       = string.Concat(urlNoApi, "_apis/build/builds/{0}?api-version=1.0");
            var requestBuildUrl    = string.Concat(urlNoApi, "_apis/build/requests?api-version=1.0");
            var testResutlUri      = string.Concat(urlNoApi, "_api/_build/build?__v=5&uri=vstfs:///Build/Build/{0}&includeTestRuns=true&includeCoverage=true");

            foreach (var buildDefinition in buildServer.BuildDefinitions)
            {
                var build = new BuildInformation
                {
                    DomainName         = buildServer.DomainName,
                    Login              = buildServer.Login,
                    CryptedPassword    = buildServer.PasswordBytes,
                    BuildDefinitionUrl = string.Concat(buildDefinitionUrl, buildDefinition.Uri),
                    BuildDetailUrl     = buildServer.DetailBuildUrl,
                    BuildDefinitionId  = buildDefinition.Id,
                    StopBuildUrl       = stopBuildUrl,
                    RequestBuildUrl    = requestBuildUrl,
                    TestResultUrl      = testResutlUri,
                    TfsVersion         = buildServer.TfsVersion,
                    Tags = buildDefinition.Tags
                };
                yield return(build);
            }
        }
        private static IEnumerable <BuildInformation> GetBuildsTfs2015(BuildServer buildServer)
        {
            var apiIndex = buildServer.Url.IndexOf("_apis", StringComparison.OrdinalIgnoreCase);

            foreach (var buildDefinition in buildServer.BuildDefinitions)
            {
                var urlNoApi           = apiIndex < 0 ? string.Concat(buildServer.Url, "/", buildDefinition.ProjectId, "/") : buildServer.Url.Substring(0, apiIndex);
                var buildDefinitionUrl = string.Concat(urlNoApi, "_apis/build/Builds?api-version=2.0&definitions=");
                var stopBuildUrl       = string.Concat(urlNoApi, "_apis/build/builds/{0}?api-version=2.0");
                var requestBuildUrl    = string.Concat(urlNoApi, "_apis/build/builds?api-version=2.0");
                var testRunUrl         = string.Concat(urlNoApi, "_apis/test/Runs/Query?includeRunDetails=true&api-version=2.2-preview.2");
                var changesetUrl       = string.Concat(urlNoApi, "_apis/tfvc/changesets/{0}?api-version=1.0");
                var build = new BuildInformation
                {
                    DomainName         = buildServer.DomainName,
                    Login              = buildServer.Login,
                    CryptedPassword    = buildServer.PasswordBytes,
                    BuildDefinitionUrl = string.Concat(buildDefinitionUrl, buildDefinition.Id),
                    BuildDefinitionId  = buildDefinition.Id,
                    StopBuildUrl       = stopBuildUrl,
                    RequestBuildUrl    = requestBuildUrl,
                    TfsVersion         = buildServer.TfsVersion,
                    TestRunUrl         = testRunUrl,
                    ChangesetUrl       = changesetUrl,
                    Tags = buildDefinition.Tags
                };
                yield return(build);
            }
        }
示例#21
0
        public IObservable<Job> UpdateAll(BuildServer buildServer, IEnumerable<Job> jobs)
        {
            return GetJobsObservableAsync(buildServer)
                .SelectMany(latestJobs =>
                {
                    var latestJobMap = latestJobs.ToDictionary(j => j.Name);

                    foreach(var job in jobs)
                    {
                        if (latestJobMap.ContainsKey(job.Name))
                        {
                            job.LastBuild = latestJobMap[job.Name].LastBuild;
                        }
                        else
                        {
                            job.LastBuild = new Build()
                            {
                                Result = BuildResult.Unavailable,
                                Time = clock.UtcNow
                            };
                        }
                    }

                    return (ICollection<Job>)jobs.ToList();
                });
        }
示例#22
0
        public void WhenRequestingACruiseProjectManagerWithAnHttpUrlConstructsANewDashboardCruiseProjectManager()
        {
            var serverAddress = "http://somethingOrOther";
            var server        = new BuildServer(serverAddress);
            var client        = mocks.DynamicMock <CruiseServerClientBase>();

            var clientFactory = mocks.StrictMock <ICruiseServerClientFactory>();

            Expect.Call(clientFactory.GenerateHttpClient(serverAddress, new ClientStartUpSettings()))
            .Constraints(new Equal(serverAddress), new Anything())
            .Return(client);
            var factory = new CruiseProjectManagerFactory(clientFactory);

            var serverManagers = new Dictionary <BuildServer, ICruiseServerManager>();

            serverManagers[server] = new HttpCruiseServerManager(client, server);

            mocks.ReplayAll();
            var manager = factory.Create(new CCTrayProject(server, ProjectName), serverManagers);

            Assert.AreEqual(ProjectName, manager.ProjectName);
            Assert.AreEqual(typeof(HttpCruiseProjectManager), manager.GetType());

            mocks.VerifyAll();
        }
示例#23
0
        public IList <DeliveryPipeline> GetPipelines()
        {
            IList <DeliveryPipeline> pipelines = new List <DeliveryPipeline>();

            Uri collectionUri = new Uri(Uri);

            ProjectCollection = new TfsTeamProjectCollection(collectionUri);

            BuildServer            = ProjectCollection.GetService <IBuildServer>();
            CommonStructureService = ProjectCollection.GetService <ICommonStructureService>();
            Registration           = ProjectCollection.GetService <IRegistration>();
            VersionControlServer   = ProjectCollection.GetService <VersionControlServer>();
            ClientHyperlinkService = ProjectCollection.GetService <TswaClientHyperlinkService>();

            Name = ProjectCollection.CatalogNode.Resource.DisplayName;

            if (BuildServer.BuildServerVersion.ToString() == "v3")
            {
                TfsVersion = 2010;
            }
            else
            {
                TfsVersion = 2012;
            }

            foreach (ProjectInfo project in CommonStructureService.ListProjects())
            {
                foreach (IBuildDefinition definition in BuildServer.QueryBuildDefinitions(project.Name))
                {
                    if (definition.Process.ServerPath.Contains("BuildProcessTemplates/PowerDelivery"))
                    {
                        IDictionary <string, object> processParams = WorkflowHelpers.DeserializeProcessParameters(definition.ProcessParameters);

                        if (processParams.ContainsKey("PowerShellScriptPath"))
                        {
                            string scriptPath = processParams["PowerShellScriptPath"] as string;

                            string scriptName = System.IO.Path.GetFileNameWithoutExtension(scriptPath.Substring(scriptPath.LastIndexOf("/")));

                            string environmentName = definition.Name.Substring(definition.Name.LastIndexOf(" - ") + 3);

                            DeliveryPipeline pipeline = pipelines.FirstOrDefault(p => p.ScriptName == scriptName);

                            if (pipeline == null)
                            {
                                pipeline = new DeliveryPipeline(this, project, scriptName);
                                pipelines.Add(pipeline);
                            }

                            PipelineEnvironment environment = new PipelineEnvironment(pipeline, environmentName, definition);

                            pipeline.Environments.Add(environment);
                        }
                    }
                }
            }

            return(pipelines);
        }
        private ListViewItem AddServer(BuildServer server)
        {
            ListViewItem newServerItem = lbServer.Items.Add(server.DisplayName, "NonSecure");

            newServerItem.Tag = server;
            SetSecurityIcon(newServerItem, server);
            return(newServerItem);
        }
示例#25
0
        public StubServerMonitor(string serverUrl)
        {
            this.serverUrl = serverUrl;
            BuildServer buildServer = new BuildServer(serverUrl);

            this.displayName          = buildServer.DisplayName;
            this.buildServerTransport = buildServer.Transport;
        }
示例#26
0
        /// <summary>
        /// Sets the Configuration for this server manager
        /// </summary>
        /// <param name="server">the BuildServer configuration</param>
        /// <param name="projectName">the project name</param>
        /// <param name="settings">the Settings</param>
        public void Initialize(BuildServer server, string projectName, Settings settings)
        {
            Configuration            = server;
            ProjectName              = projectName;
            Settings                 = settings;
            AuthorizationInformation = Settings.AuthorizationInformation;

            Api = _jenkinsApiFactory.Create(Settings.Server, AuthorizationInformation, _webRequestFactory);
        }
示例#27
0
        public static IBuildDetail GetBuild(string teamProject, string buildNumber)
        {
            IBuildDetailSpec buildDetailSpec = BuildServer.CreateBuildDetailSpec(teamProject);

            buildDetailSpec.BuildNumber = buildNumber;
            IBuildQueryResult buildQueryResult = BuildServer.QueryBuilds(buildDetailSpec);

            return(buildQueryResult.Builds.Length == 1 ? buildQueryResult.Builds[0] : null);
        }
示例#28
0
 public bool TryInit(BuildServer server, Project project)
 {
     _server              = server;
     _server.OnInitBuild += OnInitBuild;
     _server.AddCommand("stats", "show stats about builds", OnStatsRequested);
     _server.AddCommand("history", "show history about builds", OnHistoryRequested);
     LoadContainer();
     _logger.LogDebug($"Container: {_container.Builds.Count} builds");
     return(true);
 }
        public FlubuConsoleLogger(string name)
        {
            Name = name ?? throw new ArgumentNullException(nameof(name));
            BuildServer buildServer = new BuildServer();

            ColorfulConsole = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && buildServer.IsLocalBuild
                ? (IColorfulConsole) new WindowsConsole() : new AnsiConsole();

            _stopwatch.Start();
        }
示例#30
0
 /// <summary>
 /// Initialises the args.
 /// </summary>
 /// <param name="addedProjects"></param>
 /// <param name="deletedProjects"></param>
 public ServerSnapshotChangedEventArgs(string server,
                                       BuildServer configuration,
                                       IEnumerable <string> addedProjects,
                                       IEnumerable <string> deletedProjects)
 {
     this.Server        = server;
     this.Configuration = configuration;
     this.addedProjects.AddRange(addedProjects ?? new string[0]);
     this.deletedProjects.AddRange(deletedProjects ?? new string[0]);
 }
示例#31
0
        /// <summary>
        /// Initializes this instance with the appropriate information
        /// </summary>
        /// <param name="server">the BuildServer</param>
        /// <param name="session">the SessionToken</param>
        /// <param name="settings">the Settings</param>
        public void Initialize(BuildServer server, string session, Settings settings)
        {
            Configuration = server;
            SessionToken  = session;
            Settings      = settings;
            Login();
            Api = _apiFactory.Create(Configuration.Url, AuthorizationInformation, _webRequestFactory);

            ProjectsAndCurrentStatus = new Dictionary <string, ProjectStatus>();
        }
        public BuildServer AddBuildServer(BuildServer buildServer)
        {
            AddBuildServerCalls.Add(buildServer);

            buildServer.Id = buildServerId++;

            buildServers.Add(buildServer.Id, buildServer);

            return buildServer;
        }
        public IObservable<ICollection<Job>> GetJobsObservableAsync(BuildServer buildServer)
        {
            Uri jobsUri = new Uri(buildServer.Uri, "httpAuth/app/rest/buildTypes");
            var request = webRequestCreate.CreateXmlRequest(jobsUri, buildServer.Credential);

            var buildTypes = request.GetResponseObservable()
                .ParseXmlResponse()
                .Select(doc => (ICollection<Job>)MapJobs(doc, buildServer).ToList());

            return buildTypes;
        }
示例#34
0
        public IObservable<ICollection<Job>> GetJobsObservableAsync(BuildServer buildServer)
        {
            var request = (HttpWebRequest)webRequestCreate.Create(buildServer.Uri);
            request.Accept = "text/xml";

            return request.GetResponseObservable()
                .Select(response =>
                {
                    using (var stream = response.GetResponseStream())
                        return MapJobs(buildServer, XDocument.Load(stream));
                });
        }
        public IObservable<Job> UpdateAll(BuildServer buildServer, IEnumerable<Job> jobs)
        {
            log.Write("[TeamCity6Provider] Updating jobs from server: {0}", buildServer.Uri);

            var remainingJobsSet = jobs.ToDictionary(j => j);

            return this.updateStrategies.Select(strat => Observable.Defer(() =>
            {
                return remainingJobsSet.Count > 0
                    ? strat.UpdateAll(buildServer, remainingJobsSet.Keys.ToList())
                        .Do(j => { if (remainingJobsSet.ContainsKey(j)) remainingJobsSet.Remove(j); })
                    : Observable.Empty<Job>();
            }))
            .Concat();
        }
        public IObservable<Job> UpdateAll(BuildServer buildServer, IEnumerable<Job> jobs)
        {
            log.Write("[PersonalBuildsTeamCity6UpdateStrategy] Updating jobs from server: {0}", buildServer.Uri);

            var personalBuildsUri = new Uri(buildServer.Uri, "/httpAuth/app/rest/6.0/builds?locator=personal:true");

            var indexedJobs = jobs.ToDictionary(x => x.RemoteId);

            return webRequestCreate.CreateXmlRequest(personalBuildsUri, buildServer.Credential)
                .GetResponseObservable()
                .ParseXmlResponse()
                .SelectMany(buildsDoc =>
                {
                    var updatedJobs = new List<Job>();

                    foreach (var buildElement in buildsDoc.Root.Elements("build"))
                    {
                        string buildTypeId = buildElement.Attribute("buildTypeId").Value;

                        Job job;

                        if (indexedJobs.TryGetValue(buildTypeId, out job))
                        {
                            job.LastBuild = MapBuild(buildElement);
                            job.LastUpdated = clock.UtcNow;

                            indexedJobs.Remove(buildTypeId);

                            updatedJobs.Add(job);
                        }
                    }

                    log.Write("[PersonalBuildsTeamCity6UpdateStrategy] Updated {0} jobs using recent builds list",
                        updatedJobs.Count);

                    return updatedJobs;
                });
        }
        public override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            AddBuildServerCommand = CreateCommand(new ObservableCommand(), OnAddNewBuildServer);

            DeleteBuildServerCommand = CreateCommand(new ObservableCommand<BuildServer>(), OnDeleteBuildServer);

            this.SelectedBuildServer = null;

            StartLoading();

            LoadBuildServers();
        }
 public bool DeleteBuildServer(BuildServer buildServer)
 {
     throw new NotImplementedException();
 }
 public ICollection<Job> GetJobs(BuildServer buildServer)
 {
     throw new NotImplementedException();
 }
        private ICollection<Job> RemoveExistingJobs(BuildServer buildServer, ICollection<Job> jobs)
        {
            var existingJobs = jobRepository.GetJobs(buildServer);

            return jobs.Except(existingJobs)
                .ToList();
        }
示例#41
0
 private ICollection<Job> MapJobs(BuildServer buildServer, XDocument cruiseXml)
 {
     return cruiseXml.Root.Elements("Project")
         .Select(project => new Job
         {
             BuildServer = buildServer,
             Name = project.Attribute("name").Value,
             WebUri = new Uri(project.Attribute("webUrl").Value),
             LastBuild = new Build
             {
                 Result = ParseBuildResult(project.Attribute("lastBuildStatus").Value),
                 Time = ParseBuildTime(project.Attribute("lastBuildTime").Value),
                 Label = project.Attribute("lastBuildLabel").Value
             }
         })
         .ToList();
 }
示例#42
0
 private ICollection<Job> MapJobs(BuildServer buildServer, XDocument cruiseXml)
 {
     return cruiseXml.Root.Elements("job")
         .Select(project => new Job
         {
             BuildServer = buildServer,
             Name = project.Element("name").Value,
             WebUri = new Uri(project.Element("url").Value),
             LastBuild = MapBuild(project.Element("lastCompletedBuild"))
         })
         .ToList();
 }
示例#43
0
        public IObservable<BuildServer> ValidateBuildServer(BuildServer buildServer)
        {
            var request = (HttpWebRequest)webRequestCreate.Create(buildServer.Uri);
            request.Accept = "text/xml";
            request.Credentials = buildServer.Credential;

            return request.GetResponseObservable()
                .Select(response =>
                {
                    using (var stream = response.GetResponseStream())
                    {
                        if (XDocument.Load(stream).Root.Name == "Projects")
                        {
                            return buildServer;
                        }

                        throw new InvalidOperationException("Invalid build server");
                    }

                    response.Close();
                })
                .Catch<BuildServer, WebException>(ex =>
                {
                    var response = (HttpWebResponse) ex.Response;

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        return Observable.Throw<BuildServer>(new UnauthorizedAccessException());
                    }

                    return Observable.Throw<BuildServer>(ex);
                });
        }
        private void OnDeleteBuildServer(BuildServer buildServer)
        {
            var result = messageBoxFacade.Show(Strings.DeleteBuildServerConfirmationMessage,
                Strings.DeleteBuildServerConfirmationDescription, MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                Observable.ToAsync(() => this.jobController.DeleteBuildServer(buildServer), schedulerAccessor.Background)()
                    .ObserveOn(schedulerAccessor.UserInterface)
                    .Subscribe(_ =>
                    {
                        if (BuildServers.Count == 1)
                        {
                            navigationService.GoBack();
                        }
                        else
                        {
                            LoadBuildServers();
                        }
                    });
            }
        }
 internal static BuildServerEntity FromBuildServer(BuildServer buildServer, ICredentialEncryptor credentialEncryptor)
 {
     return new BuildServerEntity
     {
         Id = buildServer.Id,
         Credential = (buildServer.Credential == null)
                          ? null
                          : credentialEncryptor.Encrypt(buildServer.Credential),
         Name = buildServer.Name,
         Provider = buildServer.Provider,
         Uri = buildServer.Uri.AbsoluteUri,
     };
 }
示例#46
0
        public IObservable<BuildServer> ValidateBuildServer(BuildServer buildServer)
        {
            buildServer.Uri = (buildServer.Uri.OriginalString.EndsWith("/"))
                ? buildServer.Uri
                : new Uri(buildServer.Uri.AbsoluteUri + "/", UriKind.Absolute);

            Uri validateUri = new Uri(buildServer.Uri, ApiSuffix + "?tree=hudson");

            var request = (HttpWebRequest)webRequestCreate.Create(validateUri);
            request.Accept = "text/xml";
            request.Credentials = buildServer.Credential;

            return request.GetResponseObservable()
                .Select(response =>
                {
                    using (var stream = response.GetResponseStream())
                    {
                        if (XDocument.Load(stream).Root.Name == "hudson")
                        {
                            return buildServer;
                        }

                        throw new InvalidOperationException("Invalid build server");
                    }
                })
                .Catch<BuildServer, WebException>(ex =>
                {
                    var response = (HttpWebResponse) ex.Response;

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        return Observable.Throw<BuildServer>(new UnauthorizedAccessException());
                    }

                    return Observable.Throw<BuildServer>(ex);
                });
        }
示例#47
0
 public Job ToJob(BuildServer actualBuildServer)
 {
     return new Job
     {
         Id = id,
         Name = name,
         Alias = alias,
         RemoteId = remoteId,
         NotificationPreference = (NotificationReason) NotificationPreference,
         WebUri = (WebUri == null)
                      ? null
                      : new Uri(WebUri, UriKind.Absolute),
         LastUpdated = lastUpdated.HasValue
             ? (DateTimeOffset?)FromDbDate(lastUpdated.Value)
             : null,
         LastBuild = new Build
         {
             Label = lastBuildLabel,
             Result = (BuildResult)lastBuildResult,
             Time = lastBuildTime
         },
         BuildServer = actualBuildServer
     };
 }
 private IEnumerable<Job> MapJobs(XDocument document, BuildServer buildServer)
 {
     return document.Root.Elements("buildType")
         .Select(jobElement => new Job
         {
             // TODO: It would be nice to use @projectName here somehow
             RemoteId = jobElement.Attribute("id").Value,
             Name = jobElement.Attribute("name").Value,
             WebUri = new Uri(jobElement.Attribute("webUrl").Value),
             BuildServer = buildServer
         });
 }
        public IObservable<BuildServer> ValidateBuildServer(BuildServer buildServer)
        {
            var validateUri = new Uri(buildServer.Uri, "httpAuth/app/rest/6.0/version");

            log.Write("[TeamCity6Provider] Validating server: {0}", validateUri);

            var request = webRequestCreate.CreateTextRequest(validateUri, buildServer.Credential);

            return request.GetResponseObservable()
                .Select(response =>
                {
                    using (var stream = response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        string contentType = response.Headers[HttpRequestHeader.ContentType];

                        if (contentType != "text/plain")
                        {
                            throw new InvalidOperationException("Expected text/plain response from version service");
                        }

                        int version;
                        if (!Int32.TryParse(reader.ReadToEnd(), out version))
                        {
                            throw new InvalidOperationException("Invalid version response");
                        }

                        log.Write("[TeamCity6Provider] Validated Team City 6 server (REST API version: {0})", version);

                        return buildServer;
                    }
                });
        }