public void RemoveAllUsers() { // CTX.driver.Url = "http://bimtrackapp.co"; CTX.driver.Url = "https://qa.bimtrack.co/"; BTLogin login = new BTLogin(); login.LogIn("*****@*****.**", "Z3nt3l1499!"); BTHubsTracks btHubsTracks = new BTHubsTracks(); ProjectList prjList = btHubsTracks.OpenHubByName("ZenyTest"); prjList.SelectProject("ZENPROJECT001"); MainProject mainProject = new MainProject(); SideBarMenu sideBarMenu = mainProject.GetSidebarMenu(); sideBarMenu.ClickMenuItem("Hub Settings"); HubSettings hubSettings = new HubSettings(); UserManagementForm userForm = new UserManagementForm(hubSettings.GetRoot()); userForm.RemoveAllUsers(); CTX.driver.Close(); }
public void RemoveAllUsers() { KeyChain kc = CTX.keyChain; CTX.driver.Url = kc.UrlBimTrack; BTLogin login = new BTLogin(); login.LogIn(kc.LoginUsername, kc.LoginPassword); BTHubsTracks btHubsTracks = new BTHubsTracks(); ProjectList prjList = btHubsTracks.OpenHubByName(kc.HubName); prjList.SelectProject(kc.DefaultProject); MainProject mainProject = new MainProject(); SideBarMenu sideBarMenu = mainProject.GetSidebarMenu(); sideBarMenu.ClickMenuItem("Hub Settings"); HubSettings hubSettings = new HubSettings(); UserManagementForm userForm = new UserManagementForm(hubSettings.GetRoot()); userForm.RemoveAllUsers(); CTX.driver.Close(); }
static void Main(string[] args) { // DcEngine is the main thing we will work with // use EngineSettings structure to set various settings of the engine Engine = new DcEngine(); // we need to have at least one hub connection to work with var hubSettings = new HubSettings { HubAddress = "_write_your_hub_address_here_", HubName = "My hub", Nickname = "sharpdc" }; var hubConnection = new HubConnection(hubSettings); // we want to see the hub connection status changes for debug puropses hubConnection.ConnectionStatusChanged += (sender, e) => Console.WriteLine("Hub " + e.Status); // add this connection to the engine Engine.Hubs.Add(hubConnection); // this event will be called when at least one hub will be connected and logged in Engine.ActiveStatusChanged += delegate { // to download a file we need to have a magnet-link var magnet = new Magnet("magnet:?xt=urn:tree:tiger:3UOKTPAQUGWGKWFIL75ZDMTTQLWF5AM2BAXBVEA&xl=63636810&dn=TiX_1_zvukovoy_barrier.avi"); Console.WriteLine("Downloading the " + magnet.FileName); // the file will be saved in the current folder by default // you can provide custom file name: // engine.DownloadFile(magnet, "C:\\Temp\\my_name.avi"); Engine.DownloadFile(magnet); }; // we want to know when we have download complete Engine.DownloadManager.DownloadCompleted += (sender, e) => Console.WriteLine("Download is complete! Press enter to exit."); Console.WriteLine("Welcome to the sharpdc example"); Console.WriteLine("We try to download a file"); Console.WriteLine("Press enter to exit"); // the engine to work needs Update() method to be called periodically // we can call it manually or use built-in method StartAsync() // that will use System.Threading.Timer to call Update() with 200 msec interval Engine.StartAsync(); // would be cool to see download progress if any // so we call DisplayDownloadInfo method in other thread new ThreadStart(DisplayDownloadInfo).BeginInvoke(null, null); Console.ReadLine(); }
/* * Environnement: * DEV: https://dev.bimtrack.co/en/Login * QA: https://qa.bimtrack.co/en/Login * PROD: https://bimtrackapp.co/en/Login (edited) */ public void createUser() { KeyChain kc = CTX.keyChain; CTX.driver.Url = kc.UrlBimTrack; BTLogin login = new BTLogin(); login.LogIn(kc.LoginUsername, kc.LoginPassword); BTHubsTracks btHubsTracks = new BTHubsTracks(); ProjectList prjList = btHubsTracks.OpenHubByName(kc.HubName); prjList.SelectProject(kc.DefaultProject); MainProject mainProject = new MainProject(); SideBarMenu sideBarMenu = mainProject.GetSidebarMenu(); sideBarMenu.ClickMenuItem("Hub Settings"); HubSettings hubSettings = new HubSettings(); UserManagementForm userForm = hubSettings.ClickButtonAddUser(); var emailSuffix = BimTrackUser.GetNewUserSuffix(); var email = BimTrackUser.GetUniqueUserEmail(emailSuffix); if (userForm.AddNewUser(new BimTrackUser(email, true))) { // PROCESS EMAIL BimEmailProcessor proc = new BimEmailProcessor(); string szLink = null; while (szLink == null) { szLink = proc.GetLatestActivationForUser(emailSuffix); Console.Out.WriteLine("Loop waiting"); Thread.Sleep(1500); } Console.Out.WriteLine("SzLink == " + szLink); CTX.driver.Close(); // Complete the user creation new CompleteUserFormTest().ActivateUser(szLink); //hubSettings.FillNewUserInformation(userSuffix, true); Thread.Sleep(1500); } CTX.driver.Close(); }
/* * Environnement: * DEV: https://dev.bimtrack.co/en/Login * QA: https://qa.bimtrack.co/en/Login * PROD: https://bimtrackapp.co/en/Login (edited) */ public void startBimTrack() { // CTX.driver.Url = "http://bimtrackapp.co"; CTX.driver.Url = "https://qa.bimtrack.co/"; BTLogin login = new BTLogin(); login.LogIn("*****@*****.**", "Z3nt3l1499!"); BTHubsTracks btHubsTracks = new BTHubsTracks(); ProjectList prjList = btHubsTracks.OpenHubByName("ZenyTest"); prjList.SelectProject("ZENPROJECT001"); MainProject mainProject = new MainProject(); SideBarMenu sideBarMenu = mainProject.GetSidebarMenu(); sideBarMenu.ClickMenuItem("Hub Settings"); HubSettings hubSettings = new HubSettings(); UserManagementForm userForm = hubSettings.ClickButtonAddUser(); var emailSuffix = BimTrackUser.GetNewUserSuffix(); var email = BimTrackUser.GetUniqueUserEmail(emailSuffix); userForm.AddNewUser(new BimTrackUser(email, true)); // PROCESS EMAIL BimEmailProcessor proc = new BimEmailProcessor(); string szLink = null; while (szLink == null) { szLink = proc.GetLatestActivationForUser(emailSuffix); Console.Out.WriteLine("Loop waiting"); Thread.Sleep(1500); } Console.Out.WriteLine("SzLink == " + szLink); CTX.driver.Close(); // Complete the user creation new CompleteUserFormTest().ActivateUser(szLink); //hubSettings.FillNewUserInformation(userSuffix, true); Thread.Sleep(1500); CTX.driver.Close(); }
public HubManager( ILogger <HubService> log, IOptions <ChainSettings> chainSettings, IOptions <HubSettings> hubSettings, IServiceProvider serviceProvider, IHubContext <WebSocketHub> hubContext, HubConnectionManager connectionManager) { this.log = log; this.chainSettings = chainSettings.Value; this.hubSettings = hubSettings.Value; this.hubContext = hubContext; this.serviceProvider = serviceProvider; Connections = connectionManager; TrustedHubs = new List <string>(); AvailableHubs = new Dictionary <string, HubInfo>(); ConnectedHubs = new Dictionary <string, HubInfo>(); }
private static void DeleteReportsFromHub(Report report, HubSettings settings, Connection socketConnection) { try { var reportOwner = settings.Owner; var qrsApi = GetQrsApiConnection(socketConnection); var sharedContentInfos = qrsApi.GetSharedContentAsync(new HubSelectRequest())?.Result; if (sharedContentInfos == null) { logger.Debug("No shared content found."); } foreach (var reportPath in report.Paths) { var fileData = report.Data.FirstOrDefault(f => f.Filename == Path.GetFileName(reportPath)); var contentName = GetContentName(report?.Name ?? null, fileData); var sharedContentList = sharedContentInfos.Where(s => s.Name == contentName).ToList(); foreach (var sharedContent in sharedContentList) { var serMetaType = sharedContent.MetaData.Where(m => m.Key == "ser-type" && m.Value == "report").SingleOrDefault() ?? null; if (sharedContent.MetaData == null) { serMetaType = new MetaData(); } if (serMetaType != null && sharedContent.Owner.ToString().ToLowerInvariant() == reportOwner.ToLowerInvariant()) { qrsApi.DeleteSharedContentAsync(new HubDeleteRequest() { Id = sharedContent.Id.Value }).Wait(); } } } settings.Mode = DistributeMode.CREATEONLY; } catch (Exception ex) { logger.Error(ex, "Reports could not delete"); } }
private void btnTestConnection_Click(object sender, RoutedEventArgs e) { try { var hubSettings = new HubSettings() { ServerUrl = txtHubServerUrl.Text, Username = txtHubUsername.Text, Password = txtHubPassword.Password, Timeout = txtHubTimeout.Text, ProxyHost = txtProxyHost.Text, ProxyPort = txtProxyPort.Text, ProxyUsername = txtProxyUsername.Text, ProxyPassword = txtProxyPassword.Password }; if (hubSettings.HasSettings()) { var client = Authenticate.EstablishHubSession(hubSettings); MessageBox.Show(client != null ? Properties.Resources.MessageConnectionSuccessful : Properties.Resources.MessageConnectionUnsuccessful); } else { MessageBox.Show(Properties.Resources.MesageNoHubSettings); } } catch (Exception ex) { MessageBox.Show(Properties.Resources.MessageError); TaskManager.AddError(Properties.Resources.PaneTitle + ": " + ex.ToString()); } }
public static RestClient EstablishHubSession(HubSettings hubSettings) { var client = new RestClient(hubSettings.ServerUrl) { CookieContainer = new CookieContainer() }; if (!String.IsNullOrWhiteSpace(hubSettings.ProxyHost)) { var proxy = new WebProxy(); var uriBuilder = new UriBuilder(); uriBuilder.Host = hubSettings.ProxyHost; int port; if (int.TryParse(hubSettings.ProxyPort, out port)) { uriBuilder.Port = port; } try { var uri = uriBuilder.Uri; proxy.Address = uri; proxy.Credentials = new NetworkCredential(hubSettings.ProxyUsername, hubSettings.ProxyPassword); client.Proxy = proxy; } catch (Exception e) { throw new Exception("Hub Proxy Error", e); } } /* //Required to debug on the QA server as of 6/12/2017 due to SSL self signed cert. This ignores SSL errors. * ServicePointManager.ServerCertificateValidationCallback += * (sender, certificate, chain, sslPolicyErrors) => true; */ if (!String.IsNullOrEmpty(hubSettings.Timeout)) { client.Timeout = TimeSpan.FromSeconds(Int32.Parse(hubSettings.Timeout)).Milliseconds; } var authRequest = new RestRequest("j_spring_security_check", Method.POST).AddParameter( "application/x-www-form-urlencoded", $"j_username={hubSettings.Username}&j_password={hubSettings.Password}", ParameterType.RequestBody); var response = client.Execute(authRequest); var csrfParam = response.Headers.Where(param => param.Name == CsrfHeaderKey && !String.IsNullOrEmpty(param?.Value?.ToString())).FirstOrDefault(); if (csrfParam != null) { client.DefaultParameters.Add(csrfParam); } if (response.StatusCode == HttpStatusCode.NoContent) { return(client); } else if (response.StatusCode == HttpStatusCode.Unauthorized) { return(null); } else if (response.ErrorException != null) { return(null); } else { return(client);//to be safe, otherwise return the client. } }
public HubService(HubManager manager, IOptions <HubSettings> settings) { this.manager = manager; this.settings = settings.Value; }
private async Task <bool> GetPackagesAndRiskInformation(IEnumerable <Project> projects) { var status = false; await Task.Run(() => { var hubSettings = new HubSettings() { ServerUrl = _package.HubServerUrl, Username = _package.HubUsername, Password = _package.HubPassword, Timeout = _package.HubTimeout, ProxyHost = _package.ProxyHost, ProxyPort = _package.ProxyPort, ProxyUsername = _package.ProxyUsername, ProxyPassword = _package.ProxyPassword }; if (!_installerServices.GetInstalledPackages().Any()) { return; } if (!hubSettings.HasSettings()) { _riskAnalysisStatus = Properties.Resources.MesageNoHubSettings; status = false; } else { var client = Authenticate.EstablishHubSession(hubSettings); if (client == null) { _riskAnalysisStatus = Properties.Resources.MessageConnectionUnsuccessful; status = false; } else { String version = HubVersion.GetHubVersionNumberString(client); bool hubLessThanFour = int.Parse(version.Split('.')[0]) < 4; _packagesList.Clear(); _validProjectsList.Clear(); _validProjectsList.Add(Properties.Resources.ItemAll); foreach (var project in projects) { List <IVsPackageMetadata> packages = null; try { packages = _installerServices.GetInstalledPackages(project).ToList(); _validProjectsList.Add(project.Name); } catch { continue; } var projectPath = project.Properties; foreach (var package in packages) { var index = _packagesList.FindIndex( item => (item.Package == package.Id) && (item.Version == package.VersionString)); if (index < 0) { _packagesList.Add(new NuGetPackageViewModel.NuGetPackage { Forge = Properties.Resources.Forge, Package = package.Id, Version = package.VersionString, VsProject = project.Name }); } else { _packagesList[index].VsProject = _packagesList[index].VsProject + "|" + project.Name; } } } foreach (var item in _packagesList) { try { ProcessItem(item, client, hubLessThanFour); } catch (Exception e) { _riskAnalysisStatus = e.Message; status = false; } } if (_packagesList.Count > 0) { _packagesList = _packagesList.OrderBy(x => x.PackageStatus).ThenBy(y => y.Package).ToList(); } _validProjectsList.Sort(); status = true; Task.Run(() => CollectData.CallHome(client, hubSettings.ServerUrl, _dte.Version)); } } }); return(status); }
public SignalRService(HubSettings hubSettings) { _hubUrl = hubSettings.HubUrl; }
public void UploadToHub(Report report, HubSettings settings, Connection socketConnection) { var reportName = report?.Name ?? null; if (String.IsNullOrEmpty(reportName)) { throw new Exception("The report filename is empty."); } if (String.IsNullOrEmpty(settings.Owner)) { throw new Exception("No owner for shared content found."); } //Delete reports from hub before uploaded! if (settings.Mode == DistributeMode.DELETEALLFIRST) { DeleteReportsFromHub(report, settings, socketConnection); } foreach (var reportPath in report.Paths) { try { var fileData = report.Data.FirstOrDefault(f => f.Filename == Path.GetFileName(reportPath)); var contentName = GetContentName(reportName, fileData); // Copy with report name - Important for other delivery options. var uploadCopyReportPath = Path.Combine(Path.GetDirectoryName(reportPath), $"{reportName}{Path.GetExtension(reportPath)}"); File.Copy(reportPath, uploadCopyReportPath, true); if (settings.Mode == DistributeMode.OVERRIDE || settings.Mode == DistributeMode.CREATEONLY) { var uploadResult = new HubResult() { ReportName = reportName, }; HubInfo hubInfo = null; Guid? hubUserId = null; var qrsApi = GetQrsApiConnection(socketConnection); logger.Debug($"Use the following Qlik user '{settings.Owner}'..."); var hubUser = new DomainUser(settings.Owner, true); var filter = $"userId eq '{hubUser.UserId}' and userDirectory eq '{hubUser.UserDirectory}'"; logger.Debug($"Use Filter '{filter}'..."); var result = qrsApi.SendRequestAsync("user", HttpMethod.Get, null, filter).Result; logger.Debug($"QRS Result for user: '******'"); if (result == null || result == "[]") { throw new Exception($"Qlik user {settings.Owner} was not found or session not connected (QRS)."); } var userObject = JArray.Parse(result); if (userObject.Count > 1) { throw new Exception($"Too many User found. {result}"); } else if (userObject.Count == 1) { hubUserId = new Guid(userObject.First()["id"].ToString()); } logger.Debug($"hubUser id is '{hubUserId}'."); var sharedContent = GetSharedContentFromUser(contentName, hubUser, qrsApi); if (sharedContent == null) { var createRequest = new HubCreateRequest() { Name = contentName, ReportType = settings.SharedContentType, Description = "Created by Analytics Gate", Tags = new List <Tag>() { new Tag() { Name = "SER", CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now } }, Data = new ContentData() { ContentType = $"application/{Path.GetExtension(fileData.Filename).Trim('.')}", ExternalPath = Path.GetFileName(uploadCopyReportPath), FileData = fileData.DownloadData, } }; logger.Debug($"Create request '{JsonConvert.SerializeObject(createRequest)}'"); hubInfo = qrsApi.CreateSharedContentAsync(createRequest).Result; logger.Debug($"Create response '{JsonConvert.SerializeObject(hubInfo)}'"); } else { if (settings.Mode == DistributeMode.OVERRIDE) { var tag = sharedContent?.Tags?.FirstOrDefault(t => t.Name == "SER") ?? null; if (tag != null) { tag.CreatedDate = DateTime.Now; tag.ModifiedDate = DateTime.Now; } var updateRequest = new HubUpdateRequest() { Info = sharedContent, Data = new ContentData() { ContentType = $"application/{Path.GetExtension(fileData.Filename).Trim('.')}", ExternalPath = Path.GetFileName(uploadCopyReportPath), FileData = fileData.DownloadData, } }; logger.Debug($"Update request '{JsonConvert.SerializeObject(updateRequest)}'"); hubInfo = qrsApi.UpdateSharedContentAsync(updateRequest).Result; logger.Debug($"Update response '{JsonConvert.SerializeObject(hubInfo)}'"); } else { throw new Exception($"The shared content '{contentName}' already exist."); } } if (hubUserId != null) { //change shared content owner logger.Debug($"Change shared content owner '{hubUserId}' (User: '******')."); var newHubInfo = new HubInfo() { Id = hubInfo.Id, Type = settings.SharedContentType, Owner = new Owner() { Id = hubUserId.ToString(), UserId = hubUser.UserId, UserDirectory = hubUser.UserDirectory, Name = hubUser.UserId, } }; var changeRequest = new HubUpdateRequest() { Info = newHubInfo, }; logger.Debug($"Update Owner request '{JsonConvert.SerializeObject(changeRequest)}'"); var ownerResult = qrsApi.UpdateSharedContentAsync(changeRequest).Result; logger.Debug($"Update Owner response '{JsonConvert.SerializeObject(ownerResult)}'"); } // Get fresh shared content infos var filename = Path.GetFileName(uploadCopyReportPath); filename = filename.Replace("+", " "); hubInfo = GetSharedContentFromUser(contentName, hubUser, qrsApi); logger.Debug("Get shared content link."); var link = hubInfo?.References?.FirstOrDefault(r => r.LogicalPath.Contains($"/{filename}"))?.ExternalPath ?? null; if (link == null) { throw new Exception($"The download link is empty. Please check the security rules. (Name: {filename} - References: {hubInfo?.References?.Count}) - User: {hubUser}."); } Results.Add(new HubResult() { Success = true, ReportState = GetFormatedState(), TaskName = JobResult.TaskName, Message = "Upload to the hub was successful.", Link = link, ReportName = contentName, FullLink = GetFullLink(qrsApi.ConnectUri, link) }); } else { throw new Exception($"Unknown hub mode {settings.Mode}"); } } catch (Exception ex) { logger.Error(ex, "The delivery via 'Hub' failed."); JobResult.Exception = ReportException.GetException(ex); JobResult.Status = TaskStatusInfo.ERROR; Results.Add(new HubResult() { Success = false, ReportState = "ERROR", TaskName = JobResult.TaskName, Message = ex.Message }); } finally { socketConnection.IsFree = true; } } }
public DiskStorage(IOptions <HubSettings> settings) { this.settings = settings.Value; dataFolder = new DirectoryInfo(this.settings.DataFolder); }
public HubConnection(HubSettings settings) : base(settings.HubAddress) { Users = new ConcurrentDictionary <string, UserInfo>(); Settings = settings; ConnectionStatusChanged += HubConnectionConnectionStatusChanged; }