/// <summary> /// Fetches the servers from the discovery server. /// </summary> private bool DiscoverEndpoints(Uri discoveryUrl) { // use a short timeout. EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration); configuration.OperationTimeout = m_discoveryTimeout; DiscoveryClient client = DiscoveryClient.Create( discoveryUrl, BindingFactory.Create(m_configuration, m_configuration.CreateMessageContext()), EndpointConfiguration.Create(m_configuration)); try { EndpointDescriptionCollection endpoints = client.GetEndpoints(null); OnUpdateEndpoints(endpoints); return(true); } catch (Exception e) { Utils.Trace("Could not fetch endpoints from url: {0}. Reason={1}", discoveryUrl, e.Message); return(false); } finally { client.Close(); } }
/// <summary> /// Fetches the servers from the discovery server. /// </summary> private bool DiscoverServers(Uri discoveryUrl) { // use a short timeout. EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration); configuration.OperationTimeout = m_discoveryTimeout; DiscoveryClient client = null; try { client = DiscoveryClient.Create( discoveryUrl, BindingFactory.Create(m_configuration, m_configuration.CreateMessageContext()), EndpointConfiguration.Create(m_configuration)); ApplicationDescriptionCollection servers = client.FindServers(null); m_discoveryUrl = discoveryUrl.ToString(); OnUpdateServers(servers); return(true); } catch (Exception e) { Utils.Trace("DISCOVERY ERROR - Could not fetch servers from url: {0}. Error=({2}){1}", discoveryUrl, e.Message, e.GetType()); return(false); } finally { if (client != null) { client.Close(); } } }
/// <summary> /// Creates a new session. /// </summary> private Session CreateSession() { try { Cursor = Cursors.WaitCursor; ServiceMessageContext messageContext = m_configuration.CreateMessageContext(); BindingFactory bindingFactory = BindingFactory.Create(m_configuration, messageContext); ConfiguredEndpoint endpoint = this.EndpointsCTRL.SelectedEndpoint; endpoint.UpdateFromServer(bindingFactory); // Initialize the channel which will be created with the server. ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true), messageContext); // Wrap the channel with the session object. Session session = new Session(channel, m_configuration, endpoint, null); // Create the session. This actually connects to the server. session.Open(Guid.NewGuid().ToString(), null); return(session); } finally { Cursor = Cursors.Default; } }
private ServiceCommandOutput <object> CheckServiceConnectivity(string port, ServiceType type, ServiceSecurityMode mode) { var service = new WcfService <ICommandService <object>, DummyNativeCommandService>("localhost", ServiceName); service.AddBinding(BindingFactory.Create(new BindingConfiguration { Port = port, ServiceType = type })); if (mode == ServiceSecurityMode.BasicSSL) { var serviceSecurity = new ServiceSecurity { SecurityMode = ServiceSecurityMode.BasicSSL, CertificateConfiguration = _certificateConfiguration }; service.SetSecured(serviceSecurity); } service.Host(); var client = WcfClient <ICommandService <object> > .Create(type, "localhost", port, ServiceName, "api", mode); var output = client.Contract.ExecuteCommand("test", "token"); service.Stop(); return(output); }
/// <summary>Establishes the connection to an OPC UA server.</summary> /// <param name="url">The Url of the endpoint.</param> /// <returns>Result code.</returns> /// <exception cref="Exception">Throws and forwards any exception with short error description.</exception> public void Connect(EndpointDescription endpointDescription) { try { // Create the configuration. ApplicationConfiguration configuration = opcUA_Helper.CreateClientConfiguration(); // Create the endpoint configuration (use the application configuration to provide default values). EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration); // The default timeout for a requests sent using the channel. endpointConfiguration.OperationTimeout = 300000; // Use the pure binary encoding on the wire. endpointConfiguration.UseBinaryEncoding = true; // Create the endpoint. ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); // Create the binding factory. BindingFactory bindingFactory = BindingFactory.Create(configuration); X509Certificate2 clientCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find(); // Set up a callback to handle certificate validation errors. configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); // Initialize the channel which will be created with the server. SessionChannel channel = SessionChannel.Create( configuration, endpointDescription, endpointConfiguration, bindingFactory, clientCertificate, null); // Wrap the channel with the session object. // This call will fail if the server does not trust the client certificate. m_Session = new Session(channel, configuration, endpoint); m_Session.ReturnDiagnostics = DiagnosticsMasks.All; // Register keep alive callback. m_Session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); UserIdentity identity = new UserIdentity(); // Create the session. This actually connects to the server. // Passing null for the user identity will create an anonymous session. m_Session.Open("Siemens OPC UA sample client - main session", identity); } catch (Exception e) { throw e; } }
/// <summary> /// Fetches the network servers from the discovery server. /// </summary> private bool DiscoverServersOnNetwork(Uri discoveryUrl) { // use a short timeout. EndpointConfiguration configuration = EndpointConfiguration.Create(m_configuration); configuration.OperationTimeout = m_discoveryTimeout; DiscoveryClient client = null; try { client = DiscoveryClient.Create( discoveryUrl, BindingFactory.Create(m_configuration, m_configuration.CreateMessageContext()), EndpointConfiguration.Create(m_configuration)); uint startingRecordId = (uint)0; uint maxRecordsToReturn = (uint)0; StringCollection serverCapabilityFilter = new StringCollection(); DateTime lastCounterResetTime = DateTime.MinValue; try { startingRecordId = (uint)m_startingRecordIdUpDown.Value; maxRecordsToReturn = (uint)m_maxRecordsToReturnUpDown.Value; if (!String.IsNullOrEmpty(m_capabilityFilterTextBox.Text)) { serverCapabilityFilter = new StringCollection(m_capabilityFilterTextBox.Text.Split(',')); } } catch (Exception e) { Utils.Trace("Error retrieving FindServersOnNetwork paramters. Error=({1}){0}", e.Message, e.GetType()); return(false); } ServerOnNetworkCollection servers = client.FindServersOnNetwork(startingRecordId, maxRecordsToReturn, serverCapabilityFilter, out lastCounterResetTime); m_discoveryUrl = discoveryUrl.ToString(); OnUpdateServers(servers); return(true); } catch (Exception e) { Utils.Trace("DISCOVERY ERROR - Could not fetch servers from url: {0}. Error=({2}){1}", discoveryUrl, e.Message, e.GetType()); return(false); } finally { if (client != null) { client.Close(); } } }
public void Create_ReturnsBinding() { var source = new Mock <INotifyPropertyChanged>(); var propertyInfo = new Mock <PropertyInfo>(); var wem = new Mock <IWeakEventManager>(); var factory = new BindingFactory(); var res = factory.Create(source.Object, propertyInfo.Object, wem.Object); res.ShouldNotBeNull(); res.PropertyInfo.ShouldBe(propertyInfo.Object); res.Source.ShouldBe(source.Object); }
/// <summary> /// 连接, mqg于20180914增加,增加PLC会话超时时间 /// </summary> /// <param name="endpointDescription"></param> /// <param name="userIdentity"></param> /// <param name="timeOverMinutes"></param> public void Connect(EndpointDescription endpointDescription, UserIdentity userIdentity, int timeOverMinutes) { try { //Secify application configuration ApplicationConfiguration ApplicationConfig = mApplicationConfig; //ApplicationConfig.SecurityConfiguration.AutoAcceptUntrustedCertificates = true; //Hook up a validator function for a CertificateValidation event ApplicationConfig.CertificateValidator.CertificateValidation += Validator_CertificateValidation; //Create EndPoint configuration EndpointConfiguration EndpointConfiguration = EndpointConfiguration.Create(ApplicationConfig); //Connect to server and get endpoints ConfiguredEndpoint mEndpoint = new ConfiguredEndpoint(null, endpointDescription, EndpointConfiguration); //Create the binding factory. BindingFactory bindingFactory = BindingFactory.Create(mApplicationConfig, ServiceMessageContext.GlobalContext); //Create anonymous user identity //UserIdentity UserIdentity = new UserIdentity(); //Create and connect session mSession = Session.Create( ApplicationConfig, mEndpoint, true, "MySession", Convert.ToUInt32(timeOverMinutes * 60000), userIdentity, null ); mSession.KeepAlive += new KeepAliveEventHandler(Notification_KeepAlive); } catch (Exception e) { //handle Exception here throw e; } }
/// <summary> /// Updates an endpoint with information from the server's discovery endpoint. /// </summary> /// <param name="endpoint">The server endpoint</param> private void UpdateEndpoint(ConfiguredEndpoint endpoint) { try { Cursor = Cursors.WaitCursor; // create the binding factory if it has not been created yet. if (m_bindingFactory == null) { m_bindingFactory = BindingFactory.Create(m_configuration); } endpoint.UpdateFromServer(m_bindingFactory); } finally { Cursor = Cursors.Default; } }
private static void securelyUpdateEndpointConfiguration(ConfiguredEndpoint ep, ApplicationConfiguration applicationConfiguration) { // ep.UpdateFromServer(...) looks for matching endpoints on the server. // If there is no match with the same securityMode and securityPolicy, it will simply // _replace_ ep by one of the server endpoints, possibly lowering the security settings. Therefore: // save old settings - update from server - verify security settings -- and throw update from server away if security settings have changed. // note that ConfiguredEndpoints need a collection to live in. Note also that some settings of the configured endpoint may be changed nonetheless behind the scenes. ConfiguredEndpointCollection cepc = new ConfiguredEndpointCollection(); EndpointDescription epd = (EndpointDescription)ep.Description.Clone(); ConfiguredEndpoint cep = new ConfiguredEndpoint(cepc, epd); Opc.Ua.BindingFactory bindingFactory = BindingFactory.Create(applicationConfiguration, applicationConfiguration.CreateMessageContext()); ep.UpdateFromServer(bindingFactory); if (ep.Description.SecurityMode != epd.SecurityMode || ep.Description.SecurityPolicyUri != epd.SecurityPolicyUri) { ep.Update(cep); throw ServiceResultException.Create(StatusCodes.BadConfigurationError, "No endpoint with matching security configuration could be found during updated on connect."); } }
public static void RunBindingFactorySample() { var binding = BindingFactory.Create <BasicHttpBinding>() as BasicHttpBinding; Console.WriteLine("MaxReceivedMessageSize = {0}", binding.MaxReceivedMessageSize); Console.WriteLine("MaxBufferSize = {0}", binding.MaxBufferSize); Console.WriteLine("MaxBufferPoolSize = {0}", binding.MaxBufferPoolSize); Console.WriteLine("OpenTimeout = {0}", binding.OpenTimeout); Console.WriteLine("SendTimeout = {0}", binding.SendTimeout); Console.WriteLine("----------------------------"); var binding2 = BindingFactory.Create(typeof(BasicHttpBinding)) as BasicHttpBinding; Console.WriteLine("MaxReceivedMessageSize = {0}", binding2.MaxReceivedMessageSize); Console.WriteLine("MaxBufferSize = {0}", binding2.MaxBufferSize); Console.WriteLine("MaxBufferPoolSize = {0}", binding2.MaxBufferPoolSize); Console.WriteLine("OpenTimeout = {0}", binding2.OpenTimeout); Console.WriteLine("SendTimeout = {0}", binding2.SendTimeout); Console.WriteLine("----------------------------"); var binding3 = BindingFactory.Create <BasicHttpBinding>("lucene") as BasicHttpBinding; Console.WriteLine("MaxReceivedMessageSize = {0}", binding3.MaxReceivedMessageSize); Console.WriteLine("MaxBufferSize = {0}", binding3.MaxBufferSize); Console.WriteLine("MaxBufferPoolSize = {0}", binding3.MaxBufferPoolSize); Console.WriteLine("OpenTimeout = {0}", binding3.OpenTimeout); Console.WriteLine("SendTimeout = {0}", binding3.SendTimeout); Console.WriteLine("----------------------------"); var binding4 = BindingFactory.Create <BasicHttpBinding>("promotion") as BasicHttpBinding; Console.WriteLine("MaxReceivedMessageSize = {0}", binding4.MaxReceivedMessageSize); Console.WriteLine("MaxBufferSize = {0}", binding4.MaxBufferSize); Console.WriteLine("MaxBufferPoolSize = {0}", binding4.MaxBufferPoolSize); Console.WriteLine("OpenTimeout = {0}", binding4.OpenTimeout); Console.WriteLine("SendTimeout = {0}", binding4.SendTimeout); Console.WriteLine("----------------------------"); }
/// <summary> /// Create a session with the given UA server /// </summary> /// <param name="discoveryUrl"></param> /// <param name="configSection"></param> /// <returns></returns> public static Session CreateSession(string discoveryUrl, string configSection) { // Step 1 -- Load configuration ApplicationConfiguration configuration = ApplicationConfiguration.Load(configSection, ApplicationType.Client); ClientUtils.CheckApplicationInstanceCertificate(configuration); // Step 2 -- Select an endpoint // create the endpoint description EndpointDescription endpointDescription = ClientUtils.SelectEndpoint(discoveryUrl, false); endpointDescription.SecurityMode = MessageSecurityMode.None; endpointDescription.SecurityPolicyUri = @"http://opcfoundation.org/UA/SecurityPolicy#None"; // create the endpoint configuration EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration); // the default timeout for a requests sent using the channel. endpointConfiguration.OperationTimeout = 600000; // create the endpoint. ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); // choose the encoding strategy: true: BinaryEncoding; false: XmlEncoding endpoint.Configuration.UseBinaryEncoding = true; // create the binding factory. BindingFactory bindingFactory = BindingFactory.Create(configuration, configuration.CreateMessageContext()); // update endpoint description using the discovery endpoint. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(bindingFactory); //Console.Error.WriteLine("Updated endpoint description for url: {0}\n", endpointDescription.EndpointUrl); endpointDescription = endpoint.Description; endpointConfiguration = endpoint.Configuration; } X509Certificate2 clientCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find(); // set up a callback to handle certificate validation errors. configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); // Step 3 -- Initialize the channel which will be created with the server. SessionChannel channel = SessionChannel.Create( configuration, endpointDescription, endpointConfiguration, bindingFactory, clientCertificate, null); // Step 4 -- Create a session Session session = new Session(channel, configuration, endpoint); session.ReturnDiagnostics = DiagnosticsMasks.All; string sessionName = "SenderSession"; UserIdentity identity = new UserIdentity(); // anonymous session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); session.Open(sessionName, identity); return(session); }
/// <summary> /// This method executes the test cases for the configured endpoint. /// In case of multiple channel test cases, this endpoint value is ignored and new /// endpoint is used to connect to the server specified in test configuration. /// </summary> /// <param name="endpoint">This parameter stores an endpoint of the server.</param> public void ExecuteTestSequence(ConfiguredEndpoint endpoint) { lock (m_lock) { m_cancel = false; } if (endpoint.UpdateBeforeConnect) { // create the binding factory if it has not been created yet. if (m_bindingFactory == null) { m_bindingFactory = BindingFactory.Create(m_configuration, m_messageContext); } endpoint.UpdateFromServer(m_bindingFactory); } ChannelContext selectedChannelContext = null; selectedChannelContext = InitializeChannel(endpoint, m_logFilePath); try { foreach (TestCase testCase in m_sequenceToExecute.TestCase) { if (testCase.SkipTest || testCase.Name.StartsWith(TestCases.SerializerDirect)) { continue; } try { TestUtils.ValidateTestCase(testCase, (int)testCase.Start); } catch (Exception e) { selectedChannelContext.EventLogger.LogErrorEvent(testCase, (int)testCase.Start, e); if (m_sequenceToExecute.HaltOnError) { throw; } else { continue; } } TestCaseContext testCaseContext = TestUtils.GetExecutionContext(testCase); try { ValidateTestContext(testCaseContext, testCase); } catch (Exception e) { selectedChannelContext.EventLogger.LogErrorEvent(testCase, (int)testCase.Start, e); if (m_sequenceToExecute.HaltOnError) { throw; } else { continue; } } if (testCase.Name != TestCases.MultipleChannels) { ExecuteTestCase(selectedChannelContext, testCaseContext, testCase); } else { Uri defaultUrl = new Uri(endpoint.Description.EndpointUrl); // In case of multiple channel get endpoint urls from the test case file. List <ChannelContext> channelContextList = new List <ChannelContext>(); List <ConfiguredEndpoint> configuredEndpointList = new List <ConfiguredEndpoint>(); for (int serverCnt = 0; serverCnt < testCaseContext.ServerDetails.Count; serverCnt++) { string serverURL = testCaseContext.ServerDetails[serverCnt].Url; serverURL = serverURL.Replace("localhost", defaultUrl.DnsSafeHost); //ConfiguredEndpointCollection endpointCollection = new ConfiguredEndpointCollection () ; //ConfiguredEndpoint serverendpoint = endpointCollection.Create(serverURL); ConfiguredEndpoint serverendpoint = (ConfiguredEndpoint)endpoint.Clone(); // slow systems may not be able to renew tokens fast enough when overloaded with channels. serverendpoint.Configuration.SecurityTokenLifetime = 60000; serverendpoint.Description.EndpointUrl = serverURL; configuredEndpointList.Add(serverendpoint); //For each channel get the log file name as <default file name>_<server name>_<channel index>. for (int channelCnt = 0; channelCnt < testCaseContext.ChannelsPerServer; channelCnt++) { string logFileSuffix = "_" + testCaseContext.ServerDetails[serverCnt].Name + "_" + channelCnt.ToString(); string logFileName = m_logFilePath.Replace(".xml", logFileSuffix) + ".xml"; ChannelContext channelContext = InitializeChannel(configuredEndpointList[serverCnt], logFileName); channelContextList.Add(channelContext); } } try { WaitHandle[] waitHandles = new WaitHandle[channelContextList.Count]; for (int iCtr = 0; iCtr < channelContextList.Count; iCtr++) { waitHandles[iCtr] = channelContextList[iCtr].TestCaseComplete; ThreadPool.QueueUserWorkItem(ExecuteTestCase, new object[] { channelContextList[iCtr], testCaseContext, testCase }); } WaitHandle.WaitAll(waitHandles); } finally { for (int iCtr = 0; iCtr < channelContextList.Count; iCtr++) { WindupChannel(channelContextList[iCtr]); } } } } } finally { WindupChannel(selectedChannelContext); } RaiseEvent(new TestSequenceEventArgs(0, "Done", 0)); }
static void Main(string[] args) { VariableBrowsePaths = new List <string>(); VariableBrowsePaths.Add("/6:Data/6:Dynamic/6:Scalar/6:Int32Value"); // VariableBrowsePaths.Add("/7:MatrikonOpc Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int1"); // VariableBrowsePaths.Add("/7:MatrikonOPC Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int2"); try { // create the configuration. ApplicationConfiguration configuration = Helpers.CreateClientConfiguration(); // create the endpoint description. EndpointDescription endpointDescription = Helpers.CreateEndpointDescription(); // create the endpoint configuration (use the application configuration to provide default values). EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configuration); // the default timeout for a requests sent using the channel. endpointConfiguration.OperationTimeout = 600000; // use the pure XML encoding on the wire. endpointConfiguration.UseBinaryEncoding = true; // create the endpoint. ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); // create the binding factory. ServiceMessageContext messageContext = configuration.CreateMessageContext(); BindingFactory bindingFactory = BindingFactory.Create(configuration, messageContext); // update endpoint description using the discovery endpoint. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(bindingFactory); Console.WriteLine("Updated endpoint description for url: {0}", endpointDescription.EndpointUrl); endpointDescription = endpoint.Description; endpointConfiguration = endpoint.Configuration; } X509Certificate2 clientCertificate = configuration.SecurityConfiguration.ApplicationCertificate.Find(); // set up a callback to handle certificate validation errors. configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); // Initialize the channel which will be created with the server. ITransportChannel channel = SessionChannel.Create( configuration, endpointDescription, endpointConfiguration, clientCertificate, messageContext); // Wrap the channel with the session object. // This call will fail if the server does not trust the client certificate. Session session = new Session(channel, configuration, endpoint, null); session.ReturnDiagnostics = DiagnosticsMasks.All; // register keep alive callback. // session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // passing null for the user identity will create an anonymous session. UserIdentity identity = null; // new UserIdentity("iamuser", "password"); // create the session. This actually connects to the server. session.Open("My Session Name", identity); //Read some history values: string str = ""; do { Console.WriteLine("Select action from the menu:\n"); Console.WriteLine("\t 0 - Browse"); Console.WriteLine("\t 1 - Update"); Console.WriteLine("\t 2 - ReadRaw"); Console.WriteLine("\t 3 - ReadProcessed"); Console.WriteLine("\t 4 - ReadAtTime"); Console.WriteLine("\t 5 - ReadAttributes"); Console.WriteLine("\t 6 - DeleteAtTime"); Console.WriteLine("\t 7 - DeleteRaw"); Console.WriteLine("\n\tQ - exit\n\n"); str = Console.ReadLine(); Console.WriteLine("\n"); try { if (str == "0") { Browse(session); } else if (str == "1") { HistoryUpdate(session); } else if (str == "2") { HistoryReadRaw(session); } else if (str == "3") { HistoryReadProcessed(session); } else if (str == "4") { HistoryReadAtTime(session); } else if (str == "5") { HistoryReadAttributes(session); } else if (str == "6") { HistoryDeleteAtTime(session); } else if (str == "7") { HistoryDeleteRaw(session); } } catch (Exception e) { Console.WriteLine("Exception occured: " + e.Message); } } while (str != "Q" && str != "q"); // Display some friendly info to the console and then wait for the ENTER key to be pressed. Console.WriteLine("Connected to {0}.\nPress ENTER to disconnect to end.", DefaultServerUrl); Console.ReadLine(); // Close and Dispose of our session, effectively disconnecting us from the UA Server. session.Close(); session.Dispose(); } catch (Exception e) { Console.WriteLine("Unexpected exception: {0}.\nPress ENTER to disconnect to end.", e.Message); Console.ReadLine(); Console.WriteLine(); Console.WriteLine("========================================================================================"); Console.WriteLine(); } }
protected virtual Binding GetBinding(ServiceMetadata meta) { var bindingType = Type.GetType(meta.Binding); return(BindingFactory.Create(bindingType)); }
private void RunCommandService() { _serviceFacade = new ServiceCore(); string internalSessionId = Guid.NewGuid().ToString(); // Ensure that the super user admin exists _serviceFacade.ExecuteCommand(new ServiceRequestContext { Command = String.Format("NewUser /name:{0} /pwd:{1} /cpwd:{1} /role:admin /silent", AzureContext.Current.Config.Runtime.SuperUser.Username, AzureContext.Current.Config.Runtime.SuperUser.Password), SessionId = internalSessionId }); // Ensure that the super user readonly exists _serviceFacade.ExecuteCommand(new ServiceRequestContext { Command = String.Format("NewUser /name:{0}_ro /pwd:{1} /cpwd:{1} /role:readonly /silent", AzureContext.Current.Config.Runtime.SuperUser.Username, AzureContext.Current.Config.Runtime.SuperUser.Password), SessionId = internalSessionId }); var serviceConfig = AzureContext.Current.Config.Runtime.Server; _serviceHostNative = new WcfService <ICommandService <object>, NativeCommandService>("localhost", "CommandService"); _serviceHostJson = new WcfService <ICommandService <string>, JsonCommandService>("localhost", "CommandService"); for (int i = 0; i < serviceConfig.Count; i++) { var configuration = new BindingConfiguration { Port = serviceConfig[i].Port.ToString(CultureInfo.InvariantCulture), ServiceType = serviceConfig[i].GetWcfServiceType() }; var binding = BindingFactory.Create(configuration); if (binding.DataTypes.IsSet(DataTypeSupport.Native)) { _serviceHostNative.AddBinding(binding); } else if (binding.DataTypes.IsSet(DataTypeSupport.Json)) { _serviceHostJson.AddBinding(binding); } } if (AzureContext.Current.Config.Runtime.ServiceSecurity == ServiceSecurityMode.BasicSSL) { var serviceSecurity = new ServiceSecurity { CertificateConfiguration = AzureContext.Current.Config.Certificate.Default, SecurityMode = AzureContext.Current.Config.Runtime.ServiceSecurity }; _serviceHostJson.SetSecured(serviceSecurity); _serviceHostNative.SetSecured(serviceSecurity); } _serviceHostNative.Host(); _serviceHostJson.Host(); var authOutput = _serviceFacade.ExecuteCommand(new ServiceRequestContext { Command = String.Format("UserAuth /name:{0} /pwd:{1}", AzureContext.Current.Config.Runtime.SuperUser.Username, AzureContext.Current.Config.Runtime.SuperUser.Password), SessionId = internalSessionId }); var authenticationOutput = authOutput.Data as AuthenticationOutput; if (authenticationOutput == null) { throw new InvalidOperationException( "Could not authenticate server user: "******"GetSettings", SessionId = internalSessionId }); if (settingsOutput != null && settingsOutput.Data != null) { var settings = (Dictionary <string, string>)settingsOutput.Data; foreach (var setting in settings) { CurrentContext.Default.ApplicationParams.Add(setting.Key, setting.Value); } } //AppContext.Current.Log.Info("Agent Started: " + _serviceHostNative); //AppContext.Current.Log.Info("Agent Started: " + _serviceHostJson); }
/// <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) { BindingFactory bindingFactory = BindingFactory.Create(m_configuration, m_messageContext); endpoint.UpdateFromServer(bindingFactory); } 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); } }
/// <summary> /// Runs the testcases against the endpoint. /// </summary> /// <param name="endpoint">The endpoint to test.</param> /// <param name="testcases">The testcases to run.</param> public void Run(ConfiguredEndpoint endpoint, ServerTestConfiguration testConfiguration) { // save the test configuration. m_testConfiguration = testConfiguration; m_stopped = false; // create the binding factory. m_bindingFactory = BindingFactory.Create(m_configuration, m_messageContext); while (!m_stopped) { try { Report("Test run started."); // update from server. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(m_bindingFactory); Report("Updated endpoint from the discovery endpoint."); } // validate the server certificate. byte[] certificateData = endpoint.Description.ServerCertificate; try { X509Certificate2 certificate = CertificateFactory.Create(certificateData, true); m_configuration.CertificateValidator.Validate(certificate); } catch (ServiceResultException e) { if (e.StatusCode != StatusCodes.BadCertificateUntrusted) { throw new ServiceResultException(e, StatusCodes.BadCertificateInvalid); } // automatically trust the certificate if it is untrusted. m_configuration.CertificateValidator.Update(m_configuration.SecurityConfiguration); } m_defaultEndpoint = endpoint; // fetch all endpoints from the server. m_endpoints = GetEndpoints(endpoint); Report("Fetched all endpoints supported by the server."); } catch (Exception e) { Report(e, "Could not connect to server"); return; } m_endpointCount = 0; m_totalEndpointCount = 0; m_testCount = 0; m_failedTestCount = 0; m_iterationCount = 0; m_totalIterationCount = 0; uint totalCount = 0; uint failedCount = 0; uint endpointCount = 0; if (m_testConfiguration.EndpointSelection != EndpointSelection.Single) { EndpointSelection selection = m_testConfiguration.EndpointSelection; foreach (ConfiguredEndpoint current in m_endpoints.Endpoints) { if (IsEndpointSelected(current, selection, false)) { m_totalEndpointCount++; } if (current.Description.EncodingSupport == BinaryEncodingSupport.Optional) { if (IsEndpointSelected(current, selection, true)) { m_totalEndpointCount++; } } } foreach (ConfiguredEndpoint current in m_endpoints.Endpoints) { if (IsEndpointSelected(current, selection, false)) { m_endpointCount++; // check if test stopped. if (m_stopped) { break; } DoTestForEndpoint(current, ref totalCount, ref failedCount); endpointCount++; } if (current.Description.EncodingSupport == BinaryEncodingSupport.Optional) { if (IsEndpointSelected(current, selection, true)) { m_endpointCount++; // check if test stopped. if (m_stopped) { break; } current.Configuration.UseBinaryEncoding = !current.Configuration.UseBinaryEncoding; DoTestForEndpoint(current, ref totalCount, ref failedCount); endpointCount++; } } } } else { m_endpointCount++; m_totalEndpointCount = 1; DoTestForEndpoint(m_defaultEndpoint, ref totalCount, ref failedCount); endpointCount++; } if (failedCount > 0) { Report("WARNING: {0} tests failed. {1} tests run.", failedCount, totalCount); } else { Report("{0} tests completed successfully for {1} endpoints.", totalCount, endpointCount); DumpPerfData(); } if (!m_testConfiguration.Continuous) { break; } } }
public void connect() { clearSession(); #region Server var lServers = getServersDescr(mDiscovery); ApplicationDescription lApplication = null; foreach (var lServer in lServers) { if (mServerName.Equals(lServer.ApplicationName.ToString(), StringComparison.Ordinal)) { lApplication = lServer; break; } } if (lApplication == null) { throw new InvalidOperationException("Unable to find server. "); } var lEndpoints = DiscoveryClient.Create(new Uri(lApplication.DiscoveryUrls[0])).GetEndpoints(null); EndpointDescription lEndpoint = null; foreach (var lEP in lEndpoints) { try { if (getTransport(lEP.EndpointUrl) == mTransport && lEP.SecurityMode == MessageSecurityMode.None) { lEndpoint = lEP; break; } } catch { } } if (lEndpoint == null) { throw new InvalidOperationException("Unable to find suitable endpoint. "); } mHost = mDiscovery.Split(':')[1].Substring(2); lEndpoint.EndpointUrl = lEndpoint.EndpointUrl.Replace("localhost", mHost); #endregion #region ApplicationConfiguration var lAppConfig = new ApplicationConfiguration(); lAppConfig.ApplicationName = "Process Simulator 2"; lAppConfig.ApplicationType = ApplicationType.Client; lAppConfig.ApplicationUri = "http://localhost/VendorId/ApplicationId/InstanceId"; lAppConfig.ProductUri = "http://VendorId/ProductId/VersionId"; lAppConfig.SecurityConfiguration = new SecurityConfiguration(); lAppConfig.SecurityConfiguration.ApplicationCertificate = new CertificateIdentifier(); lAppConfig.SecurityConfiguration.ApplicationCertificate.StoreType = CertificateStoreType.Windows; lAppConfig.SecurityConfiguration.ApplicationCertificate.StorePath = "LocalMachine\\My"; lAppConfig.SecurityConfiguration.ApplicationCertificate.SubjectName = lAppConfig.ApplicationName; lAppConfig.SecurityConfiguration.TrustedPeerCertificates.StoreType = CertificateStoreType.Windows; lAppConfig.SecurityConfiguration.TrustedPeerCertificates.StorePath = "LocalMachine\\My"; var lClientCertificate = lAppConfig.SecurityConfiguration.ApplicationCertificate.Find(true); if (lClientCertificate == null) { lClientCertificate = CertificateFactory.CreateCertificate( lAppConfig.SecurityConfiguration.ApplicationCertificate.StoreType, lAppConfig.SecurityConfiguration.ApplicationCertificate.StorePath, lAppConfig.ApplicationUri, lAppConfig.ApplicationName, null, null, 1024, 120); } lAppConfig.TransportConfigurations.Add(new TransportConfiguration(Opc.Ua.Utils.UriSchemeOpcTcp, typeof(Opc.Ua.Bindings.UaTcpBinding))); lAppConfig.TransportConfigurations.Add(new TransportConfiguration(Opc.Ua.Utils.UriSchemeHttp, typeof(Opc.Ua.Bindings.UaSoapXmlBinding))); lAppConfig.TransportQuotas = new TransportQuotas(); lAppConfig.TransportQuotas.OperationTimeout = 360000; lAppConfig.TransportQuotas.MaxStringLength = 67108864; lAppConfig.ServerConfiguration = new ServerConfiguration(); lAppConfig.ClientConfiguration = new ClientConfiguration(); lAppConfig.ClientConfiguration.DefaultSessionTimeout = 36000; lAppConfig.Validate(ApplicationType.Client); #endregion #region Session var lEndpointConfig = EndpointConfiguration.Create(lAppConfig); lEndpointConfig.OperationTimeout = 300000; lEndpointConfig.UseBinaryEncoding = true; var lConfiguredEndpoint = new ConfiguredEndpoint(null, lEndpoint, lEndpointConfig); var lBindingFactory = BindingFactory.Create(lAppConfig, new ServiceMessageContext()); lAppConfig.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = true; }; var lChannel = SessionChannel.Create(lAppConfig, lEndpoint, lEndpointConfig, lBindingFactory, lClientCertificate, null); mSession = new Session(lChannel, lAppConfig, lConfiguredEndpoint); mSession.ReturnDiagnostics = DiagnosticsMasks.All; mSession.KeepAlive += MSession_KeepAlive; mSession.Notification += MSession_Notification; mSession.PublishError += MSession_PublishError; if (String.IsNullOrWhiteSpace(mLogin) == false && String.IsNullOrWhiteSpace(mPassword) == false) { mSession.Open("Process Simulator 2 session", new UserIdentity(mLogin, mPassword)); } else { mSession.Open("Process Simulator 2 session", null); } #endregion #region Namespace var lNewNamespaces = getNamespaces(); if (mNamespaces != null && NumberOfItems > 0) { int lIndex; int[] lNsChanges = new int[mNamespaces.Length]; bool lNeedChanges = false; for (int i = 0; i < mNamespaces.Length; i++) { lIndex = StringUtils.getIndex(lNewNamespaces, mNamespaces[i]); if (lIndex == -1) { throw new InvalidOperationException("Namespace '" + mNamespaces[i] + "' is missing. "); } lNsChanges[i] = lIndex; if (i != lIndex) { lNeedChanges = true; } } if (lNeedChanges) { foreach (DataItem lItem in mItemList) { if (lItem.mNodeId.NamespaceIndex != lNsChanges[lItem.mNodeId.NamespaceIndex]) { lItem.mNodeId = new NodeId(lItem.mNodeId.Identifier, (ushort)lNsChanges[lItem.mNodeId.NamespaceIndex]); } } mNamespaces = lNewNamespaces; } } else { mNamespaces = lNewNamespaces; } #endregion #region Subscription mSubscription = new Subscription(mSession.DefaultSubscription); mSubscription.DisplayName = "Subscription"; mSubscription.PublishingEnabled = true; mSubscription.PublishingInterval = mPublishingInterval; mSubscription.KeepAliveCount = 10; mSubscription.LifetimeCount = 100; mSubscription.MaxNotificationsPerPublish = 100; mSession.AddSubscription(mSubscription); mSubscription.Create(); byte lAccess; object lValue; StatusCode lStatusCode; string lType; bool lArray; int lNotOKItemsCount = 0; foreach (DataItem lItem in mItemList) { try { checkVariable(lItem.mNodeId, out lAccess, out lValue, out lStatusCode, out lType, out lArray); lItem.setAccess(lAccess); lItem.StatusCode = lStatusCode; if ((lAccess == AccessLevels.CurrentRead || lAccess == AccessLevels.CurrentReadOrWrite) && StatusCode.IsGood(lStatusCode) && lValue != null) { lItem.mValue = lValue; } else { lItem.initValue(lType, lArray); } addItemToSubscription(lItem); } catch (Exception lExc) { lItem.setAccess(AccessLevels.None); lNotOKItemsCount = lNotOKItemsCount + 1; Log.Error("Data item '" + lItem.mNodeId.ToString() + "' activation error. " + lExc.Message, lExc.ToString()); } } mSubscription.ApplyChanges(); #endregion mConnected = true; raiseConnectionState(); #region Update Item Values if (mItemList.Count > lNotOKItemsCount) { foreach (DataItem lItem in mItemList) { if (lItem.Access.HasFlag(EAccess.READ)) { lItem.raiseValueChanged(); } } } #endregion if (lNotOKItemsCount > 0) { throw new InvalidOperationException("Unable to activate " + StringUtils.ObjectToString(lNotOKItemsCount) + " data item(s). "); } }
protected override void OnStart(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; var contextSettings = new ContextSettings { CommandFactory = new CommandFactory() }; HostContext.CreateFrom(_arguments.GetValue("configPath", "konfdb.json"), contextSettings); CurrentHostContext.Default.Log.Info("Agent Started: DataManagement"); #region Run Command Service ServiceFacade = new ServiceCore(); string internalSessionId = Guid.NewGuid().ToString(); // Ensure that the super user admin exists ServiceFacade.ExecuteCommand(new ServiceRequestContext { Command = String.Format("NewUser /name:{0} /pwd:{1} /cpwd:{1} /role:admin /silent", CurrentHostContext.Default.Config.Runtime.SuperUser.Username, CurrentHostContext.Default.Config.Runtime.SuperUser.Password), SessionId = internalSessionId }); // Ensure that the super user readonly exists ServiceFacade.ExecuteCommand(new ServiceRequestContext { Command = String.Format("NewUser /name:{0}_ro /pwd:{1} /cpwd:{1} /role:readonly /silent", CurrentHostContext.Default.Config.Runtime.SuperUser.Username, CurrentHostContext.Default.Config.Runtime.SuperUser.Password), SessionId = internalSessionId }); var serviceConfig = CurrentHostContext.Default.Config.Runtime.Server; _serviceHostNative = new WcfService <ICommandService <object>, NativeCommandService>("localhost", "CommandService"); _serviceHostJson = new WcfService <ICommandService <string>, JsonCommandService>("localhost", "CommandService"); for (int i = 0; i < serviceConfig.Count; i++) { var configuration = new BindingConfiguration { Port = serviceConfig[i].Port.ToString(CultureInfo.InvariantCulture), ServiceType = serviceConfig[i].GetWcfServiceType() }; var binding = BindingFactory.Create(configuration); if (binding.DataTypes.IsSet(DataTypeSupport.Native)) { _serviceHostNative.AddBinding(binding); } else if (binding.DataTypes.IsSet(DataTypeSupport.Json)) { _serviceHostJson.AddBinding(binding); } } if (CurrentHostContext.Default.Config.Runtime.ServiceSecurity == ServiceSecurityMode.BasicSSL) { var serviceSecurity = new ServiceSecurity { CertificateConfiguration = CurrentHostContext.Default.Config.Certificate.Default, SecurityMode = CurrentHostContext.Default.Config.Runtime.ServiceSecurity }; _serviceHostJson.SetSecured(serviceSecurity); _serviceHostNative.SetSecured(serviceSecurity); } _serviceHostNative.Host(); _serviceHostJson.Host(); var authOutput = ServiceFacade.ExecuteCommand(new ServiceRequestContext { Command = String.Format("UserAuth /name:{0} /pwd:{1}", CurrentHostContext.Default.Config.Runtime.SuperUser.Username, CurrentHostContext.Default.Config.Runtime.SuperUser.Password), SessionId = internalSessionId }); var authenticationOutput = authOutput.Data as AuthenticationOutput; if (authenticationOutput == null) { throw new InvalidOperationException( "Could not authenticate server user: "******"GetSettings", SessionId = internalSessionId }); if (settingsOutput != null && settingsOutput.Data != null) { var settings = (Dictionary <string, string>)settingsOutput.Data; foreach (var setting in settings) { CurrentHostContext.Default.ApplicationParams.Add(setting.Key, setting.Value); } } //AppContext.Current.Log.Info("Agent Started: " + _serviceHostNative); //AppContext.Current.Log.Info("Agent Started: " + _serviceHostJson); #endregion _thread = new Thread(RunInBackground) { Name = "ShellService", IsBackground = true }; _shutdownEvent = new ManualResetEvent(false); _thread.Start(); }
protected override Binding GetBinding(ServiceMetadata meta) { var bindingType = Type.GetType(meta.Binding); return(BindingFactory.Create(bindingType, "unary")); }