private void manager_connectionEvent(ConnectionInformation connection) { uint ID = connection.GetConnectionID(); connection.OnConnectionClosed += connectionChanged; liveConnections.Add(ID, connection); connection.StartPacketProcessing(); }
private void connectionChanged(ConnectionInformation information) { //if (state == ConnectionState.closed) { CloseConnection(information.GetConnectionID()); liveConnections.Remove(information.GetConnectionID()); information.OnConnectionClosed -= connectionChanged; } }
public Session(ConnectionInformation pSock) { mSock = pSock; Authorizated = false; (pSock.Parser as HeartbeatParser).OnDataReceived += BytesReceived; Logging.WriteLine("Received connection"); SendData("authreq"); pSock.StartPacketProcessing(); }
internal GameClient(uint ClientId, ConnectionInformation pConnection) { this.Id = ClientId; this.ignoredPingCount = 0; this.modeldataSent = false; this.Connection = pConnection; this.SetDoorPos = false; this.packetParser = new GamePacketParser(this); this.sessionData = new SessionDataProvider(); }
public WorkingProcess(Server webServer, Stream stream, ConnectionInformation ci, CoreSessionEventHandler onSessionStartHandler, CoreAuthenticationEventHandler onAuthenticateHandler) { this.webServer = webServer; this.stream = stream; this.ci = ci; OnSessionStartHandler = onSessionStartHandler; OnAuthenticateHandler = onAuthenticateHandler; ms = new MemoryStream(); outputStream = new StringBuilder(); }
private void manager_connectionEvent(ConnectionInformation connection) { uint ID = connection.GetConnectionID(); try { liveConnections.Add(ID, connection); connection.OnConnectionClosed += connectionChanged; ButterflyEnvironment.GetGame().GetClientManager().CreateAndStartClient(connection.GetConnectionID(), connection); Logging.WriteLine("Accepting connection ID " + ID + " from " + connection.GetIP()); } catch (Exception e) { Console.WriteLine(e.ToString() + Environment.NewLine + ID); } }
/// <summary> /// Parse an XML query plan and represent that information. /// </summary> /// <param name="manager">Communicaton manager.</param> protected override void ParseQueryPlan(CommManager manager) { string planString = this.planStream.ReadToEnd(manager.Token); XDocument plan = XDocument.Parse(planString); // ReSharper disable PossibleNullReferenceException XElement query = plan.Root.Elements().First(e => e.Name == "QueryPlan"); IEnumerable<XElement> vertices = query.Elements().Where(e => e.Name == "Vertex"); foreach (XElement v in vertices) { Stage stage = new Stage(); stage.Id = int.Parse(v.Element("UniqueId").Value); stage.Replication = int.Parse(v.Element("Partitions").Value); stage.Operator = v.Element("Type").Value; stage.Name = v.Element("Name").Value; { string code = v.Element("Explain").Value; string[] lines = code.Split('\n'); if (lines.Length > 1) { stage.Code = lines.Skip(1). // drop stage name Select(l => l.Trim()). // remove leading tab ToArray(); } else { stage.Code = new string[] { }; } } this.stages.Add(stage.Id, stage); { // These should be connection attributes, not stage attributes. string cht = v.Element("ChannelType").Value; string connectionManager = v.Element("DynamicManager").Element("Type").Value; string connection = v.Element("ConnectionOperator").Value; ConnectionInformation info = new ConnectionInformation(); info.ConnectionManager = connectionManager; switch (connection) { case "Pointwise": info.Arity = Connection.ConnectionType.PointToPoint; break; case "CrossProduct": info.Arity = Connection.ConnectionType.AllToAll; break; default: throw new DryadException("Don't know about connection of type " + connection); } switch (cht) { case "DiskFile": info.ChannelKind = Connection.ChannelType.DiskFile; break; case "TCPPipe": info.ChannelKind = Connection.ChannelType.TCP; break; case "MemoryFIFO": info.ChannelKind = Connection.ChannelType.Fifo; break; default: throw new DryadException("Don't know about channel of type " + cht); } this.perNodeConnectionInfo.Add(stage.Id, info); } switch (stage.Operator) { case "InputTable": stage.IsInput = true; stage.UriType = v.Element("StorageSet").Element("Type").Value; stage.Uri = v.Element("StorageSet").Element("SourceURI").Value; break; case "OutputTable": stage.IsOutput = true; stage.UriType = v.Element("StorageSet").Element("Type").Value; stage.Uri = v.Element("StorageSet").Element("SinkURI").Value; break; case "Tee": stage.IsTee = true; break; case "Concat": stage.IsConcat = true; break; } if (!v.Elements("Children").Any()) continue; bool first = true; var children = v.Element("Children").Elements().Where(e => e.Name == "Child").ToList(); foreach (XElement child in children) { // This code parallels the graphbuilder.cpp for XmlExecHost Connection conn = new Connection(); int fromid = int.Parse(child.Element("UniqueId").Value); ConnectionInformation fromConnectionInformation = this.perNodeConnectionInfo[fromid]; Stage from = this.stages[fromid]; conn.From = from; conn.To = stage; conn.ChannelKind = fromConnectionInformation.ChannelKind; ConnectionInformation thisConnectionInformation = this.perNodeConnectionInfo[stage.Id]; switch (thisConnectionInformation.ConnectionManager) { case "FullAggregator": case "HashDistributor": case "RangeDistributor": // Ignore except first child if (first) { first = false; conn.ConnectionManager = thisConnectionInformation.ConnectionManager; } else { conn.ConnectionManager = ""; } break; case "PartialAggregator": case "Broadcast": // All children have the same connection manager conn.ConnectionManager = thisConnectionInformation.ConnectionManager; break; case "Splitter": // The connection manager depends on the number of children if (first) { first = false; if (children.Count() == 1) conn.ConnectionManager = thisConnectionInformation.ConnectionManager; else conn.ConnectionManager = "SemiSplitter"; } else { conn.ConnectionManager = ""; } break; case "None": case "": break; } conn.Arity = fromConnectionInformation.Arity; this.connections.Add(conn); } } // ReSharper restore PossibleNullReferenceException }
internal /* for testing purposes */ async Task ConnectionStepAsync(ConnectionInformation connection, IProgressController controller, IProgressStepExecutionEvents notifications, CancellationToken cancellationToken) { this.host.ActiveSection?.UserNotifications?.HideNotification(NotificationIds.FailedToConnectId); this.host.ActiveSection?.UserNotifications?.HideNotification(NotificationIds.BadSonarQubePluginId); notifications.ProgressChanged(connection.ServerUri.ToString()); try { notifications.ProgressChanged(Strings.ConnectionStepValidatinCredentials); if (!this.host.SonarQubeService.IsConnected) { await this.host.SonarQubeService.ConnectAsync(connection, cancellationToken); } if (connection.Organization == null) { var hasOrgs = await this.host.SonarQubeService.HasOrganizations(cancellationToken); if (hasOrgs) { notifications.ProgressChanged(Strings.ConnectionStepRetrievingOrganizations); var organizations = await this.host.SonarQubeService.GetAllOrganizationsAsync(cancellationToken); connection.Organization = AskUserToSelectOrganizationOnUIThread(organizations); if (connection.Organization == null) // User clicked cancel { AbortWithMessage(notifications, controller, cancellationToken); // TODO: Might be worth throwing return; } } } // Persist the credentials on successful connection to SonarQube, unless // the connection is anonymous if (!string.IsNullOrEmpty(connection.UserName) && !string.IsNullOrEmpty(connection.Password.ToUnsecureString())) { this.credentialStore.WriteCredentials( connection.ServerUri, new Credential(connection.UserName, connection.Password.ToUnsecureString())); } var isCompatible = await this.AreSolutionProjectsAndSonarQubePluginsCompatibleAsync(controller, notifications, cancellationToken); if (!isCompatible) { return; // Message is already displayed by the method } this.ConnectedServer = connection; notifications.ProgressChanged(Strings.ConnectionStepRetrievingProjects); var projects = await this.host.SonarQubeService.GetAllProjectsAsync(connection.Organization?.Key, cancellationToken); // The SonarQube client will limit the number of returned projects to 10K (hard limit on SonarQube side) // but will no longer fail when trying to retrieve more. In the case where the project we want to bind to // is not in the list and the binding was already done and the key is not null then we manually // forge and add a new project to the list. if (!string.IsNullOrWhiteSpace(this.host.VisualStateManager.BoundProjectKey) && projects.Count == 10000 && !projects.Any(p => p.Key == this.host.VisualStateManager.BoundProjectKey)) { this.host.Logger.WriteLine($"The project with key '{this.host.VisualStateManager.BoundProjectKey}' is not part of the first ten thousand projects. The binding process will continue assuming it was found."); this.host.Logger.WriteLine("Note that if the project key does not actually exist on the server the binding will fail at a later stage."); // We have to create a new list because the collection returned by the service as a fixed size projects = new List <SonarQubeProject>(projects); // Let's put the new item first in the collection to ease finding it. projects.Insert(0, new SonarQubeProject(this.host.VisualStateManager.BoundProjectKey, this.host.VisualStateManager.BoundProjectName ?? this.host.VisualStateManager.BoundProjectKey)); } this.OnProjectsChanged(connection, projects); notifications.ProgressChanged(Strings.ConnectionResultSuccess); } catch (HttpRequestException e) { // For some errors we will get an inner exception which will have a more specific information // that we would like to show i.e.when the host could not be resolved var innerException = e.InnerException as System.Net.WebException; this.host.Logger.WriteLine(CoreStrings.SonarQubeRequestFailed, e.Message, innerException?.Message); AbortWithMessage(notifications, controller, cancellationToken); } catch (TaskCanceledException) { // Canceled or timeout this.host.Logger.WriteLine(CoreStrings.SonarQubeRequestTimeoutOrCancelled); AbortWithMessage(notifications, controller, cancellationToken); } catch (Exception ex) { this.host.Logger.WriteLine(CoreStrings.SonarQubeRequestFailed, ex.Message, null); AbortWithMessage(notifications, controller, cancellationToken); } }
public static Parser Create( IServiceCollection services, StartServer startServer = null, Jupyter jupyter = null, StartStdIO startStdIO = null, StartHttp startHttp = null, ITelemetry telemetry = null, IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null) { if (services == null) { throw new ArgumentNullException(nameof(services)); } startServer ??= (startupOptions, invocationContext) => Program.ConstructWebHost(startupOptions).Run(); jupyter ??= JupyterCommand.Do; startStdIO ??= StdIOCommand.Do; startHttp ??= HttpCommand.Do; // Setup first time use notice sentinel. firstTimeUseNoticeSentinel ??= new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion); // Setup telemetry. telemetry ??= new Telemetry.Telemetry( VersionSensor.Version().AssemblyInformationalVersion, firstTimeUseNoticeSentinel); var filter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing); var verboseOption = new Option <bool>( "--verbose", "Enable verbose logging to the console"); var logPathOption = new Option <DirectoryInfo>( "--log-path", "Enable file logging to the specified directory"); var pathOption = new Option <DirectoryInfo>( "--path", "Installs the kernelspecs to the specified directory") .ExistingOnly(); var defaultKernelOption = new Option <string>( "--default-kernel", description: "The default language for the kernel", getDefaultValue: () => "csharp"); var rootCommand = DotnetInteractive(); rootCommand.AddCommand(Jupyter()); rootCommand.AddCommand(StdIO()); rootCommand.AddCommand(HttpServer()); return(new CommandLineBuilder(rootCommand) .UseDefaults() .UseMiddleware(async(context, next) => { if (context.ParseResult.Errors.Count == 0) { telemetry.SendFiltered(filter, context.ParseResult); } // If sentinel does not exist, print the welcome message showing the telemetry notification. if (!firstTimeUseNoticeSentinel.Exists() && !Telemetry.Telemetry.SkipFirstTimeExperience) { context.Console.Out.WriteLine(); context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage); firstTimeUseNoticeSentinel.CreateIfNotExists(); } await next(context); }) .Build()); RootCommand DotnetInteractive() { var command = new RootCommand { Name = "dotnet-interactive", Description = "Interactive programming for .NET." }; command.AddOption(logPathOption); command.AddOption(verboseOption); return(command); } Command Jupyter() { var httpPortRangeOption = new Option <HttpPortRange>( "--http-port-range", parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result), description: "Specifies the range of port to use to enable HTTP services", isDefault: true); var command = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel") { defaultKernelOption, logPathOption, verboseOption, httpPortRangeOption, new Argument <FileInfo> { Name = "connection-file" }.ExistingOnly() }; command.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext>(JupyterHandler); var installCommand = new Command("install", "Install the .NET kernel for Jupyter") { logPathOption, verboseOption, httpPortRangeOption, pathOption }; installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext, HttpPortRange, DirectoryInfo>(InstallHandler); command.AddCommand(installCommand); return(command); Task <int> JupyterHandler(StartupOptions startupOptions, JupyterOptions options, IConsole console, InvocationContext context) { services = RegisterKernelInServiceCollection( services, startupOptions, options.DefaultKernel, serviceCollection => { serviceCollection.AddSingleton(_ => new HtmlNotebookFrontedEnvironment()); serviceCollection.AddSingleton <FrontendEnvironment>(c => c.GetService <HtmlNotebookFrontedEnvironment>()); }); services.AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile)) .AddSingleton(c => { return(CommandScheduler.Create <JupyterRequestContext>(delivery => c.GetRequiredService <ICommandHandler <JupyterRequestContext> >() .Trace() .Handle(delivery))); }) .AddSingleton(c => new JupyterRequestContextHandler( c.GetRequiredService <IKernel>()) .Trace()) .AddSingleton <IHostedService, Shell>() .AddSingleton <IHostedService, Heartbeat>(); return(jupyter(startupOptions, console, startServer, context)); } Task <int> InstallHandler(IConsole console, InvocationContext context, HttpPortRange httpPortRange, DirectoryInfo path) { var jupyterInstallCommand = new JupyterInstallCommand(console, new JupyterKernelSpecInstaller(console), httpPortRange, path); return(jupyterInstallCommand.InvokeAsync()); } } Command HttpServer() { var httpPortOption = new Option <HttpPort>( "--http-port", description: "Specifies the port on which to enable HTTP services", parseArgument: result => { if (result.Tokens.Count == 0) { return(HttpPort.Auto); } var source = result.Tokens[0].Value; if (source == "*") { return(HttpPort.Auto); } if (!int.TryParse(source, out var portNumber)) { result.ErrorMessage = "Must specify a port number or *."; return(null); } return(new HttpPort(portNumber)); }, isDefault: true); var command = new Command("http", "Starts dotnet-interactive with kernel functionality exposed over http") { defaultKernelOption, httpPortOption, logPathOption }; command.Handler = CommandHandler.Create <StartupOptions, KernelHttpOptions, IConsole, InvocationContext>( (startupOptions, options, console, context) => { RegisterKernelInServiceCollection( services, startupOptions, options.DefaultKernel, serviceCollection => { serviceCollection.AddSingleton(_ => { var frontendEnvironment = new BrowserFrontendEnvironment(); return(frontendEnvironment); }); serviceCollection.AddSingleton <FrontendEnvironment>(c => c.GetRequiredService <BrowserFrontendEnvironment>()); }); return(startHttp(startupOptions, console, startServer, context)); }); return(command); } Command StdIO() { var httpPortRangeOption = new Option <HttpPortRange>( "--http-port-range", parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result), description: "Specifies the range of port to use to enable HTTP services"); var command = new Command( "stdio", "Starts dotnet-interactive with kernel functionality exposed over standard I/O") { defaultKernelOption, logPathOption, httpPortRangeOption }; command.Handler = CommandHandler.Create <StartupOptions, StdIOOptions, IConsole, InvocationContext>( (startupOptions, options, console, context) => { if (startupOptions.EnableHttpApi) { RegisterKernelInServiceCollection( services, startupOptions, options.DefaultKernel, serviceCollection => { serviceCollection.AddSingleton(_ => new HtmlNotebookFrontedEnvironment()); serviceCollection.AddSingleton <FrontendEnvironment>(c => c.GetService <HtmlNotebookFrontedEnvironment>()); }, kernel => { StdIOCommand.CreateServer(kernel, console); }); return(startHttp(startupOptions, console, startServer, context)); } return(startStdIO( startupOptions, CreateKernel(options.DefaultKernel, new BrowserFrontendEnvironment(), startupOptions, null), console)); }); return(command); }
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public async Task connectAsync() { switch (state) { case ConnectionState.DISCONNECTED: case ConnectionState.ERROR: setState(ConnectionState.CONNECTING); for (int i = 1; i <= MAX_CONNECTION_TRIES; i++) { try { // Cancel connecting if for example disconnectAsync() got called: if (state != ConnectionState.CONNECTING) { return; } // Setup socket: socket = new StreamSocket(); socket.Control.KeepAlive = true; socket.Control.QualityOfService = SocketQualityOfService.LowLatency; hostName = new HostName(account.serverAddress); // Add all ignored certificate errors: foreach (ChainValidationResult item in account.connectionConfiguration.IGNORED_CERTIFICATE_ERRORS) { socket.Control.IgnorableServerCertificateErrors.Add(item); } // Connect with timeout: if (disableTcpTimeout) { connectingCTS = new CancellationTokenSource(); } else { connectingCTS = new CancellationTokenSource(CONNECTION_TIMEOUT_MS); } await socket.ConnectAsync(hostName, account.port.ToString(), SocketProtectionLevel.PlainSocket).AsTask(connectingCTS.Token); // Setup stream reader and writer: dataWriter = new DataWriter(socket.OutputStream); dataReader = new DataReader(socket.InputStream) { InputStreamOptions = InputStreamOptions.Partial }; // Update account connection info: ConnectionInformation connectionInfo = account.CONNECTION_INFO; connectionInfo.socketInfo = socket?.Information; // Connection successfully established: if (state == ConnectionState.CONNECTING) { setState(ConnectionState.CONNECTED); } return; } catch (TaskCanceledException e) { Logger.Error("[TCPConnection2]: " + i + " try to connect to " + account.serverAddress + " failed:", e); lastConnectionError = new ConnectionError(ConnectionErrorCode.CONNECT_TIMEOUT, e.Message); } catch (Exception e) { onConnectionError(e, i); } } setState(ConnectionState.ERROR, lastConnectionError); break; default: break; } }
public void SetConnection(ConnectionInformation _Con) { Con = _Con; OnNewPacket = null; }
private static ServerViewModel VerifyConnectSectionViewModelIsConnectedAndHasNoProjects(ConnectSectionViewModel vm, ConnectionInformation connection) { ServerViewModel serverVM = VerifyConnectSectionViewModelIsConnected(vm, connection); serverVM.Projects.Should().BeEmpty("Unexpected number of projects"); return(serverVM); }
private void ConnectionChanged(ConnectionInformation information) { this.CloseConnection(information); information.connectionClose -= new ConnectionInformation.ConnectionChange(this.ConnectionChanged); }
private void manager_connectionEvent(ConnectionInformation connection) { liveConnections.Add(connection.getConnectionID(), connection); connection.connectionChanged += connectionChanged; ButterflyEnvironment.GetGame().GetClientManager().CreateAndStartClient((uint)connection.getConnectionID(), connection); }
public static Parser Create( IServiceCollection services, StartServer startServer = null, Jupyter jupyter = null, StartKernelServer startKernelServer = null, ITelemetry telemetry = null, IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null) { if (services == null) { throw new ArgumentNullException(nameof(services)); } startServer = startServer ?? ((startupOptions, invocationContext) => Program.ConstructWebHost(startupOptions).Run()); jupyter = jupyter ?? JupyterCommand.Do; startKernelServer = startKernelServer ?? (async(startupOptions, kernel, console) => { var server = new StandardIOKernelServer( kernel, Console.In, Console.Out); await server.Input.LastAsync(); }); // Setup first time use notice sentinel. firstTimeUseNoticeSentinel = firstTimeUseNoticeSentinel ?? new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion); // Setup telemetry. telemetry = telemetry ?? new Telemetry.Telemetry( VersionSensor.Version().AssemblyInformationalVersion, firstTimeUseNoticeSentinel); var filter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing); void Track(ParseResult o) => telemetry.SendFiltered(filter, o); var verboseOption = new Option( "--verbose", "Enable verbose logging to the console") { Argument = new Argument <bool>() }; var logPathOption = new Option( "--log-path", "Enable file logging to the specified directory") { Argument = new Argument <DirectoryInfo> { Name = "dir" } }; var rootCommand = DotnetInteractive(); rootCommand.AddCommand(Jupyter()); rootCommand.AddCommand(KernelServer()); return(new CommandLineBuilder(rootCommand) .UseDefaults() .UseMiddleware(async(context, next) => { // If sentinel does not exist, print the welcome message showing the telemetry notification. if (!firstTimeUseNoticeSentinel.Exists() && !Telemetry.Telemetry.SkipFirstTimeExperience) { context.Console.Out.WriteLine(); context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage); firstTimeUseNoticeSentinel.CreateIfNotExists(); } await next(context); }) .Build()); RootCommand DotnetInteractive() { var command = new RootCommand { Name = "dotnet-interactive", Description = "Interactive programming for .NET." }; command.AddOption(logPathOption); command.AddOption(verboseOption); return(command); } Command Jupyter() { var jupyterCommand = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel"); var defaultKernelOption = new Option("--default-kernel", "The the default language for the kernel") { Argument = new Argument <string>(defaultValue: () => "csharp") }; jupyterCommand.AddOption(defaultKernelOption); jupyterCommand.AddOption(logPathOption); jupyterCommand.AddOption(verboseOption); var connectionFileArgument = new Argument <FileInfo> { Name = "connection-file" }.ExistingOnly(); jupyterCommand.AddArgument(connectionFileArgument); jupyterCommand.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext>((startupOptions, options, console, context) => { Track(context.ParseResult); services .AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile)) .AddSingleton( c => { return(CommandScheduler .Create <JupyterRequestContext>(delivery => c.GetRequiredService <ICommandHandler <JupyterRequestContext> >() .Trace() .Handle(delivery))); }) .AddSingleton(c => CreateKernel(options.DefaultKernel)) .AddSingleton(c => new JupyterRequestContextHandler(c.GetRequiredService <IKernel>()) .Trace()) .AddSingleton <IHostedService, Shell>() .AddSingleton <IHostedService, Heartbeat>(); return(jupyter(startupOptions, console, startServer, context)); }); var installCommand = new Command("install", "Install the .NET kernel for Jupyter") { logPathOption, verboseOption }; installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext>((console, context) => { Track(context.ParseResult); return(new JupyterInstallCommand(console, new FileSystemJupyterKernelSpec()).InvokeAsync()); }); jupyterCommand.AddCommand(installCommand); return(jupyterCommand); } Command KernelServer() { var defaultKernelOption = new Option("--default-kernel", "The default .NET kernel language for the notebook.") { Argument = new Argument <string>(defaultValue: () => "csharp") }; var startKernelServerCommand = new Command("kernel-server", "Starts dotnet-interactive with kernel functionality exposed over standard I/O") { defaultKernelOption, logPathOption, verboseOption }; startKernelServerCommand.Handler = CommandHandler.Create <StartupOptions, KernelServerOptions, IConsole, InvocationContext>( (startupOptions, options, console, context) => { Track(context.ParseResult); return(startKernelServer(startupOptions, CreateKernel(options.DefaultKernel), console)); }); return(startKernelServerCommand); } }
public void ConnectionWorkflow_ConnectionStep_UnsuccessfulConnection() { // Arrange var connectionInfo = new ConnectionInformation(new Uri("http://server")); bool projectChangedCallbackCalled = false; this.host.TestStateManager.SetProjectsAction = (c, p) => { projectChangedCallbackCalled = true; c.Should().Be(connectionInfo, "Unexpected connection"); p.Should().BeNull("Not expecting any projects"); }; this.projectSystemHelper.Projects = new[] { new ProjectMock("foo.csproj") { ProjectKind = ProjectSystemHelper.CSharpProjectKind } }; var controller = new ConfigurableProgressController(); this.sonarQubeService.AllowConnections = false; var executionEvents = new ConfigurableProgressStepExecutionEvents(); string connectionMessage = connectionInfo.ServerUri.ToString(); var testSubject = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled)); // Act testSubject.ConnectionStep(controller, CancellationToken.None, connectionInfo, executionEvents); // Assert executionEvents.AssertProgressMessages( connectionMessage, Strings.ConnectionStepValidatinCredentials, Strings.DetectingServerPlugins, Strings.ConnectionStepRetrievingProjects, Strings.ConnectionResultFailure); projectChangedCallbackCalled.Should().BeFalse("Callback should not have been called"); this.sonarQubeService.ConnectionRequestsCount.Should().Be(1); this.host.VisualStateManager.IsConnected.Should().BeFalse(); ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNotification(NotificationIds.FailedToConnectId, Strings.ConnectionFailed); // Act (reconnect with same bad connection) executionEvents.Reset(); projectChangedCallbackCalled = false; testSubject.ConnectionStep(controller, CancellationToken.None, connectionInfo, executionEvents); // Assert executionEvents.AssertProgressMessages( connectionMessage, Strings.ConnectionStepValidatinCredentials, Strings.DetectingServerPlugins, Strings.ConnectionStepRetrievingProjects, Strings.ConnectionResultFailure); projectChangedCallbackCalled.Should().BeFalse("Callback should not have been called"); this.sonarQubeService.ConnectionRequestsCount.Should().Be(2); this.host.VisualStateManager.IsConnected.Should().BeFalse(); ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNotification(NotificationIds.FailedToConnectId, Strings.ConnectionFailed); // Canceled connections CancellationTokenSource tokenSource = new CancellationTokenSource(); executionEvents.Reset(); projectChangedCallbackCalled = false; CancellationToken token = tokenSource.Token; tokenSource.Cancel(); // Act testSubject.ConnectionStep(controller, token, connectionInfo, executionEvents); // Assert executionEvents.AssertProgressMessages( connectionMessage, Strings.ConnectionStepValidatinCredentials, Strings.DetectingServerPlugins, Strings.ConnectionStepRetrievingProjects, Strings.ConnectionResultCancellation); projectChangedCallbackCalled.Should().BeFalse("Callback should not have been called"); this.sonarQubeService.ConnectionRequestsCount.Should().Be(3); this.host.VisualStateManager.IsConnected.Should().BeFalse(); ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNotification(NotificationIds.FailedToConnectId, Strings.ConnectionFailed); }
private void FirmaBilgileriDoldur() { ConnectionInformation connection = new ConnectionInformation(); cmbFirma.DataSource = connection.FirmaDoldur(); }
public void SetConnection(ConnectionInformation con) { this.con = con; onNewPacket = null; }
public void StateManager_SetProjectsUIThread() { // Setup var section = ConfigurableSectionController.CreateDefault(); ConfigurableUserNotification notifications = (ConfigurableUserNotification)section.UserNotifications; ConfigurableHost host = new ConfigurableHost(); StateManager testSubject = this.CreateTestSubject(host); host.VisualStateManager = testSubject; section.ViewModel.State = testSubject.ManagedState; var connection1 = new ConnectionInformation(new Uri("http://127.0.0.1")); var connection2 = new ConnectionInformation(new Uri("http://127.0.0.2")); var projects = new[] { new ProjectInformation(), new ProjectInformation() }; host.SetActiveSection(section); ServerViewModel serverVM; // Act + Verify // Case 1 - not connected to server (indicated by null) section.UserNotifications.ShowNotificationError("message", NotificationIds.FailedToFindBoundProjectKeyId, null); testSubject.SetProjects(connection1, null); notifications.AssertNoNotification(NotificationIds.FailedToFindBoundProjectKeyId); VerifyConnectSectionViewModelIsNotConnected(section.ViewModel, connection1); VerifyConnectSectionViewModelIsNotConnected(section.ViewModel, connection2); VerifyConnectSectionViewModelHasNoBoundProjects(section.ViewModel); // Case 2 - connection1, empty project collection section.UserNotifications.ShowNotificationError("message", NotificationIds.FailedToFindBoundProjectKeyId, null); testSubject.SetProjects(connection1, new ProjectInformation[0]); notifications.AssertNoNotification(NotificationIds.FailedToFindBoundProjectKeyId); serverVM = VerifyConnectSectionViewModelIsConnectedAndHasNoProjects(section.ViewModel, connection1); Assert.IsTrue(serverVM.ShowAllProjects, "Expected show all projects"); VerifySectionCommands(section, serverVM); VerifyConnectSectionViewModelIsNotConnected(section.ViewModel, connection2); VerifyConnectSectionViewModelHasNoBoundProjects(section.ViewModel); // Case 3 - connection1, non-empty project collection section.UserNotifications.ShowNotificationError("message", NotificationIds.FailedToFindBoundProjectKeyId, null); testSubject.SetProjects(connection1, projects); notifications.AssertNoNotification(NotificationIds.FailedToFindBoundProjectKeyId); serverVM = VerifyConnectSectionViewModelIsConnectedAndHasProjects(section.ViewModel, connection1, projects); VerifySectionCommands(section, serverVM); VerifyConnectSectionViewModelIsNotConnected(section.ViewModel, connection2); VerifyConnectSectionViewModelHasNoBoundProjects(section.ViewModel); Assert.IsTrue(serverVM.ShowAllProjects, "Expected show all projects to be true when adding new projects"); // Case 4 - connection2, change projects testSubject.SetProjects(connection1, projects); section.UserNotifications.ShowNotificationError("message", NotificationIds.FailedToFindBoundProjectKeyId, null); testSubject.SetProjects(connection2, projects); notifications.AssertNoNotification(NotificationIds.FailedToFindBoundProjectKeyId); serverVM = VerifyConnectSectionViewModelIsConnectedAndHasProjects(section.ViewModel, connection1, projects); VerifySectionCommands(section, serverVM); serverVM = VerifyConnectSectionViewModelIsConnectedAndHasProjects(section.ViewModel, connection2, projects); VerifySectionCommands(section, serverVM); VerifyConnectSectionViewModelHasNoBoundProjects(section.ViewModel); Assert.IsTrue(serverVM.ShowAllProjects, "Expected show all projects to be true when changing projects"); // Case 5 - connection1 & connection2, once detached (connected or not), are reset, changes still being tracked host.ClearActiveSection(); testSubject.SetProjects(connection1, projects); testSubject.SetProjects(connection2, projects); // Act section.UserNotifications.ShowNotificationError("message", NotificationIds.FailedToFindBoundProjectKeyId, null); host.SetActiveSection(section); // Verify notifications.AssertNotification(NotificationIds.FailedToFindBoundProjectKeyId); serverVM = VerifyConnectSectionViewModelIsConnectedAndHasProjects(section.ViewModel, connection1, projects); VerifySectionCommands(section, serverVM); serverVM = VerifyConnectSectionViewModelIsConnectedAndHasProjects(section.ViewModel, connection2, projects); VerifySectionCommands(section, serverVM); VerifyConnectSectionViewModelHasNoBoundProjects(section.ViewModel); }
internal void CreateAndStartClient(uint clientID, ConnectionInformation connection) { GameClient client = new GameClient(clientID, connection); if (clients.ContainsKey(clientID)) clients.Remove(clientID); lock (clientsAddQueue.SyncRoot) { clientsAddQueue.Enqueue(client); } }
private static ServerViewModel VerifyConnectSectionViewModelIsConnectedAndHasNoProjects(ConnectSectionViewModel vm, ConnectionInformation connection) { ServerViewModel serverVM = VerifyConnectSectionViewModelIsConnected(vm, connection); Assert.AreEqual(0, serverVM.Projects.Count, "Unexpected number of projects"); return(serverVM); }
private void Manager_connectionEvent(ConnectionInformation connection) { connection.connectionClose += new ConnectionInformation.ConnectionChange(this.ConnectionChanged); ButterflyEnvironment.GetGame().GetClientWebManager().CreateAndStartClient(connection.getConnectionID(), connection); }
private ProgressStepDefinition[] CreateConnectionSteps(IProgressController controller, ConnectionInformation connection) { string connectStepDisplayText = string.Format(CultureInfo.CurrentCulture, Strings.ConnectingToSever, connection.ServerUri); return(new[] { new ProgressStepDefinition(connectStepDisplayText, StepAttributes.Indeterminate | StepAttributes.BackgroundThread, (cancellationToken, notifications) => this.ConnectionStepAsync(connection, controller, notifications, cancellationToken).GetAwaiter().GetResult()), new ProgressStepDefinition(connectStepDisplayText, StepAttributes.BackgroundThread, (token, notifications) => this.DownloadServiceParametersAsync(controller, notifications, token).GetAwaiter().GetResult()), }); }
private static void VerifyConnectSectionViewModelIsNotConnected(ConnectSectionViewModel vm, ConnectionInformation connection) { ServerViewModel serverVM = vm.State?.ConnectedServers?.SingleOrDefault(s => s.Url == connection.ServerUri); serverVM.Should().BeNull("Should not find server view model for {0}", connection.ServerUri); }
public BindCommandArgs(string projectKey, string projectName, ConnectionInformation connection) { this.ProjectKey = projectKey; this.ProjectName = projectName; this.Connection = connection; }
private static ServerViewModel VerifyConnectSectionViewModelIsConnectedAndHasProjects(ConnectSectionViewModel vm, ConnectionInformation connection, ProjectInformation[] projects) { ServerViewModel serverVM = VerifyConnectSectionViewModelIsConnected(vm, connection); CollectionAssert.AreEquivalent(projects, serverVM.Projects.Select(p => p.ProjectInformation).ToArray(), "Unexpected projects for server {0}", connection.ServerUri); return(serverVM); }
public void SetProjects(ConnectionInformation connection, IEnumerable <ProjectInformation> projects) { this.VerifyActiveSection(); this.SetProjectsAction?.Invoke(connection, projects); }
private static ServerViewModel VerifyConnectSectionViewModelIsConnected(ConnectSectionViewModel vm, ConnectionInformation connection) { ServerViewModel serverVM = vm.State?.ConnectedServers?.SingleOrDefault(s => s.Url == connection.ServerUri); Assert.IsNotNull(serverVM, "Could not find server view model for {0}", connection.ServerUri); return(serverVM); }
private SolutionBindingOperation CreateTestSubject(string projectKey, ConnectionInformation connection = null) { return(new SolutionBindingOperation(this.serviceProvider, connection ?? new ConnectionInformation(new Uri("http://host")), projectKey)); }
private void OnProjectsChanged(ConnectionInformation connection, IEnumerable <SonarQubeProject> projects) { this.host.VisualStateManager.SetProjects(connection, projects); }
///<inheritdoc/> public string CreateConnectionString(string resourceType, ConnectionInformation connectionInformation) { IConnectionStringBuilder builder = GetBuilder(resourceType); return(builder.CreateConnectionString(connectionInformation)); }
public static Parser Create( IServiceCollection services, StartServer startServer = null, Jupyter jupyter = null, StartStdIO startStdIO = null, StartHttp startHttp = null, Action onServerStarted = null, ITelemetry telemetry = null, IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null) { var operation = Log.OnEnterAndExit(); if (services is null) { throw new ArgumentNullException(nameof(services)); } var disposeOnQuit = new CompositeDisposable(); startServer ??= (startupOptions, invocationContext) => { operation.Info("constructing webhost"); var webHost = Program.ConstructWebHost(startupOptions); disposeOnQuit.Add(webHost); operation.Info("starting kestrel server"); webHost.Start(); onServerStarted?.Invoke(); webHost.WaitForShutdown(); operation.Dispose(); }; jupyter ??= JupyterCommand.Do; startStdIO ??= StdIOCommand.Do; startHttp ??= HttpCommand.Do; // Setup first time use notice sentinel. firstTimeUseNoticeSentinel ??= new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion); var clearTextProperties = new[] { "frontend" }; // Setup telemetry. telemetry ??= new Telemetry.Telemetry( VersionSensor.Version().AssemblyInformationalVersion, firstTimeUseNoticeSentinel, "dotnet/interactive/cli"); var filter = new TelemetryFilter( Sha256Hasher.HashWithNormalizedCasing, clearTextProperties, (commandResult, directives, entryItems) => { // add frontend var frontendTelemetryAdded = false; foreach (var directive in directives) { switch (directive.Key) { case "vscode": case "jupyter": case "synapse": frontendTelemetryAdded = true; entryItems.Add(new KeyValuePair <string, string>("frontend", directive.Key)); break; } } if (!frontendTelemetryAdded) { if (commandResult.Command.Name == "jupyter") { entryItems.Add(new KeyValuePair <string, string>("frontend", "jupyter")); } else { entryItems.Add(new KeyValuePair <string, string>("frontend", "unknown")); } } }); var verboseOption = new Option <bool>( "--verbose", "Enable verbose logging to the console"); var logPathOption = new Option <DirectoryInfo>( "--log-path", "Enable file logging to the specified directory"); var pathOption = new Option <DirectoryInfo>( "--path", "Installs the kernelspecs to the specified directory") .ExistingOnly(); var defaultKernelOption = new Option <string>( "--default-kernel", description: "The default language for the kernel", getDefaultValue: () => "csharp").AddSuggestions("fsharp", "csharp", "pwsh"); var rootCommand = DotnetInteractive(); rootCommand.AddCommand(Jupyter()); rootCommand.AddCommand(StdIO()); rootCommand.AddCommand(HttpServer()); return(new CommandLineBuilder(rootCommand) .UseDefaults() .UseMiddleware(async(context, next) => { if (context.ParseResult.Errors.Count == 0) { telemetry.SendFiltered(filter, context.ParseResult); } // If sentinel does not exist, print the welcome message showing the telemetry notification. if (!Telemetry.Telemetry.SkipFirstTimeExperience && !firstTimeUseNoticeSentinel.Exists()) { context.Console.Out.WriteLine(); context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage); firstTimeUseNoticeSentinel.CreateIfNotExists(); } await next(context); }) .Build()); RootCommand DotnetInteractive() { var command = new RootCommand { Name = "dotnet-interactive", Description = "Interactive programming for .NET." }; command.AddGlobalOption(logPathOption); command.AddGlobalOption(verboseOption); return(command); } Command Jupyter() { var httpPortRangeOption = new Option <HttpPortRange>( "--http-port-range", parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result), description: "Specifies the range of ports to use to enable HTTP services", isDefault: true); var jupyterCommand = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel") { defaultKernelOption, httpPortRangeOption, new Argument <FileInfo> { Name = "connection-file", Description = "The path to a connection file provided by Jupyter" }.ExistingOnly() }; jupyterCommand.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext, CancellationToken>(JupyterHandler); var installCommand = new Command("install", "Install the .NET kernel for Jupyter") { httpPortRangeOption, pathOption }; installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext, HttpPortRange, DirectoryInfo>(InstallHandler); jupyterCommand.AddCommand(installCommand); return(jupyterCommand); async Task <int> JupyterHandler(StartupOptions startupOptions, JupyterOptions options, IConsole console, InvocationContext context, CancellationToken cancellationToken) { var frontendEnvironment = new HtmlNotebookFrontendEnvironment(); var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions); kernel.Add( new JavaScriptKernel(), new[] { "js" }); services.AddKernel(kernel); await kernel.VisitSubkernelsAsync(async k => { switch (k) { case DotNetKernel dk: await dk.UseJupyterHelpersAsync(); break; } }); var clientSideKernelClient = new SignalRBackchannelKernelClient(); services.AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile)) .AddSingleton(clientSideKernelClient) .AddSingleton(c => { return(new JupyterRequestContextScheduler(delivery => c.GetRequiredService <JupyterRequestContextHandler>() .Handle(delivery))); }) .AddSingleton(c => new JupyterRequestContextHandler(kernel)) .AddSingleton <IHostedService, Shell>() .AddSingleton <IHostedService, Heartbeat>(); var result = await jupyter(startupOptions, console, startServer, context); return(result); } Task <int> InstallHandler(IConsole console, InvocationContext context, HttpPortRange httpPortRange, DirectoryInfo path) { var jupyterInstallCommand = new JupyterInstallCommand(console, new JupyterKernelSpecInstaller(console), httpPortRange, path); return(jupyterInstallCommand.InvokeAsync()); } } Command HttpServer() { var httpPortOption = new Option <HttpPort>( "--http-port", description: "Specifies the port on which to enable HTTP services", parseArgument: result => { if (result.Tokens.Count == 0) { return(HttpPort.Auto); } var source = result.Tokens[0].Value; if (source == "*") { return(HttpPort.Auto); } if (!int.TryParse(source, out var portNumber)) { result.ErrorMessage = "Must specify a port number or *."; return(null); } return(new HttpPort(portNumber)); }, isDefault: true); var httpCommand = new Command("http", "Starts dotnet-interactive with kernel functionality exposed over http") { defaultKernelOption, httpPortOption }; httpCommand.Handler = CommandHandler.Create <StartupOptions, KernelHttpOptions, IConsole, InvocationContext>( (startupOptions, options, console, context) => { var frontendEnvironment = new BrowserFrontendEnvironment(); var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions); kernel.Add( new JavaScriptKernel(), new[] { "js" }); services.AddKernel(kernel) .AddSingleton(new SignalRBackchannelKernelClient()); onServerStarted ??= () => { console.Out.WriteLine("Application started. Press Ctrl+C to shut down."); }; return(startHttp(startupOptions, console, startServer, context)); }); return(httpCommand); } Command StdIO() { var httpPortRangeOption = new Option <HttpPortRange>( "--http-port-range", parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result), description: "Specifies the range of ports to use to enable HTTP services"); var httpPortOption = new Option <HttpPort>( "--http-port", description: "Specifies the port on which to enable HTTP services", parseArgument: result => { if (result.FindResultFor(httpPortRangeOption) is { } conflictingOption) { var parsed = result.Parent as OptionResult; result.ErrorMessage = $"Cannot specify both {conflictingOption.Token.Value} and {parsed.Token.Value} together"; return(null); } if (result.Tokens.Count == 0) { return(HttpPort.Auto); } var source = result.Tokens[0].Value; if (source == "*") { return(HttpPort.Auto); } if (!int.TryParse(source, out var portNumber)) { result.ErrorMessage = "Must specify a port number or *."; return(null); } return(new HttpPort(portNumber)); }); var workingDirOption = new Option <DirectoryInfo>( "--working-dir", () => new DirectoryInfo(Environment.CurrentDirectory), "Working directory to which to change after launching the kernel."); var stdIOCommand = new Command( "stdio", "Starts dotnet-interactive with kernel functionality exposed over standard I/O") { defaultKernelOption, httpPortRangeOption, httpPortOption, workingDirOption }; stdIOCommand.Handler = CommandHandler.Create <StartupOptions, StdIOOptions, IConsole, InvocationContext>( async(startupOptions, options, console, context) => { var isVsCode = context.ParseResult.Directives.Contains("vscode"); FrontendEnvironment frontendEnvironment = startupOptions.EnableHttpApi ? new HtmlNotebookFrontendEnvironment() : new BrowserFrontendEnvironment(); var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions); services.AddKernel(kernel); kernel.UseQuitCommand(); var kernelServer = kernel.CreateKernelServer(startupOptions.WorkingDir); if (startupOptions.EnableHttpApi) { var clientSideKernelClient = new SignalRBackchannelKernelClient(); if (isVsCode) { var frontEndKernel = kernelServer.GetFrontEndKernel("vscode"); kernel.Add(frontEndKernel); await kernel.VisitSubkernelsAsync(async k => { switch (k) { case DotNetKernel dk: await dk.UseVSCodeHelpersAsync(kernel); break; } }); services.AddSingleton(clientSideKernelClient); ((HtmlNotebookFrontendEnvironment)frontendEnvironment).RequiresAutomaticBootstrapping = false; kernel.Add( new JavaScriptKernel(clientSideKernelClient), new[] { "js" }); } else { services.AddSingleton(clientSideKernelClient); kernel.Add( new JavaScriptKernel(clientSideKernelClient), new[] { "js" }); } var _ = kernelServer.RunAsync(); onServerStarted ??= () => { kernelServer.NotifyIsReady(); }; await startHttp(startupOptions, console, startServer, context); } kernel.Add( new JavaScriptKernel(), new[] { "js" }); await startStdIO( startupOptions, kernelServer, console); }); return(stdIOCommand); }
public static Parser Create( IServiceCollection services, StartServer startServer = null, Demo demo = null, TryGitHub tryGithub = null, Pack pack = null, Install install = null, Verify verify = null, Jupyter jupyter = null, StartKernelServer startKernelServer = null) { if (services == null) { throw new ArgumentNullException(nameof(services)); } startServer = startServer ?? ((options, invocationContext) => Program.ConstructWebHost(options).Run()); jupyter = jupyter ?? JupyterCommand.Do; demo = demo ?? DemoCommand.Do; tryGithub = tryGithub ?? ((repo, console) => GitHubHandler.Handler(repo, console, new GitHubRepoLocator())); verify = verify ?? ((verifyOptions, console, startupOptions) => VerifyCommand.Do(verifyOptions, console, () => new FileSystemDirectoryAccessor(verifyOptions.Dir), PackageRegistry.CreateForTryMode(verifyOptions.Dir), startupOptions)); pack = pack ?? PackCommand.Do; install = install ?? InstallCommand.Do; startKernelServer = startKernelServer ?? KernelServerCommand.Do; var dirArgument = new Argument <DirectoryInfo> { Arity = ArgumentArity.ZeroOrOne, Name = nameof(StartupOptions.Dir).ToLower(), Description = "Specify the path to the root directory for your documentation" }.ExistingOnly(); var rootCommand = StartInTryMode(); rootCommand.AddCommand(StartInHostedMode()); rootCommand.AddCommand(Demo()); rootCommand.AddCommand(GitHub()); rootCommand.AddCommand(Pack()); rootCommand.AddCommand(Install()); rootCommand.AddCommand(Verify()); rootCommand.AddCommand(Jupyter()); rootCommand.AddCommand(KernelServer()); return(new CommandLineBuilder(rootCommand) .UseDefaults() .UseMiddleware(async(context, next) => { if (context.ParseResult.Directives.Contains("debug") && !(Clock.Current is VirtualClock)) { VirtualClock.Start(); } await next(context); }) .Build()); RootCommand StartInTryMode() { var command = new RootCommand { Name = "dotnet-try", Description = "Interactive documentation in your browser" }; command.AddArgument(dirArgument); command.AddOption(new Option( "--add-package-source", "Specify an additional NuGet package source") { Argument = new Argument <PackageSource>(() => new PackageSource(Directory.GetCurrentDirectory())) { Name = "NuGet source" } }); command.AddOption(new Option( "--package", "Specify a Try .NET package or path to a .csproj to run code samples with") { Argument = new Argument <string> { Name = "name or .csproj" } }); command.AddOption(new Option( "--package-version", "Specify a Try .NET package version to use with the --package option") { Argument = new Argument <string> { Name = "version" } }); command.AddOption(new Option( "--uri", "Specify a URL or a relative path to a Markdown file") { Argument = new Argument <Uri>() }); command.AddOption(new Option( "--enable-preview-features", "Enable preview features") { Argument = new Argument <bool>() }); command.AddOption(new Option( "--log-path", "Enable file logging to the specified directory") { Argument = new Argument <DirectoryInfo> { Name = "dir" } }); command.AddOption(new Option( "--verbose", "Enable verbose logging to the console") { Argument = new Argument <bool>() }); var portArgument = new Argument <ushort>(); portArgument.AddValidator(symbolResult => { if (symbolResult.Tokens .Select(t => t.Value) .Count(value => !ushort.TryParse(value, out _)) > 0) { return("Invalid argument for --port option"); } return(null); }); command.AddOption(new Option( "--port", "Specify the port for dotnet try to listen on") { Argument = portArgument }); command.Handler = CommandHandler.Create <InvocationContext, StartupOptions>((context, options) => { services.AddSingleton(_ => PackageRegistry.CreateForTryMode( options.Dir, options.AddPackageSource)); startServer(options, context); }); return(command); } Command StartInHostedMode() { var command = new Command("hosted") { new Option( "--id", "A unique id for the agent instance (e.g. its development environment id).") { Argument = new Argument <string>(defaultValue: () => Environment.MachineName) }, new Option( "--production", "Specifies whether the agent is being run using production resources") { Argument = new Argument <bool>() }, new Option( "--language-service", "Specifies whether the agent is being run in language service-only mode") { Argument = new Argument <bool>() }, new Option( new[] { "-k", "--key" }, "The encryption key") { Argument = new Argument <string>() }, new Option( new[] { "--ai-key", "--application-insights-key" }, "Application Insights key.") { Argument = new Argument <string>() }, new Option( "--region-id", "A unique id for the agent region") { Argument = new Argument <string>() }, new Option( "--log-to-file", "Writes a log file") { Argument = new Argument <bool>() } }; command.Description = "Starts the Try .NET agent"; command.IsHidden = true; command.Handler = CommandHandler.Create <InvocationContext, StartupOptions>((context, options) => { services.AddSingleton(_ => PackageRegistry.CreateForHostedMode()); services.AddSingleton(c => new MarkdownProject(c.GetRequiredService <PackageRegistry>())); services.AddSingleton <IHostedService, Warmup>(); startServer(options, context); }); return(command); } Command Demo() { var demoCommand = new Command( "demo", "Learn how to create Try .NET content with an interactive demo") { new Option("--output", "Where should the demo project be written to?") { Argument = new Argument <DirectoryInfo>( defaultValue: () => new DirectoryInfo(Directory.GetCurrentDirectory())) } }; demoCommand.Handler = CommandHandler.Create <DemoOptions, InvocationContext>((options, context) => { demo(options, context.Console, startServer, context); }); return(demoCommand); } Command GitHub() { var argument = new Argument <string> { // System.CommandLine parameter binding does lookup by name, // so name the argument after the github command's string param Name = nameof(TryGitHubOptions.Repo) }; var github = new Command("github", "Try a GitHub repo") { argument }; github.IsHidden = true; github.Handler = CommandHandler.Create <TryGitHubOptions, IConsole>((repo, console) => tryGithub(repo, console)); return(github); } Command Jupyter() { var jupyterCommand = new Command("jupyter", "Starts dotnet try as a Jupyter kernel") { IsHidden = true }; var connectionFileArgument = new Argument <FileInfo> { Name = "ConnectionFile", Arity = ArgumentArity.ZeroOrOne //should be removed once the commandlineapi allows subcommands to not have arguments from the main command }.ExistingOnly(); jupyterCommand.AddArgument(connectionFileArgument); jupyterCommand.Handler = CommandHandler.Create <JupyterOptions, IConsole, InvocationContext>((options, console, context) => { services .AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile)) .AddSingleton( c => { return(CommandScheduler .Create <JupyterRequestContext>(delivery => c.GetRequiredService <ICommandHandler <JupyterRequestContext> >() .Trace() .Handle(delivery))); }) .AddSingleton((Func <IServiceProvider, IKernel>)(c => CreateKernel())) .AddSingleton(c => new JupyterRequestContextHandler( c.GetRequiredService <PackageRegistry>(), c.GetRequiredService <IKernel>()) .Trace()) .AddSingleton <IHostedService, Shell>() .AddSingleton <IHostedService, Heartbeat>(); return(jupyter(console, startServer, context)); }); var installCommand = new Command("install", "Install the .NET kernel for Jupyter"); installCommand.Handler = CommandHandler.Create <IConsole>((console) => { return(new JupyterCommandLine(console, new FileSystemJupyterKernelSpec()).InvokeAsync()); }); jupyterCommand.AddCommand(installCommand); return(jupyterCommand); } Command KernelServer() { var startKernelServerCommand = new Command("kernel-server", "Starts dotnet try with kernel functionality exposed over standard i/o") { IsHidden = true }; startKernelServerCommand.Handler = CommandHandler.Create <IConsole>((console) => { return(startKernelServer(CreateKernel(), console)); }); return(startKernelServerCommand); } Command Pack() { var packCommand = new Command("pack", "Create a Try .NET package") { new Argument <DirectoryInfo> { Name = nameof(PackOptions.PackTarget) }, new Option("--version", "The version of the Try .NET package") { Argument = new Argument <string>() }, new Option("--enable-wasm", "Enables web assembly code execution") }; packCommand.IsHidden = true; packCommand.Handler = CommandHandler.Create <PackOptions, IConsole>( (options, console) => { return(pack(options, console)); }); return(packCommand); } Command Install() { var installCommand = new Command("install", "Install a Try .NET package") { new Argument <string> { Name = nameof(InstallOptions.PackageName) }, new Option("--add-source") { Argument = new Argument <PackageSource>() } }; installCommand.IsHidden = true; installCommand.Handler = CommandHandler.Create <InstallOptions, IConsole>((options, console) => install(options, console)); return(installCommand); } Command Verify() { var verifyCommand = new Command("verify", "Verify Markdown files in the target directory and its children.") { dirArgument }; verifyCommand.Handler = CommandHandler.Create <VerifyOptions, IConsole, StartupOptions>( (options, console, startupOptions) => { return(verify(options, console, startupOptions)); }); return(verifyCommand); } }
static void manager_connectionEvent(ConnectionInformation connection) { new Session(connection); }
public static Parser Create( IServiceCollection services, StartServer startServer = null, Jupyter jupyter = null, StartKernelServer startKernelServer = null, ITelemetry telemetry = null, IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null) { if (services == null) { throw new ArgumentNullException(nameof(services)); } startServer ??= (startupOptions, invocationContext) => Program.ConstructWebHost(startupOptions).Run(); jupyter ??= JupyterCommand.Do; startKernelServer ??= async(startupOptions, kernel, console) => { var disposable = Program.StartToolLogging(startupOptions); if (kernel is KernelBase kernelBase) { kernelBase.RegisterForDisposal(disposable); } var server = new StandardIOKernelServer( kernel, Console.In, Console.Out); await server.Input.LastAsync(); }; // Setup first time use notice sentinel. firstTimeUseNoticeSentinel ??= new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion); // Setup telemetry. telemetry ??= new Telemetry.Telemetry( VersionSensor.Version().AssemblyInformationalVersion, firstTimeUseNoticeSentinel); var filter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing); var verboseOption = new Option <bool>( "--verbose", "Enable verbose logging to the console"); var httpPortOption = new Option <int>( "--http-port", "Specifies the port on which to enable HTTP services"); var httpPortRangeOption = new Option <PortRange>( "--http-port-range", parseArgument: result => { if (result.Parent.Parent.Children.FirstOrDefault(c => c.Symbol == httpPortOption) is OptionResult conflictingOption) { var parsed = result.Parent as OptionResult; result.ErrorMessage = $"Cannot specify both {conflictingOption.Token.Value} and {parsed.Token.Value} together"; return(null); } var source = result.Tokens[0].Value; if (string.IsNullOrWhiteSpace(source)) { result.ErrorMessage = "Must specify a port range"; return(null); } var parts = source.Split(new[] { "-" }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { result.ErrorMessage = "Must specify a port range"; return(null); } if (!int.TryParse(parts[0], out var start) || !int.TryParse(parts[1], out var end)) { result.ErrorMessage = "Must specify a port range as StartPort-EndPort"; return(null); } if (start > end) { result.ErrorMessage = "Start port must be lower then end port"; return(null); } var pr = new PortRange(start, end); return(pr); }, description: "Specifies the range of port to use to enable HTTP services"); var logPathOption = new Option <DirectoryInfo>( "--log-path", "Enable file logging to the specified directory"); var defaultKernelOption = new Option <string>( "--default-kernel", description: "The default language for the kernel", getDefaultValue: () => "csharp"); var rootCommand = DotnetInteractive(); rootCommand.AddCommand(Jupyter()); rootCommand.AddCommand(KernelServer()); rootCommand.AddCommand(HttpServer()); return(new CommandLineBuilder(rootCommand) .UseDefaults() .UseMiddleware(async(context, next) => { if (context.ParseResult.Errors.Count == 0) { telemetry.SendFiltered(filter, context.ParseResult); } // If sentinel does not exist, print the welcome message showing the telemetry notification. if (!firstTimeUseNoticeSentinel.Exists() && !Telemetry.Telemetry.SkipFirstTimeExperience) { context.Console.Out.WriteLine(); context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage); firstTimeUseNoticeSentinel.CreateIfNotExists(); } await next(context); }) .Build()); RootCommand DotnetInteractive() { var command = new RootCommand { Name = "dotnet-interactive", Description = "Interactive programming for .NET." }; command.AddOption(logPathOption); command.AddOption(verboseOption); command.AddOption(httpPortOption); return(command); } Command Jupyter() { var jupyterCommand = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel") { defaultKernelOption, logPathOption, verboseOption, httpPortOption, httpPortRangeOption, new Argument <FileInfo> { Name = "connection-file" }.ExistingOnly() }; jupyterCommand.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext>(JupyterHandler); var installCommand = new Command("install", "Install the .NET kernel for Jupyter") { logPathOption, verboseOption, httpPortRangeOption }; installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext, PortRange>(InstallHandler); jupyterCommand.AddCommand(installCommand); return(jupyterCommand); Task <int> JupyterHandler(StartupOptions startupOptions, JupyterOptions options, IConsole console, InvocationContext context) { services.AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile)) .AddSingleton(_ => { var frontendEnvironment = new BrowserFrontendEnvironment { ApiUri = new Uri($"http://localhost:{startupOptions.HttpPort}") }; return(frontendEnvironment); }) .AddSingleton <FrontendEnvironment>(c => c.GetService <BrowserFrontendEnvironment>()) .AddSingleton(c => { return(CommandScheduler.Create <JupyterRequestContext>(delivery => c.GetRequiredService <ICommandHandler <JupyterRequestContext> >() .Trace() .Handle(delivery))); }) .AddSingleton(c => { var frontendEnvironment = c.GetRequiredService <BrowserFrontendEnvironment>(); var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions, c.GetRequiredService <HttpProbingSettings>()); return(kernel); }) .AddSingleton(c => new JupyterRequestContextHandler( c.GetRequiredService <IKernel>()) .Trace()) .AddSingleton <IHostedService, Shell>() .AddSingleton <IHostedService, Heartbeat>() ; return(jupyter(startupOptions, console, startServer, context)); } Task <int> InstallHandler(IConsole console, InvocationContext context, PortRange httpPortRange) => new JupyterInstallCommand(console, new JupyterKernelSpec(), httpPortRange).InvokeAsync(); } Command HttpServer() { var startKernelHttpCommand = new Command("http", "Starts dotnet-interactive with kernel functionality exposed over http") { defaultKernelOption, httpPortOption, logPathOption, httpPortRangeOption }; startKernelHttpCommand.Handler = CommandHandler.Create <StartupOptions, KernelHttpOptions, IConsole, InvocationContext>( (startupOptions, options, console, context) => { var frontendEnvironment = new BrowserFrontendEnvironment(); services .AddSingleton(_ => frontendEnvironment) .AddSingleton(c => CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions, null)); return(jupyter(startupOptions, console, startServer, context)); }); return(startKernelHttpCommand); } Command KernelServer() { var startKernelServerCommand = new Command( "stdio", "Starts dotnet-interactive with kernel functionality exposed over standard I/O") { defaultKernelOption, logPathOption, }; startKernelServerCommand.Handler = CommandHandler.Create <StartupOptions, KernelServerOptions, IConsole, InvocationContext>( (startupOptions, options, console, context) => startKernelServer( startupOptions, CreateKernel(options.DefaultKernel, new BrowserFrontendEnvironment(), startupOptions, null), console)); return(startKernelServerCommand); } }
private static void SetupConnections(string host, int port, string username, string password, string database, int minConn, int maxConn) { var key = GetConnectionPoolKey(host, port, username, database); ConnectionInformation info; lock (ConnectionInfo) { if (!ConnectionInfo.TryGetValue(key, out info)) info = ConnectionInfo[key] = new ConnectionInformation(minConn, maxConn); } lock (info) { for (var i = info.Active.Count + info.Busy.Count; i < info.Min || (info.Active.Count == 0 && i < info.Max); i++) { try { var socket = new MapiSocket(); socket.Connect(host, port, username, password, database); info.Active.Enqueue(socket); } catch (IOException ex) { throw new MonetDbException(ex, "Problem connecting to the MonetDB server."); } } } }
/// <summary> /// Sets the connection. /// </summary> /// <param name="con">The con.</param> public void SetConnection(ConnectionInformation con) { _con = con; OnNewPacket = null; }
internal void Stop() { if (GetMessageHandler() != null) MessageHandler.Destroy(); if (GetHabboDataContainer() != null) { GetHabboDataContainer().Destroy(); } this.MessageHandler = null; this.Habbo = null; this.Connection = null; }
public async Task ConnectionWorkflow_ConnectionStep_UnsuccessfulConnection() { // Arrange this.sonarQubeServiceMock.Setup(x => x.GetAllProjectsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(() => { throw new Exception(); }); var connectionInfo = new ConnectionInformation(new Uri("http://server")); bool projectChangedCallbackCalled = false; this.host.TestStateManager.SetProjectsAction = (c, p) => { projectChangedCallbackCalled = true; c.Should().Be(connectionInfo, "Unexpected connection"); p.Should().BeNull("Not expecting any projects"); }; this.projectSystemHelper.Projects = new[] { new ProjectMock("foo.csproj") { ProjectKind = ProjectSystemHelper.CSharpProjectKind } }; var controller = new ConfigurableProgressController(); var executionEvents = new ConfigurableProgressStepExecutionEvents(); string connectionMessage = connectionInfo.ServerUri.ToString(); var testSubject = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled)); // Act await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, CancellationToken.None); // Assert executionEvents.AssertProgressMessages( connectionMessage, Strings.ConnectionStepValidatinCredentials, Strings.DetectingSonarQubePlugins, Strings.ConnectionStepRetrievingProjects, Strings.ConnectionResultFailure); projectChangedCallbackCalled.Should().BeFalse("Callback should not have been called"); this.sonarQubeServiceMock.Verify(x => x.ConnectAsync(It.IsAny <ConnectionInformation>(), It.IsAny <CancellationToken>()), Times.Once()); this.host.VisualStateManager.IsConnected.Should().BeFalse(); ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNotification(NotificationIds.FailedToConnectId, Strings.ConnectionFailed); // Act (reconnect with same bad connection) executionEvents.Reset(); projectChangedCallbackCalled = false; await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, CancellationToken.None); // Assert executionEvents.AssertProgressMessages( connectionMessage, Strings.ConnectionStepValidatinCredentials, Strings.DetectingSonarQubePlugins, Strings.ConnectionStepRetrievingProjects, Strings.ConnectionResultFailure); projectChangedCallbackCalled.Should().BeFalse("Callback should not have been called"); this.sonarQubeServiceMock.Verify(x => x.ConnectAsync(It.IsAny <ConnectionInformation>(), It.IsAny <CancellationToken>()), Times.Exactly(2)); this.host.VisualStateManager.IsConnected.Should().BeFalse(); ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNotification(NotificationIds.FailedToConnectId, Strings.ConnectionFailed); // Canceled connections CancellationTokenSource tokenSource = new CancellationTokenSource(); executionEvents.Reset(); projectChangedCallbackCalled = false; CancellationToken token = tokenSource.Token; tokenSource.Cancel(); // Act await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, token); // Assert executionEvents.AssertProgressMessages( connectionMessage, Strings.ConnectionStepValidatinCredentials, Strings.DetectingSonarQubePlugins, Strings.ConnectionStepRetrievingProjects, Strings.ConnectionResultCancellation); projectChangedCallbackCalled.Should().BeFalse("Callback should not have been called"); this.sonarQubeServiceMock.Verify(x => x.ConnectAsync(It.IsAny <ConnectionInformation>(), It.IsAny <CancellationToken>()), Times.Exactly(3)); this.host.VisualStateManager.IsConnected.Should().BeFalse(); ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNotification(NotificationIds.FailedToConnectId, Strings.ConnectionFailed); }
/// <summary> /// Parse an XML query plan and represent that information. /// </summary> private void ParseQueryPlan() { if (!File.Exists(this.xmlPlanFile)) throw new Exception(String.Format( SR.CannotReadQueryPlan , this.xmlPlanFile)); XDocument plan = XDocument.Load(this.xmlPlanFile); XElement query = plan.Root.Elements().Where(e => e.Name == "QueryPlan").First(); IEnumerable<XElement> vertices = query.Elements().Where(e => e.Name == "Vertex"); foreach (XElement v in vertices) { Stage stage = new Stage(); stage.Id = int.Parse(v.Element("UniqueId").Value); stage.Replication = int.Parse(v.Element("Partitions").Value); stage.Operator = v.Element("Type").Value; stage.Name = v.Element("Name").Value; { string code = v.Element("Explain").Value; stage.Code = code.Split('\n'). Skip(1). // drop stage name Select(l => l.Trim()). // remove leading tab ToArray(); } this.stages.Add(stage.Id, stage); { // These should be connection attributes, not stage attributes. string cht = v.Element("ChannelType").Value; string connectionManager = v.Element("DynamicManager").Element("Type").Value; string connection = v.Element("ConnectionOperator").Value; ConnectionInformation info = new ConnectionInformation(); info.ConnectionManager = connectionManager; switch (connection) { case "Pointwise": info.Arity = Connection.ConnectionType.PointToPoint; break; case "CrossProduct": info.Arity = Connection.ConnectionType.AllToAll; break; default: throw new Exception(String.Format( SR.UnknownConnectionType , connection)); } switch (cht) { case "DiskFile": info.ChannelKind = Connection.ChannelType.DiskFile; break; case "TCPPipe": info.ChannelKind = Connection.ChannelType.TCP; break; case "MemoryFIFO": info.ChannelKind = Connection.ChannelType.Fifo; break; default: throw new Exception(String.Format( SR.UnknownChannelType2 , cht)); } this.perNodeConnectionInfo.Add(stage.Id, info); } switch (stage.Operator) { case "InputTable": stage.IsInput = true; stage.UriType = v.Element("StorageSet").Element("Type").Value; stage.Uri = v.Element("StorageSet").Element("SourceURI").Value; break; case "OutputTable": stage.IsOutput = true; stage.UriType = v.Element("StorageSet").Element("Type").Value; stage.Uri = v.Element("StorageSet").Element("SinkURI").Value; break; case "Tee": stage.IsTee = true; break; case "Concat": stage.IsConcat = true; break; default: break; } if (v.Elements("Children").Count() == 0) continue; bool first = true; IEnumerable<XElement> children = v.Element("Children").Elements().Where(e => e.Name == "Child"); foreach (XElement child in children) { // This code parallels the graphbuilder.cpp for XmlExecHost Connection conn = new Connection(); int fromid = int.Parse(child.Element("UniqueId").Value); ConnectionInformation fromConnectionInformation = this.perNodeConnectionInfo[fromid]; Stage from = this.stages[fromid]; conn.From = from; conn.To = stage; conn.ChannelKind = fromConnectionInformation.ChannelKind; switch (fromConnectionInformation.ConnectionManager) { case "FullAggregator": case "HashDistributor": case "RangeDistributor": // Ignore except first child if (first) { first = false; conn.ConnectionManager = fromConnectionInformation.ConnectionManager; } else { conn.ConnectionManager = ""; } break; case "PartialAggregator": case "Broadcast": // All children have the same connection manager conn.ConnectionManager = fromConnectionInformation.ConnectionManager; break; case "Splitter": // The connection manager depends on the number of children if (first) { first = false; if (children.Count() == 1) conn.ConnectionManager = fromConnectionInformation.ConnectionManager; else conn.ConnectionManager = "SemiSplitter"; } else { conn.ConnectionManager = ""; } break; case "None": case "": break; } conn.Arity = fromConnectionInformation.Arity; this.connections.Add(conn); } } }
internal /*for testing purposes*/ static ConnectionInfoDialogViewModel CreateViewModel(ConnectionInformation currentConnection) { var vm = new ConnectionInfoDialogViewModel(); if (currentConnection != null) { vm.ServerUrlRaw = currentConnection.ServerUri.AbsoluteUri; // Security: don't populate the user name field, as this might be a token // See https://github.com/SonarSource/sonarlint-visualstudio/issues/1081 } return(vm); }
public void SetConnection(ConnectionInformation con) { this.con = con; this.onNewPacket = null; }
internal /*for testing purposes*/ static ConnectionInfoDialogViewModel CreateViewModel(ConnectionInformation currentConnection) { var vm = new ConnectionInfoDialogViewModel(); if (currentConnection != null) { vm.ServerUrlRaw = currentConnection.ServerUri.AbsoluteUri; vm.Username = currentConnection.UserName; } return(vm); }