public async Task OnExecute(IConsole console) { console.WriteLine("Starting Boost UI..."); var port = NetworkExtensions.GetAvailablePort(Port); if (port != Port) { console.WriteLine($"Port {Port} is allready in use.", ConsoleColor.Yellow); var useOther = Prompt.GetYesNo($"Start UI on port: {port}", true); if (useOther) { Port = port; } else { return; } } _webServer.LogLevel = LogLevel; var url = await _webServer.StartAsync(Port); if (!Debugger.IsAttached) { if (Path is { })
public void TestToEndPointWithLoopbackAddress() { IPEndPoint endpointFromHostname = NetworkExtensions.ToEndPoint("localhost", ServicesPort); IPEndPoint endpointFromIp = NetworkExtensions.ToEndPoint("127.0.0.1", ServicesPort); string expectedEndpoint = "127.0.0.1:" + ServicesPort; Assert.AreEqual(expectedEndpoint, endpointFromHostname.ToString()); Assert.AreEqual(expectedEndpoint, endpointFromIp.ToString()); }
public async Task OnExecute(IConsole console) { console.WriteLine("Starting local proxy"); var port = NetworkExtensions.GetAvailablePort(Port); if (port != Port) { console.WriteLine($"Port {Port} is allready in use.", ConsoleColor.Yellow); var useOther = Prompt.GetYesNo($"Start proxy on port: {port}", true); if (useOther) { Port = port; } else { return; } } var options = new LocalProxyOptions { Port = Port, DestinationAddress = DestinationAddress }; string url = await _proxyServer.StartAsync( options, CommandAborded); ProcessHelpers.OpenBrowser(url); var stopMessage = "Press 'q' or 'esc' to stop"; console.WriteLine(stopMessage); while (true) { ConsoleKeyInfo key = Console.ReadKey(); if (key.KeyChar == 'q' || key.Key == ConsoleKey.Escape) { break; } else { console.ClearLine(); console.WriteLine("Unknown command", ConsoleColor.Red); Console.WriteLine(stopMessage); } } console.WriteLine("Stopping proxy...."); await _proxyServer.StopAsync(); _proxyServer.Dispose(); }
public IEnumerable <ICommunicationInterface> GetAllInterfaces() { var advanvedInfoList = SocketLite.Helper.AdapterInfo.GetAdapters(); var profiles = NetworkInformation .GetConnectionProfiles() .Where(c => c.NetworkAdapter != null) .GroupBy(c => c.NetworkAdapter.NetworkAdapterId) .Select(x => x.FirstOrDefault()) .ToDictionary(c => c.NetworkAdapter.NetworkAdapterId.ToString(), c => c); return(NetworkInformation.GetHostNames() .Where(h => h.IPInformation?.NetworkAdapter != null && h.Type == HostNameType.Ipv4 && h.IPInformation.PrefixLength != null) .Select(h => { var adapter = h.IPInformation?.NetworkAdapter; var adapterId = adapter?.NetworkAdapterId.ToString(); var subnetAddress = NetworkExtensions.GetSubnetAddress( h.CanonicalName, h.IPInformation.PrefixLength.Value); //var t = profiles[adapterId].NetworkAdapter; //var u = t.GetConnectedProfileAsync(); //var r = u.GetResults(); //t.NetworkItem.GetNetworkTypes(). ConnectionProfile connectProfile; var adapterName = profiles.TryGetValue(adapterId, out connectProfile) ? connectProfile.ProfileName : "{ unknown }"; return new CommunicationsInterface { NativeInterfaceId = adapterId, //IsInternetConnected = profiles?[adapterId]?.NetworkAdapter?.NetworkItem?.GetNetworkTypes() == NetworkTypes.Internet, GatewayAddress = advanvedInfoList?.FirstOrDefault(x => x?.AdapterId == adapterId)?.Gateway, Name = adapterName, IpAddress = h.CanonicalName, BroadcastAddress = NetworkExtensions.GetBroadcastAddress(IpAddress, subnetAddress), NativeHostName = h, NativeNetworkAdapter = adapter, ConnectionStatus = CommunicationConnectionStatus.Unknown }; })); }
public Config() { do { SelectedPort = random.Next(8000, 55535 + 1); var isOpen = NetworkExtensions.ScanPort(SelectedPort).Result; if (isOpen) { usedPorts.AddOrUpdate(SelectedPort, i => byte.MinValue, (i, b) => byte.MinValue); } Logger?.Invoke($"Trying port {SelectedPort}({isOpen})"); }while (usedPorts.ContainsKey(SelectedPort)); usedPorts.AddOrUpdate(SelectedPort, i => byte.MinValue, (i, b) => byte.MinValue); Logger = message => Debug.WriteLine(message); }
public void TestToEndPointWithExternalAddress() { const string DeltaEngineExternalIp = "217.91.31.182"; IPEndPoint endpointFromDomain = NetworkExtensions.ToEndPoint("deltaengine.net", ServicesPort); IPEndPoint endpointFromIp = NetworkExtensions.ToEndPoint(DeltaEngineExternalIp, ServicesPort); #if DEBUG const string DeltaEngineInternalIp = "192.168.0.5"; #else const string DeltaEngineInternalIp = "127.0.0.1"; #endif var validEndpoints = new[] { DeltaEngineExternalIp + ":" + ServicesPort, DeltaEngineInternalIp + ":" + ServicesPort }; Assert.Contains(endpointFromDomain.ToString(), validEndpoints); Assert.Contains(endpointFromIp.ToString(), validEndpoints); }
private void timerInternalIp_Elapsed(object sender, ElapsedEventArgs e) { if (!UserSettings.GlobalSettings.VisibilityNetworkInternalIp) { return; } string ip = null; try { ip = NetworkExtensions.GetLocalIpAddress(); } catch (Exception ex) { Logger.Write("NetworkTicker() - NetworkExtensions.GetLocalIpAddress() - Exception raised", true, ex); } InternalIpAddress = !string.IsNullOrEmpty(ip) ? ip : "N/A"; }
/// <summary> /// Creates an instance with the default configuration with the specified root dirctory and remote option. /// </summary> public PackageDeployerService(string rootDirectory, bool allowRemote, string securitySettings) : this(NetworkExtensions.GetFullHostName(), MrdsConstants.PackageDeployerServiceDefaultPort, rootDirectory, allowRemote, securitySettings) { }
public async Task <IActionResult> OnPostAsync() { // Get the current user. var user = await _userManager.GetUserAsync(User); // Check if there aren't any IDs provided. if (Input.Ids == null || !Input.Ids.Any()) { // Display a message. TempData["StatusMessage"] = "Error: No or invalid IDs have been provided."; // Redirect to the index page. return(RedirectToPage("/Content/DatabaseTypes/PPI/Created/Networks/Index")); } // Define the view. View = new ViewModel { Items = _context.Networks .Where(item => item.NetworkDatabases.Any(item1 => item1.Database.DatabaseType.Name == "PPI")) .Where(item => item.IsPublic || item.NetworkUsers.Any(item1 => item1.User == user)) .Where(item => Input.Ids.Contains(item.Id)) }; // Check if there weren't any items found. if (View.Items == null || !View.Items.Any()) { // Display a message. TempData["StatusMessage"] = "Error: No networks have been found with the provided IDs, or you don't have access to them."; // Redirect to the index page. return(RedirectToPage("/Content/DatabaseTypes/PPI/Created/Networks/Index")); } // Check if the reCaptcha is valid. if (!await _reCaptchaChecker.IsValid(Input.ReCaptchaToken)) { // Add an error to the model. ModelState.AddModelError(string.Empty, "The reCaptcha verification failed."); // Return the page. return(Page()); } // Check if the provided model isn't valid. if (!ModelState.IsValid) { // Add an error to the model. ModelState.AddModelError(string.Empty, "An error has been encountered. Please check again the input fields."); // Redisplay the page. return(Page()); } // Return the streamed file. return(new FileCallbackResult(MediaTypeNames.Application.Zip, async(zipStream, _) => { // Define a new ZIP archive. using var archive = new ZipArchive(zipStream, ZipArchiveMode.Create); // Check if the overview file should be added. if (true) { // Create a new entry in the archive and open it. using var stream = archive.CreateEntry($"Networks-List.txt", CompressionLevel.Fastest).Open(); // Write to the entry the corresponding file content. await NetworkExtensions.WriteToStreamOverviewTextFileContent(View.Items.Select(item => item.Id), stream, _serviceProvider, HttpContext.Request.Scheme, HttpContext.Request.Host); } // Check which should be the format of the files within the archive. if (Input.FileFormat == "txt") { // Go over each of the networks to download. foreach (var network in View.Items) { // Create a new entry in the archive and open it. using var stream = archive.CreateEntry($"Network-{network.Name.Replace(" ", "-")}-{network.Id}.txt", CompressionLevel.Fastest).Open(); // Write to the entry the corresponding file content. await network.WriteToStreamTxtFileContent(stream, _serviceProvider); } } if (Input.FileFormat == "sif") { // Go over each of the networks to download. foreach (var network in View.Items) { // Create a new entry in the archive and open it. using var stream = archive.CreateEntry($"Network-{network.Name.Replace(" ", "-")}-{network.Id}.sif", CompressionLevel.Fastest).Open(); // Write to the entry the corresponding file content. await network.WriteToStreamSifFileContent(stream, _serviceProvider); } } else if (Input.FileFormat == "json") { // Go over each of the networks to download. foreach (var network in View.Items) { // Create a new entry in the archive and open it. using var stream = archive.CreateEntry($"Network-{network.Name.Replace(" ", "-")}-{network.Id}.json", CompressionLevel.Fastest).Open(); // Write to the entry the corresponding file content. await network.WriteToStreamJsonFileContent(stream, _serviceProvider); } } else if (Input.FileFormat == "cyjs") { // Go over each of the networks to download. foreach (var network in View.Items) { // Create a new entry in the archive and open it. using var stream = archive.CreateEntry($"Network-{network.Name.Replace(" ", "-")}-{network.Id}.cyjs", CompressionLevel.Fastest).Open(); // Write to the entry the corresponding file content. await network.WriteToStreamCyjsFileContent(stream, _serviceProvider); } } else if (Input.FileFormat == "xlsx") { // Go over each of the networks to download. foreach (var network in View.Items) { // Create a new entry in the archive and open it. using var stream = archive.CreateEntry($"Network-{network.Name.Replace(" ", "-")}-{network.Id}.xlsx", CompressionLevel.Fastest).Open(); // Write to the entry the corresponding file content. await network.WriteToStreamXlsxFileContent(stream, _serviceProvider); } } }) { FileDownloadName = $"NetControl4BioMed-Networks-{DateTime.UtcNow:yyyyMMdd}.zip" });
/// <summary> /// Starts the services when the Windows service is started. /// </summary> protected override void OnStart(string[] args) { // Start service... // No service start/success message logging is required because the AutoLog feature is enabled // and required to catch messages during .NET AppDomain creation, e.g. assembly load failure. try { // Delay start when option is configured var delay = Settings.Default.StartDelay; while (delay-- > 0) { RequestAdditionalTime(1000); Thread.Sleep(1000); // Set breakpoint here to debug service start-up } // Set current directory to service executable path (default is system directory) var programDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Debug.Assert(programDirectory != null); Directory.SetCurrentDirectory(programDirectory); // Get host name from configuration or local DNS name var hostName = Settings.Default.HostName; if (hostName != null) { hostName = hostName.Trim(); } if (String.IsNullOrWhiteSpace(hostName) || hostName.Equals("localhost", StringComparison.OrdinalIgnoreCase) || hostName.Equals("127.0.0.1", StringComparison.OrdinalIgnoreCase) || hostName.Equals("::1", StringComparison.OrdinalIgnoreCase)) { hostName = NetworkExtensions.GetFullHostName(); } // Get root directory from configuration or service path var rootDirectory = Settings.Default.PackageDeployerRootDirectory; if (rootDirectory != null) { rootDirectory = rootDirectory.Trim(); } rootDirectory = !String.IsNullOrWhiteSpace(rootDirectory) ? Path.Combine(programDirectory, rootDirectory) : programDirectory; // Get security settings var security = SecurityManager.CreateDefault(); var securitySettings = SecurityManager.Serialize(security); // Start Package Deployer RequestAdditionalTime(Settings.Default.ServiceStartTimeout * 1000); _packageDeployer = new PackageDeployerService(hostName, Settings.Default.PackageDeployerPort, rootDirectory, true, securitySettings); _packageDeployer.Error += OnHostedServiceError; _packageDeployer.Start(); } catch (ConfigurationException error) { // Log configuration errors directly to event log (TraceSource will not work as config failed) EventLog.WriteEntry(MrdsToolkitConstants.ServiceHostTraceSourceName, error.GetFullMessage(true), EventLogEntryType.Error); } catch (Exception error) { // Log failure _log.TraceEvent(TraceEventType.Error, 0, Resources.ServiceFailedToStart, error.GetFullMessage(true)); // Re-throw exception to cause start to fail throw; } }
/// <summary> /// Deletes the items from the database. /// </summary> /// <param name="serviceProvider">The application service provider.</param> /// <param name="token">The cancellation token for the task.</param> public async Task DeleteAsync(IServiceProvider serviceProvider, CancellationToken token) { // Check if there weren't any valid items found. if (Items == null) { // Throw an exception. throw new TaskException("No valid items could be found with the provided data."); } // Get the total number of batches. var count = Math.Ceiling((double)Items.Count() / ApplicationDbContext.BatchSize); // Go over each batch. for (var index = 0; index < count; index++) { // Check if the cancellation was requested. if (token.IsCancellationRequested) { // Break. break; } // Get the items in the current batch. var batchItems = Items .Skip(index * ApplicationDbContext.BatchSize) .Take(ApplicationDbContext.BatchSize); // Get the IDs of the items in the current batch. var batchIds = batchItems.Select(item => item.Id); // Define the list of items to get. var networks = new List <Network>(); // Use a new scope. using (var scope = serviceProvider.CreateScope()) { // Use a new context instance. using var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); // Get the items with the provided IDs. var items = context.Networks .Where(item => batchIds.Contains(item.Id)); // Check if there were no items found. if (items == null || !items.Any()) { // Continue. continue; } // Get the items found. networks = items .ToList(); } // Get the IDs of the items. var networkIds = networks .Select(item => item.Id); // Delete the dependent entities. await NetworkExtensions.DeleteDependentAnalysesAsync(networkIds, serviceProvider, token); await NetworkExtensions.DeleteDependentGenericEdgesAsync(networkIds, serviceProvider, token); await NetworkExtensions.DeleteDependentGenericNodesAsync(networkIds, serviceProvider, token); // Delete the related entities. await NetworkExtensions.DeleteRelatedEntitiesAsync <NetworkNodeCollection>(networkIds, serviceProvider, token); await NetworkExtensions.DeleteRelatedEntitiesAsync <NetworkEdge>(networkIds, serviceProvider, token); await NetworkExtensions.DeleteRelatedEntitiesAsync <NetworkNode>(networkIds, serviceProvider, token); await NetworkExtensions.DeleteRelatedEntitiesAsync <NetworkDatabase>(networkIds, serviceProvider, token); await NetworkExtensions.DeleteRelatedEntitiesAsync <NetworkUserInvitation>(networkIds, serviceProvider, token); await NetworkExtensions.DeleteRelatedEntitiesAsync <NetworkUser>(networkIds, serviceProvider, token); // Delete the items. await IEnumerableExtensions.DeleteAsync(networks, serviceProvider, token); } }