public AsyncProcessingNetChannel(Func<IMessageProcessingPipeBuilder, IMessageProcessingPipeBuilder> configureProcesssingPipe, INetNode node,
     ITransportChannel transportChannel, IMessageSerializer serializer, ICoreEvents logger, INetNodeConfig config, IBufferPool bufferPool)
     : base(node, transportChannel, serializer, logger, config, bufferPool)
 {
     _pipeBuilder = configureProcesssingPipe(new MessageProcessingPipeBuilder());
     _processor = _pipeBuilder.Build();
 }
 public ChatClientNetChannel(IActorSystem<IRoomActor> rooms, ICallbacksGatewayNode callbacksNode, INetNode node,  
     ITransportChannel transportChannel, IMessageSerializer serializer, ICoreEvents logger, INetNodeConfig config, IBufferPool bufferPool) 
     : base(node, transportChannel, serializer, logger, config, bufferPool)
 {
     _rooms = rooms;
     _callbacksNode = callbacksNode;
 }
Example #3
0
        public MessageProcessor(ITransportChannel channel, IMessageSerializer serializer)
        {
            _serializer = serializer;
            _transportChannel = channel;
            _messagesToSend = new ConcurrentQueue<object>();

            _transportChannel.MessageReceived += new System.EventHandler<RawMessageEventArgs>(_transportChannel_MessageReceived);
            _transportChannel.Closed += new System.EventHandler<TransportChannelClosedEventArgs>(_transportChannel_Closed);
        }
Example #4
0
 /// <summary>
 /// Constructs a new instance of the session.
 /// </summary>
 /// <param name="channel">The channel used to communicate with the server.</param>
 /// <param name="configuration">The configuration for the client application.</param>
 /// <param name="endpoint">The endpoint use to initialize the channel.</param>
 /// <param name="clientCertificate">The certificate to use for the client.</param>
 /// <remarks>
 /// The application configuration is used to look up the certificate if none is provided.
 /// The clientCertificate must have the private key. This will require that the certificate
 /// be loaded from a certicate store. Converting a DER encoded blob to a X509Certificate2
 /// will not include a private key.
 /// </remarks>
 public Session(
     ITransportChannel        channel, 
     ApplicationConfiguration configuration,
     ConfiguredEndpoint       endpoint,
     X509Certificate2         clientCertificate)
 :
     base(channel)
 {
     Initialize(channel, configuration, endpoint, clientCertificate); 
 }
        /// <summary>
        /// Intializes the object with a channel and a message context.
        /// </summary>
        /// <param name="channel">The channel.</param>
        public ClientBase(ITransportChannel channel)
        {
            if (channel == null) throw new ArgumentNullException("channel");
            
            m_channel = channel;
            m_useTransportChannel = true;

            WcfChannelBase wcfChannel = channel as WcfChannelBase;

            if (wcfChannel != null)
            {
                m_useTransportChannel = wcfChannel.m_wcfBypassChannel != null || wcfChannel.UseBinaryEncoding;
            }
        }
Example #6
0
        public Session(ITransportChannel channel)
        {
            _channel = channel;
            Channel.Closed += _channel_Closed;
            _msgProc = new MessageProcessor(Channel, new MsgPackSerializer(new TypeResolver()));
            _msgProc.MessageReceived += msgProc_MessageReceived;
            MessageQueue.StartPolling();

            Thread commandPollThread = new Thread(new ThreadStart(() =>
            {
                var pendingCommands = MessageQueue.GetPendingCommands(Tracker.Id);
                if (pendingCommands.Length > 0)
                {
                    foreach (var command in pendingCommands)
                    {
                        //_msgProc.Send();
                        switch (command)
                        {
                            case "CMD.ACTIVATE":
                                _msgProc.Send(new CommandRequest{CommandId = 0});
                                break;
                            case "CMD.DEACTIVATE":
                                _msgProc.Send(new CommandRequest { CommandId = 1 });
                                break;
                            case "CMD.SIGNAL":
                                _msgProc.Send(new CommandRequest { CommandId = 2 });
                                break;
                        }
                    }
                }
            }));
            commandPollThread.Name = "StealME.Server.CommandSenderThread";
            commandPollThread.IsBackground = true;
            commandPollThread.Start();

            // Get Protocol version from Tracker
            _msgProc.Send(new GetRequest { GetTypeId = 2 });
        }
 public SFChatClientNetChannel(INetNode node, ITransportChannel transportChannel, IMessageSerializer serializer, ICoreEvents logger, INetNodeConfig config, IBufferPool bufferPool)
     : base(node, transportChannel, serializer, logger, config, bufferPool)
 {
 }
Example #8
0
        /// <summary>
        /// Runs the test in a background thread.
        /// </summary>
        private void DoTest(ConfiguredEndpoint endpoint)
        {
            PerformanceTestResult result = new PerformanceTestResult(endpoint, 100);

            result.Results.Add(1, -1);
            result.Results.Add(10, -1);
            result.Results.Add(50, -1);
            result.Results.Add(100, -1);
            result.Results.Add(250, -1);
            result.Results.Add(500, -1);

            try
            {
                // update the endpoint.
                if (endpoint.UpdateBeforeConnect)
                {
                    endpoint.UpdateFromServer();
                }

                SessionClient client = null;

                Uri url = new Uri(endpoint.Description.EndpointUrl);

                ITransportChannel channel = SessionChannel.Create(
                    m_configuration,
                    endpoint.Description,
                    endpoint.Configuration,
                    m_clientCertificate,
                    m_messageContext);

                client = new SessionClient(channel);

                List <int> requestSizes = new List <int>(result.Results.Keys);

                for (int ii = 0; ii < requestSizes.Count; ii++)
                {
                    // update the progress indicator.
                    TestProgress((ii * 100) / requestSizes.Count);

                    lock (m_lock)
                    {
                        if (!m_running)
                        {
                            break;
                        }
                    }

                    int count = requestSizes[ii];

                    // initialize request.
                    RequestHeader requestHeader = new RequestHeader();
                    requestHeader.ReturnDiagnostics = 5000;

                    ReadValueIdCollection nodesToRead = new ReadValueIdCollection(count);

                    for (int jj = 0; jj < count; jj++)
                    {
                        ReadValueId item = new ReadValueId();

                        item.NodeId      = new NodeId((uint)jj, 1);
                        item.AttributeId = Attributes.Value;

                        nodesToRead.Add(item);
                    }

                    // ensure valid connection.
                    DataValueCollection      results         = null;
                    DiagnosticInfoCollection diagnosticInfos = null;

                    client.Read(
                        requestHeader,
                        0,
                        TimestampsToReturn.Both,
                        nodesToRead,
                        out results,
                        out diagnosticInfos);

                    if (results.Count != count)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    // do test.
                    DateTime start = DateTime.UtcNow;

                    for (int jj = 0; jj < result.Iterations; jj++)
                    {
                        client.Read(
                            requestHeader,
                            0,
                            TimestampsToReturn.Both,
                            nodesToRead,
                            out results,
                            out diagnosticInfos);

                        if (results.Count != count)
                        {
                            throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                        }
                    }

                    DateTime finish = DateTime.UtcNow;

                    long    totalTicks          = finish.Ticks - start.Ticks;
                    decimal averageMilliseconds = ((((decimal)totalTicks) / ((decimal)result.Iterations))) / ((decimal)TimeSpan.TicksPerMillisecond);
                    result.Results[requestSizes[ii]] = (double)averageMilliseconds;
                }
            }
            finally
            {
                TestComplete(result);
            }
        }
Example #9
0
        public async Task HandleAsync(
            IServiceDiscoveryRequest request,
            IAppConnection sourceConnection,
            ITransportChannel sourceChannel)
        {
            IReadOnlyCollection <(IConsumedMethod Consumed, IProvidedMethod Provided)> methodMatches;

            if (request.ConsumedService.HasValue)
            {
                methodMatches = _registryService.GetMethodMatches(
                    sourceConnection.Info.ApplicationId,
                    request.ConsumedService.Value);
            }
            else
            {
                methodMatches = _registryService.GetMethodMatches(sourceConnection.Info.ApplicationId);
            }
            IEnumerable <IGrouping <(IConsumedService ConsumedService, IProvidedService ProvidedService, Maybe <UniqueId> ConnectionId), IProvidedMethod> > groupedMethods;

            if (request.DiscoveryMode == DiscoveryMode.Offline)
            {
                var providerApps          = methodMatches.Select(x => x.Provided.ProvidedService.Application.Id).Distinct().ToArray();
                var availableProviderApps = FilterAvailableApps(providerApps);
                groupedMethods = methodMatches
                                 .Join(availableProviderApps, x => x.Provided.ProvidedService.Application.Id, y => y, (x, y) => x)
                                 .GroupBy(
                    x => (
                        x.Consumed.ConsumedService,
                        x.Provided.ProvidedService,
                        ConnectionId: Maybe <UniqueId> .Nothing),
                    x => x.Provided);
            }
            else
            {
                var onlineConnections = _appLifecycleManager.GetOnlineConnections();
                groupedMethods = methodMatches
                                 .Join(onlineConnections, x => x.Provided.ProvidedService.Application.Id, y => y.Info.ApplicationId, (x, y) => (Match: x, ConnectionId: y.Id))
                                 .GroupBy(
                    x => (
                        x.Match.Consumed.ConsumedService,
                        x.Match.Provided.ProvidedService,
                        new Maybe <UniqueId>(x.ConnectionId)),
                    x => x.Match.Provided);
            }

            var discoveredServices =
                from s in groupedMethods
                let consumedService = s.Key.ConsumedService
                                      let providedService = s.Key.ProvidedService
                                                            let connectionId = s.Key.ConnectionId
                                                                               select _protocol.MessageFactory.CreateDiscoveredService(
                    _protocol.MessageFactory.CreateConsumedServiceReference(
                        consumedService.Service.Id,
                        consumedService.Alias),
                    _protocol.MessageFactory.CreateProvidedServiceReference(
                        providedService.Service.Id,
                        providedService.Alias,
                        providedService.Application.Id,
                        connectionId),
                    s.Key.ProvidedService.Title,
                    s.Select(m =>
                             _protocol.MessageFactory.CreateDiscoveredServiceMethod(
                                 m.Method.Name,
                                 m.Title,
                                 m.Method.InputMessage.Id,
                                 m.Method.OutputMessage.Id,
                                 Convert(m.Method.Type),
                                 m.Options.Select(o => _protocol.MessageFactory.CreateOption(o.Id, o.Value)).ToList()))
                    .ToList());

            using (var response = _protocol.MessageFactory.CreateServiceDiscoveryResponse(discoveredServices.ToList()))
            {
                Log.Info("Completed service discovery request {{{0}}} from {{{1}}}: {2}", request, sourceConnection, response);
                var serializedResponse = _protocol.Serializer.Serialize(response);
                try
                {
                    await sourceChannel.Out
                    .WriteAsync(new TransportMessageFrame(serializedResponse))
                    .ConfigureAwait(false);
                }
                catch
                {
                    serializedResponse.Dispose();
                    throw;
                }
            }
        }
Example #10
0
        /// <summary>
        /// Initializes the channel.
        /// </summary>
        private void Initialize(
            ITransportChannel        channel, 
            ApplicationConfiguration configuration, 
            ConfiguredEndpoint       endpoint,
            X509Certificate2         clientCertificate)
        {
            Initialize();

            // save configuration information.
            m_configuration = configuration;
            m_endpoint = endpoint;
            
            // update the default subscription. 
            m_defaultSubscription.MinLifetimeInterval = (uint)configuration.ClientConfiguration.MinSubscriptionLifetime;

            if (m_endpoint.Description.SecurityPolicyUri != SecurityPolicies.None)
            {
                // update client certificate.
                m_instanceCertificate = clientCertificate;

                if (clientCertificate == null)
                {
                    // load the application instance certificate.
                    if (m_configuration.SecurityConfiguration.ApplicationCertificate == null)
                    {
                        throw new ServiceResultException(
                            StatusCodes.BadConfigurationError,
                            "The client configuration does not specify an application instance certificate.");
                    }

                    m_instanceCertificate = m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true);
                }

                // check for valid certificate.
                if (m_instanceCertificate == null)
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadConfigurationError,
                        "Cannot find the application instance certificate. Store={0}, SubjectName={1}, Thumbprint={2}.",
                        m_configuration.SecurityConfiguration.ApplicationCertificate.StorePath,
                        m_configuration.SecurityConfiguration.ApplicationCertificate.SubjectName,
                        m_configuration.SecurityConfiguration.ApplicationCertificate.Thumbprint);
                }

                // check for private key.
                if (!m_instanceCertificate.HasPrivateKey)
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadConfigurationError,
                        "Do not have a privat key for the application instance certificate. Subject={0}, Thumbprint={1}.",
                        m_instanceCertificate.Subject,
                        m_instanceCertificate.Thumbprint);
                }

                //load certificate chain
                /*m_instanceCertificateChain = new X509Certificate2Collection(m_instanceCertificate);
                List<CertificateIdentifier> issuers = new List<CertificateIdentifier>();
                configuration.CertificateValidator.GetIssuers(m_instanceCertificate, issuers);
                for (int i = 0; i < issuers.Count; i++)
                {
                    m_instanceCertificateChain.Add(issuers[i].Certificate);
                }*/
            }

            // initialize the message context.
            ServiceMessageContext messageContext = channel.MessageContext;

            if (messageContext != null)
            {
                m_namespaceUris = messageContext.NamespaceUris;
                m_serverUris    = messageContext.ServerUris;
                m_factory       = messageContext.Factory;
            }    
            else
            {
                m_namespaceUris = new NamespaceTable();
                m_serverUris    = new StringTable();
                m_factory       = ServiceMessageContext.GlobalContext.Factory;
            }

            // set the default preferred locales.
            m_preferredLocales = new string[] { CultureInfo.CurrentCulture.Name };

            // create a context to use.
            m_systemContext = new SystemContext();

            m_systemContext.SystemHandle = this;
            m_systemContext.EncodeableFactory = m_factory;
            m_systemContext.NamespaceUris = m_namespaceUris;
            m_systemContext.ServerUris = m_serverUris;
            m_systemContext.TypeTable = this.TypeTree;
            m_systemContext.PreferredLocales = null;
            m_systemContext.SessionId = null;
            m_systemContext.UserIdentity = null;
        }
Example #11
0
 /// <summary>
 /// Intializes the object with a channel and a message context.
 /// </summary>
 public RegistrationClient(ITransportChannel channel)
 :
     base(channel)
 {
 }
Example #12
0
 /// <summary>
 /// Intializes the object with a channel and a message context.
 /// </summary>
 public SessionClient(ITransportChannel channel)
 :
     base(channel)
 {
 }
Example #13
0
 public static ValueTask <Maybe <long> > ReceiveMessageAsync(
     this ITransportChannel channel,
     ArraySegment <byte> buffer)
 {
     return(channel.ReceiveMessageAsync(buffer.Array, buffer.Offset, buffer.Count));
 }
Example #14
0
 public static ValueTask <Maybe <long> > ReceiveMessageAsync(
     this ITransportChannel channel,
     byte[] buffer)
 {
     return(channel.ReceiveMessageAsync(buffer, 0, buffer.Length));
 }
Example #15
0
 public static Task SendMessageAsync(
     this ITransportChannel channel,
     byte[] buffer)
 {
     return(channel.SendMessageAsync(buffer, 0, buffer.Length));
 }
Example #16
0
 public static Task SendMessageAsync(
     this ITransportChannel channel,
     ArraySegment <byte> buffer)
 {
     return(channel.SendMessageAsync(buffer.Array, buffer.Offset, buffer.Count));
 }
Example #17
0
        /// <summary>
        /// Creates a new UA-binary transport channel if requested. Null otherwise.
        /// </summary>
        /// <param name="configuration">The application configuration.</param>
        /// <param name="description">The description for the endpoint.</param>
        /// <param name="endpointConfiguration">The configuration to use with the endpoint.</param>
        /// <param name="clientCertificate">The client certificate.</param>
        /// <param name="clientCertificateChain">The client certificate chain.</param>
        /// <param name="messageContext">The message context to use when serializing the messages.</param>
        /// <returns></returns>
        public static ITransportChannel CreateUaBinaryChannel(
            ApplicationConfiguration configuration,
            EndpointDescription description,
            EndpointConfiguration endpointConfiguration,
            X509Certificate2 clientCertificate,
            X509Certificate2Collection clientCertificateChain,
            ServiceMessageContext messageContext)
        {
            bool useUaTcp = description.EndpointUrl.StartsWith(Utils.UriSchemeOpcTcp);
            bool useHttps = description.EndpointUrl.StartsWith(Utils.UriSchemeHttps);

            switch (description.TransportProfileUri)
            {
            case Profiles.UaTcpTransport:
            {
                useUaTcp = true;
                break;
            }

            case Profiles.HttpsBinaryTransport:
            {
                useHttps = true;
                break;
            }
            }

            // initialize the channel which will be created with the server.
            ITransportChannel channel = null;

            if (useUaTcp)
            {
                channel = new TcpTransportChannel();
            }
#if !NO_HTTPS
            else if (useHttps)
            {
                channel = new HttpsTransportChannel();
            }
#endif

            if (channel == null)
            {
                throw ServiceResultException.Create(
                          StatusCodes.BadProtocolVersionUnsupported,
                          "Unsupported transport profile\r\n");
            }

            // create a UA-TCP channel.
            TransportChannelSettings settings = new TransportChannelSettings {
                Description            = description,
                Configuration          = endpointConfiguration,
                ClientCertificate      = clientCertificate,
                ClientCertificateChain = clientCertificateChain
            };

            if (description.ServerCertificate != null && description.ServerCertificate.Length > 0)
            {
                settings.ServerCertificate = Utils.ParseCertificateBlob(description.ServerCertificate);
            }

            if (configuration != null)
            {
                settings.CertificateValidator = configuration.CertificateValidator.GetChannelValidator();
            }

            settings.NamespaceUris = messageContext.NamespaceUris;
            settings.Factory       = messageContext.Factory;

            channel.Initialize(new Uri(description.EndpointUrl), settings);
            channel.Open();

            return(channel);
        }
        public IIncomingInvocation <TRequest, TResponse> CreateAsync <TRequest, TResponse>(IncomingInvocationDescriptor info, ITransportChannel channel)
        {
            var invocation = new IncomingInvocation <TRequest, TResponse>(
                info,
                channel,
                _protocol,
                _marshaller.GetMarshaller <TRequest>(),
                _marshaller.GetMarshaller <TResponse>());

            invocation.Start();
            return(invocation);
        }
Example #19
0
        public async Task HandleAsync(IInvocationStart request, IAppConnection sourceConnection, ITransportChannel sourceChannel)
        {
            IAppConnection    targetConnection = null;
            ITransportChannel targetChannel    = null;

            try
            {
                Log.Info("Handling invocation {0} from {{{1}}}: {{{2}}}", sourceChannel.Id, sourceConnection, request);
                targetConnection = await request.Target.Handle(_resolveTargetConnectionHandler, sourceConnection).ConfigureAwait(false);

                targetChannel = await targetConnection.CreateChannelAsync().ConfigureAwait(false);

                Log.Debug("Created channel {0} for invocation {1} from {{{2}}} to {{{3}}}: {{{4}}}", targetChannel.Id, sourceChannel.Id, sourceConnection, targetConnection, request);
                using (var invocationStarting = _protocolMessageFactory.CreateInvocationStarting())
                {
                    var serialized = _protocolSerializer.Serialize(invocationStarting);
                    try
                    {
                        await sourceChannel.Out.WriteAsync(new TransportMessageFrame(serialized)).ConfigureAwait(false);

                        Log.Trace("Sent starting event for invocation {0}", sourceChannel.Id);
                    }
                    catch
                    {
                        serialized.Dispose();
                        throw;
                    }
                }
                using (var invocationRequested = request.Target.Handle(_createRequestHandler, sourceConnection))
                {
                    var serialized = _protocolSerializer.Serialize(invocationRequested);
                    try
                    {
                        await targetChannel.Out.WriteAsync(new TransportMessageFrame(serialized)).ConfigureAwait(false);

                        Log.Trace("Sent requested event for invocation {0} to {1}", targetChannel.Id, targetConnection);
                    }
                    catch
                    {
                        serialized.Dispose();
                        throw;
                    }
                }
                var propagateTask1 = TaskRunner.RunInBackground(() => PropagateAsync(sourceChannel.In, targetChannel.Out));
                var propagateTask2 = TaskRunner.RunInBackground(() => PropagateAsync(targetChannel.In, sourceChannel.Out));
                await Task.WhenAll(propagateTask1, propagateTask2).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                sourceChannel.Out.TryTerminate(ex);
                targetChannel?.Out.TryTerminate(ex);
                throw;
            }
            finally
            {
                try
                {
                    await Task
                    .WhenAll(
                        targetChannel?.In.ConsumeAsync((Action <TransportMessageFrame>)DisposeFrame).IgnoreExceptions() ?? TaskConstants.Completed,
                        sourceChannel.In.ConsumeAsync((Action <TransportMessageFrame>)DisposeFrame).IgnoreExceptions(),
                        targetChannel?.Completion ?? TaskConstants.Completed,
                        sourceChannel.Completion)
                    .ConfigureAwait(false);

                    Log.Info("Completed invocation {0} from {{{1}}} to {{{2}}}: {{{3}}}", sourceChannel.Id, sourceConnection, targetConnection, request);
                }
                catch (OperationCanceledException)
                {
                    Log.Info("Canceled invocation {0} from {{{1}}} to {{{2}}}: {{{3}}}", sourceChannel.Id, sourceConnection, targetConnection, request);
                    throw;
                }
                catch (Exception ex)
                {
                    Log.Warn("Failed invocation {0} from {{{1}}} to {{{2}}}: {{{3}}}. Error: {4}", sourceChannel.Id, sourceConnection, targetConnection, request, ex.FormatTypeAndMessage());
                    throw;
                }
            }
        }
Example #20
0
        public void Terminate()
        {
            // todo: mark Tracker OffLine in DB

            if(_msgProc != null)
                _msgProc.MessageReceived -= msgProc_MessageReceived;

            Channel.TerminateChannel();
            _msgProc = null;
            _channel = null;
            _protocol = null;
            _tracker = null;
        }
Example #21
0
        /// <summary>
        /// Select the endpoint based on the model
        /// </summary>
        /// <param name="server"></param>
        /// <param name="endpoints"></param>
        /// <param name="channel"></param>
        /// <param name="haveCert"></param>
        /// <returns></returns>
        private static EndpointDescription SelectServerEndpoint(EndpointModel server,
                                                                IEnumerable <EndpointDescription> endpoints, ITransportChannel channel,
                                                                bool haveCert)
        {
            Contract.Requires(channel != null);

            // Filter
            var filtered = endpoints
                           .Where(e => e.TransportProfileUri == Profiles.UaTcpTransport)
                           .Where(e => {
                switch (server.SecurityMode)
                {
                case SecurityMode.Best:
                    return(true);

                case SecurityMode.None:
                    return(e.SecurityMode == MessageSecurityMode.None);

                case SecurityMode.Sign:
                    return(e.SecurityMode == MessageSecurityMode.Sign);

                case SecurityMode.SignAndEncrypt:
                    return(e.SecurityMode == MessageSecurityMode.SignAndEncrypt);
                }
                return(true);
            })
                           .Where(e => string.IsNullOrEmpty(server.SecurityPolicy) ||
                                  server.SecurityPolicy == e.SecurityPolicyUri);

            var bestEndpoint = filtered.FirstOrDefault();

            foreach (var endpoint in filtered)
            {
                if ((haveCert && (endpoint.SecurityLevel > bestEndpoint.SecurityLevel)) ||
                    (!haveCert && (endpoint.SecurityLevel < bestEndpoint.SecurityLevel)))
                {
                    bestEndpoint = endpoint;
                }
            }
            return(bestEndpoint);
        }
 public SFActorsBackendClientNetChannel(INetNode node, ITransportChannel transportChannel, IMessageSerializer serializer, ICoreEvents logger, INetNodeConfig config, IBufferPool bufferPool)
     : base(node, transportChannel, serializer, logger, config, bufferPool)
 {
 }
Example #23
0
        public Session(
            ITransportChannel channel,
            ApplicationConfiguration configuration,
            ConfiguredEndpoint endpoint,
            X509Certificate2 clientCertificate,
            EndpointDescriptionCollection availableEndpoints)
            :
                base(channel)
        {
            Initialize(channel, configuration, endpoint, clientCertificate);

            m_expectedServerEndpoints = availableEndpoints;
        }
Example #24
0
 /// <summary>
 /// Intializes the object with a channel and a message context.
 /// </summary>
 public DiscoveryClient(ITransportChannel channel)
 :
     base(channel)
 {
 }
        private async void OkBTN_Click(object sender, EventArgs e)
        {
            try
            {
                EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration);

                configuration.OperationTimeout = (int)OperationTimeoutNC.Value;
                configuration.UseBinaryEncoding = UseBinaryEncodingCK.Checked;
                configuration.MaxMessageSize = (int)MaxMessageSizeNC.Value;
                configuration.MaxArrayLength = (int)MaxArrayLengthNC.Value;
                configuration.MaxStringLength = (int)MaxStringLengthNC.Value;
                configuration.MaxByteStringLength = (int)MaxByteStringLengthNC.Value;

                ITransportChannel channel = SessionChannel.Create(
                    m_configuration,
                    m_endpoints[EndpointCB.SelectedIndex],
                    configuration,
                    await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true),
                    m_messageContext);

                // create the channel.                   

                // open the channel.
                Cursor = Cursors.WaitCursor;

                m_channel = channel;

                // close the dialog.
                DialogResult = DialogResult.OK;
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Example #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Session"/> class.
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <param name="template">The template session.</param>
        /// <param name="copyEventHandlers">if set to <c>true</c> the event handlers are copied.</param>
        public Session(ITransportChannel channel, Session template, bool copyEventHandlers)
        :
            base(channel)
        {
            Initialize(channel, template.m_configuration, template.m_endpoint, template.m_instanceCertificate);

            m_defaultSubscription = template.m_defaultSubscription;
            m_sessionTimeout = template.m_sessionTimeout;
            m_maxRequestMessageSize = template.m_maxRequestMessageSize;
            m_preferredLocales = template.m_preferredLocales;
            m_sessionName = template.m_sessionName;
            m_handle = template.m_handle;
            m_identity = template.m_identity;
            m_keepAliveInterval = template.m_keepAliveInterval;

            if (copyEventHandlers)
            {
                m_KeepAlive = template.m_KeepAlive;
                m_Publish = template.m_Publish;
                m_PublishError = template.m_PublishError;
                m_SubscriptionsChanged = template.m_SubscriptionsChanged;
                m_SessionClosing = template.m_SessionClosing;
            }
            
            foreach (Subscription subscription in template.Subscriptions)
            {
                this.AddSubscription(new Subscription(subscription, copyEventHandlers));
            }
        }
        /// <summary>
        /// Creates a session with the endpoint.
        /// </summary>
        public async Task <Session> Connect(ConfiguredEndpoint endpoint)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            EndpointDescriptionCollection availableEndpoints = null;

            // check if the endpoint needs to be updated.
            if (endpoint.UpdateBeforeConnect)
            {
                ConfiguredServerDlg configurationDialog = new ConfiguredServerDlg();
                endpoint = configurationDialog.ShowDialog(endpoint, m_configuration);

                if (endpoint == null)
                {
                    return(null);
                }
                availableEndpoints = configurationDialog.AvailableEnpoints;
            }

            m_endpoint = endpoint;

            // copy the message context.
            m_messageContext = m_configuration.CreateMessageContext();


            X509Certificate2           clientCertificate      = null;
            X509Certificate2Collection clientCertificateChain = null;

            if (endpoint.Description.SecurityPolicyUri != SecurityPolicies.None)
            {
                if (m_configuration.SecurityConfiguration.ApplicationCertificate == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate must be specified.");
                }

                clientCertificate = await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

                if (clientCertificate == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate cannot be found.");
                }

                // load certificate chain
                clientCertificateChain = new X509Certificate2Collection(clientCertificate);
                List <CertificateIdentifier> issuers = new List <CertificateIdentifier>();
                await m_configuration.CertificateValidator.GetIssuers(clientCertificate, issuers);

                for (int i = 0; i < issuers.Count; i++)
                {
                    clientCertificateChain.Add(issuers[i].Certificate);
                }
            }

            // create the channel.
            ITransportChannel channel = SessionChannel.Create(
                m_configuration,
                endpoint.Description,
                endpoint.Configuration,
                clientCertificate,
                m_configuration.SecurityConfiguration.SendCertificateChain ? clientCertificateChain : null,
                m_messageContext);

            // create the session.
            return(Connect(endpoint, channel, availableEndpoints));
        }
Example #28
0
        /// <summary>
        /// Creates a session with the endpoint.
        /// </summary>
        public async Task <Session> Connect(ConfiguredEndpoint endpoint)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            // check if the endpoint needs to be updated.
            if (endpoint.UpdateBeforeConnect)
            {
                ConfiguredServerDlg configurationDialog = new ConfiguredServerDlg();
                endpoint = await configurationDialog.ShowDialog(endpoint, m_configuration);
            }

            if (endpoint == null)
            {
                return(null);
            }

            m_endpoint = endpoint;

            // copy the message context.
            m_messageContext = m_configuration.CreateMessageContext();

            X509Certificate2 clientCertificate = null;

            if (endpoint.Description.SecurityPolicyUri != SecurityPolicies.None)
            {
                if (m_configuration.SecurityConfiguration.ApplicationCertificate == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate must be specified.");
                }

                clientCertificate = await m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

                if (clientCertificate == null)
                {
                    throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "ApplicationCertificate cannot be found.");
                }
            }

            // create the channel.
            ITransportChannel channel = SessionChannel.Create(
                m_configuration,
                endpoint.Description,
                endpoint.Configuration,
                clientCertificate,
                m_messageContext);

            try
            {
                // create the session.
                Session session = new Session(channel, m_configuration, endpoint, null);
                session.ReturnDiagnostics = DiagnosticsMasks.All;

                SessionOpenDlg sessiondlg = new SessionOpenDlg();
                session = await sessiondlg.ShowDialog(session, PreferredLocales);

                if (session != null)
                {
                    // session now owns the channel.
                    channel = null;
                    // add session to tree.
                    AddNode(session);

                    return(session);
                }
            }
            finally
            {
                // ensure the channel is closed on error.
                if (channel != null)
                {
                    channel.Close();
                    channel = null;
                }
            }

            return(null);
        }
Example #29
0
        public async Task HandleAsync(
            IMethodDiscoveryRequest request,
            IAppConnection sourceConnection,
            ITransportChannel sourceChannel)
        {
            Log.Info("Handling method discovery request {{{0}}} from {{{1}}}", request, sourceConnection);
            var appId = sourceConnection.Info.ApplicationId;
            IEnumerable <IProvidedMethod> matchingProvidedMethods =
                request.ConsumedMethod.HasValue
                    ? _registryService.GetMatchingProvidedMethods(appId, request.ConsumedMethod.Value)
                    : _registryService.GetMatchingProvidedMethods(appId);

            if (request.InputMessageId.HasValue)
            {
                matchingProvidedMethods = matchingProvidedMethods
                                          .Where(x => string.Equals(x.Method.InputMessage.Id, request.InputMessageId.Value));
            }
            if (request.OutputMessageId.HasValue)
            {
                matchingProvidedMethods = matchingProvidedMethods
                                          .Where(x => string.Equals(x.Method.OutputMessage.Id, request.OutputMessageId.Value));
            }
            IEnumerable <IDiscoveredMethod> discoveredMethods;

            if (request.DiscoveryMode == DiscoveryMode.Online)
            {
                var onlineConnections = _appLifecycleManager.GetOnlineConnections();
                discoveredMethods = matchingProvidedMethods
                                    .Join(
                    onlineConnections,
                    x => x.ProvidedService.Application.Id,
                    y => y.Info.ApplicationId,
                    (method, connection) => (method, connection))
                                    .Select(pm => Convert(pm.method, pm.connection.Id));
            }
            else
            {
                var providedMethods       = matchingProvidedMethods.ToArray();
                var providerApps          = providedMethods.Select(x => x.ProvidedService.Application.Id).Distinct().ToArray();
                var availableProviderApps = FilterAvailableApps(providerApps);
                discoveredMethods = providedMethods
                                    .Join(availableProviderApps, x => x.ProvidedService.Application.Id, y => y, (x, y) => x)
                                    .Select(pm => Convert(pm, Maybe <UniqueId> .Nothing));
            }
            using (var response = _protocol.MessageFactory.CreateMethodDiscoveryResponse(discoveredMethods.ToList()))
            {
                Log.Info("Completed method discovery request {{{0}}} from {{{1}}}: {2}", request, sourceConnection, response);
                var serializedResponse = _protocol.Serializer.Serialize(response);
                try
                {
                    await sourceChannel.Out
                    .WriteAsync(new TransportMessageFrame(serializedResponse))
                    .ConfigureAwait(false);
                }
                catch
                {
                    serializedResponse.Dispose();
                    throw;
                }
            }
        }
 public MouseActorsBackendClientNetChannel(IActorSystem<ITestActor> actorSystem, INetNode node, ITransportChannel transportChannel, IMessageSerializer serializer, 
     ICoreEvents logger, INetNodeConfig config, IBufferPool bufferPool)
     : base(node, transportChannel, serializer, logger, config, bufferPool)
 {
     _actorSystem = actorSystem;
 }
Example #31
0
 private async Task HandleInvocationStartRequestAsync(IInvocationStartRequested request, ITransportChannel channel)
 {
     _log.Debug("Handling invocation start request: {0}", request);
     if (!_options.ServicesDictionary.TryGetValue((request.ServiceId, request.ServiceAlias), out var providedService))
     {
         throw new InvalidOperationException($"Service implementation with alias {request.ServiceAlias} not provided: {request.ServiceId}");
     }
     if (!providedService.CallHandlers.TryGetValue(request.MethodId, out var callHandler))
     {
         throw new InvalidOperationException($"Method implementation with alias {request.ServiceAlias} not provided: {request.ServiceId}.{request.MethodId}");
     }
     var invocationInfo =
         new IncomingInvocationDescriptor(
             new InvocationMethodDescriptor(
                 request.ServiceId,
                 request.MethodId,
                 request.ServiceAlias),
             new InvocationSourceDescriptor(
                 request.ConsumerApplicationId,
                 request.ConsumerApplicationInstanceId,
                 request.ConsumerConnectionId));
     await callHandler.HandleAsync(invocationInfo, channel).ConfigureAwait(false);
 }
Example #32
0
        /// <summary>
        /// Connects to the UA server identfied by the CLSID.
        /// </summary>
        /// <param name="clsid">The CLSID.</param>
        /// <returns>The UA server.</returns>
        private Session Connect(Guid clsid)
        {
            // load the endpoint information.
            ConfiguredEndpoint endpoint = m_endpoint = LoadConfiguredEndpoint(clsid);

            if (endpoint == null)
            {
                throw new ServiceResultException(StatusCodes.BadConfigurationError);
            }

            // update security information.
            if (endpoint.UpdateBeforeConnect)
            {
                endpoint.UpdateFromServer(BindingFactory.Default);

                // check if halted while waiting for a response.
                if (!m_running)
                {
                    throw new ServiceResultException(StatusCodes.BadServerHalted);
                }
            }

            // look up the client certificate.
            X509Certificate2 clientCertificate = m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true);

            // create a message context to use with the channel.
            ServiceMessageContext messageContext = m_configuration.CreateMessageContext();

            // create the channel.
            ITransportChannel channel = SessionChannel.Create(
                m_configuration,
                endpoint.Description,
                endpoint.Configuration,
                clientCertificate,
                messageContext);

            // create the session.
            Session session = new Session(channel, m_configuration, endpoint, clientCertificate);

            // create a session name that is useful for debugging.
            string sessionName = Utils.Format("COM Client ({0})", System.Net.Dns.GetHostName());

            // open the session.
            Opc.Ua.UserIdentity identity = null;

            if (endpoint.UserIdentity != null)
            {
                // need to decode password.
                UserNameIdentityToken userNameToken = endpoint.UserIdentity as UserNameIdentityToken;

                if (userNameToken != null)
                {
                    UserNameIdentityToken copy = new UserNameIdentityToken();
                    copy.PolicyId            = userNameToken.PolicyId;
                    copy.DecryptedPassword   = new UTF8Encoding().GetString(userNameToken.Password);
                    copy.UserName            = userNameToken.UserName;
                    copy.EncryptionAlgorithm = userNameToken.EncryptionAlgorithm;
                    identity = new Opc.Ua.UserIdentity(copy);
                }

                // create the identity object.
                else
                {
                    identity = new Opc.Ua.UserIdentity(endpoint.UserIdentity);
                }
            }

            session.Open(sessionName, identity);

            // return the new session.
            return(session);
        }
Example #33
0
 public UaDiscoveryClient(ITransportChannel channel) : base(channel)
 {
 }