/// <summary> /// Serializes the object to JSON. /// </summary> /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="obj">The object to serialize to JSON.</param> internal static void Serialize(JsonWriter writer, EndpointProperties obj) { // Required properties are always serialized, optional properties are serialized when not null. writer.WriteStartObject(); writer.WriteProperty(obj.Name, "name", JsonWriterExtensions.WriteStringValue); if (obj.Port != null) { writer.WriteProperty(obj.Port, "port", JsonWriterExtensions.WriteIntValue); } writer.WriteEndObject(); }
private void ProduceMessage(ISession session) { // Provision the queue string queueName = "Q/tutorial"; Console.WriteLine("Attempting to provision the queue '{0}'...", queueName); // Create the queue using (IQueue queue = ContextFactory.Instance.CreateQueue(queueName)) { // Set queue permissions to "consume" and access-type to "exclusive" EndpointProperties endpointProps = new EndpointProperties() { Permission = EndpointProperties.EndpointPermission.Consume, AccessType = EndpointProperties.EndpointAccessType.Exclusive }; // Provision it, and do not fail if it already exists session.Provision(queue, endpointProps, ProvisionFlag.IgnoreErrorIfEndpointAlreadyExists | ProvisionFlag.WaitForConfirm, null); Console.WriteLine("Queue '{0}' has been created and provisioned.", queueName); // Create the message using (IMessage message = ContextFactory.Instance.CreateMessage()) { // Message's destination is the queue and the message is persistent message.Destination = queue; message.DeliveryMode = MessageDeliveryMode.Persistent; // Create the message content as a binary attachment message.BinaryAttachment = Encoding.ASCII.GetBytes("Persistent Queue Tutorial"); // Send the message to the queue on the Solace messaging router Console.WriteLine("Sending message to queue {0}...", queueName); ReturnCode returnCode = session.Send(message); if (returnCode == ReturnCode.SOLCLIENT_OK) { // Delivery not yet confirmed. See ConfirmedPublish.cs Console.WriteLine("Done."); } else { Console.WriteLine("Sending failed, return code: {0}", returnCode); } } } }
public TransactedSessionHolder(string senderId, ContextProperties contextProps, SessionProperties sessionProps) { m_SenderId = senderId; Log.Start("Creating the Context"); m_Context = ContextFactory.Instance.CreateContext(contextProps, null); Log.Done(); Log.Start("Creating the Session"); m_Session = m_Context.CreateSession(sessionProps, HandleSessionMessage, HandleSessionEvent); Log.Done(); Log.Start("Connecting the Session"); Log.AssertOK(m_Session.Connect()); Log.Start("Checking capabilities"); Log.AssertTrue(m_Session.IsCapable(CapabilityType.TRANSACTED_SESSION), "The 'TRANSACTED_SESSION' capability is required to run this sample"); Log.Start("Creating Transacted Session"); m_TxSession = m_Session.CreateTransactedSession(new TransactedSessionProperties()); Log.Done(); Log.Start("Creating Temporary Queue"); m_Queue = m_Session.CreateTemporaryQueue(); Log.Done(); Log.Start("Creating consumer Flow"); FlowProperties flowProps = new FlowProperties(); flowProps.FlowStartState = true; EndpointProperties endpointProps = new EndpointProperties(); m_Flow = m_TxSession.CreateFlow(flowProps, m_Queue, null, HandleTransactedMessage, HandleFlowEvent, endpointProps); Log.Done(); }
/// <summary> /// Provision a Queue on appliance if one with the same name and Message VPN /// already exists. /// </summary> /// <param name="session"></param> /// <param name="queueName"></param> /// <param name="respectsMsgTTL"></param> private IQueue ProvisionQueue(ISession session, string queueName, bool respectsMsgTTL) { EndpointProperties endpointProps = new EndpointProperties(); // Set permissions to allow all permissions to others endpointProps.Permission = EndpointProperties.EndpointPermission.Delete; // Set access type to exclusive endpointProps.AccessType = EndpointProperties.EndpointAccessType.Exclusive; // Set quota to 100 MB endpointProps.Quota = 100; // Set respects TTL to respectsMsgTTL endpointProps.RespectsMsgTTL = respectsMsgTTL; IQueue queue = ContextFactory.Instance.CreateQueue(queueName); session.Provision(queue /* endpoint */, endpointProps /*endpoint properties */, ProvisionFlag.WaitForConfirm | ProvisionFlag.IgnoreErrorIfEndpointAlreadyExists /* block waiting for confirmation */, null /*no correlation key*/); Console.WriteLine(string.Format("Queue '{0}' successfully provisioned on the appliance", queueName)); return(queue); }
private static TrafficManagerEndpoint GetPowershellTrafficManagerEndpoint(string id, string resourceGroupName, string profileName, string endpointType, string endpointName, EndpointProperties mamlEndpointProperties) { return(new TrafficManagerEndpoint { Id = id, ResourceGroupName = resourceGroupName, ProfileName = profileName, Name = endpointName, Type = endpointType, TargetResourceId = mamlEndpointProperties.TargetResourceId, Target = mamlEndpointProperties.Target, EndpointStatus = mamlEndpointProperties.EndpointStatus, Location = mamlEndpointProperties.EndpointLocation, Priority = mamlEndpointProperties.Priority, Weight = mamlEndpointProperties.Weight, EndpointMonitorStatus = mamlEndpointProperties.EndpointMonitorStatus, MinChildEndpoints = mamlEndpointProperties.MinChildEndpoints, }); }
private static TrafficManagerEndpoint GetPowershellTrafficManagerEndpoint(string id, string resourceGroupName, string profileName, string endpointType, string endpointName, EndpointProperties mamlEndpointProperties) { return new TrafficManagerEndpoint { Id = id, ResourceGroupName = resourceGroupName, ProfileName = profileName, Name = endpointName, Type = endpointType, TargetResourceId = mamlEndpointProperties.TargetResourceId, Target = mamlEndpointProperties.Target, EndpointStatus = mamlEndpointProperties.EndpointStatus, Location = mamlEndpointProperties.EndpointLocation, Priority = mamlEndpointProperties.Priority, Weight = mamlEndpointProperties.Weight, EndpointMonitorStatus = mamlEndpointProperties.EndpointMonitorStatus, MinChildEndpoints = mamlEndpointProperties.MinChildEndpoints, }; }
void Run(IContext context, string host) { // Validate parameters if (context == null) { throw new ArgumentException("Solace Systems API context Router must be not null.", "context"); } if (string.IsNullOrWhiteSpace(host)) { throw new ArgumentException("Solace Messaging Router host name must be non-empty.", "host"); } if (string.IsNullOrWhiteSpace(VPNName)) { throw new InvalidOperationException("VPN name must be non-empty."); } if (string.IsNullOrWhiteSpace(UserName)) { throw new InvalidOperationException("Client username must be non-empty."); } // Create session properties SessionProperties sessionProps = new SessionProperties() { Host = host, VPNName = VPNName, UserName = UserName, ReconnectRetries = DefaultReconnectRetries }; // Connect to the Solace messaging router Console.WriteLine("Connecting as {0}@{1} on {2}...", UserName, VPNName, host); Session = context.CreateSession(sessionProps, null, null); ReturnCode returnCode = Session.Connect(); if (returnCode == ReturnCode.SOLCLIENT_OK) { Console.WriteLine("Session successfully connected."); // Provision the queue string queueName = "Q/tutorial"; Console.WriteLine("Attempting to provision the queue '{0}'...", queueName); // Set queue permissions to "consume" and access-type to "exclusive" EndpointProperties endpointProps = new EndpointProperties() { Permission = EndpointProperties.EndpointPermission.Consume, AccessType = EndpointProperties.EndpointAccessType.Exclusive }; // Create the queue Queue = ContextFactory.Instance.CreateQueue(queueName); // Provision it, and do not fail if it already exists Session.Provision(Queue, endpointProps, ProvisionFlag.IgnoreErrorIfEndpointAlreadyExists & ProvisionFlag.WaitForConfirm, null); Console.WriteLine("Queue '{0}' has been created and provisioned.", queueName); // Create and start flow to the newly provisioned queue // NOTICE HandleMessageEvent as the message event handler // and HandleFlowEvent as the flow event handler Flow = Session.CreateFlow(new FlowProperties() { AckMode = MessageAckMode.ClientAck }, Queue, null, HandleMessageEvent, HandleFlowEvent); Flow.Start(); Console.WriteLine("Waiting for a message in the queue '{0}'...", queueName); WaitEventWaitHandle.WaitOne(); } else { Console.WriteLine("Error connecting, return code: {0}", returnCode); } }
public override void SampleCall(string[] args) { #region Parse Arguments ArgParser cmdLineParser = new ArgParser(); if (!cmdLineParser.Parse(args)) { // parse failed PrintUsage(INVALID_ARGUMENTS_ERROR); return; } #endregion #region Initialize properties from command line // Initialize the properties. ContextProperties contextProps = new ContextProperties(); SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config); #endregion // Define IContext and ISession. IContext context = null; ISession session = null; IBrowser browser = null; IQueue queue = null; try { InitContext(cmdLineParser.LogLevel); #region Initialize the context, connect the Session, and assert capabilities. Console.WriteLine("About to create the context ..."); context = ContextFactory.Instance.CreateContext(contextProps, null); Console.WriteLine("Context successfully created "); Console.WriteLine("About to create the session ..."); session = context.CreateSession(sessionProps, SampleUtils.HandleMessageEvent, SampleUtils.HandleSessionEvent); Console.WriteLine("Session successfully created."); Console.WriteLine("About to connect the session ..."); if (session.Connect() == ReturnCode.SOLCLIENT_OK) { Console.WriteLine("Session successfully connected"); Console.WriteLine(GetRouterInfo(session)); } // Does the appliance support these capabilities:PUB_GUARANTEED,ENDPOINT_MANAGEMENT,BROWSER? Console.Write(String.Format("Check for capability: {0} ... ", CapabilityType.PUB_GUARANTEED)); if (!session.IsCapable(CapabilityType.PUB_GUARANTEED)) { Console.WriteLine("Not Supported\n Exiting"); return; } else { Console.WriteLine("Supported"); } Console.Write(String.Format("Check for capability: {0} ... ", CapabilityType.ENDPOINT_MANAGEMENT)); if (!session.IsCapable(CapabilityType.ENDPOINT_MANAGEMENT)) { Console.WriteLine("Not Supported\n Exiting"); return; } else { Console.WriteLine("Supported"); } Console.Write(String.Format("Check for capability: {0} ... ", CapabilityType.BROWSER)); if (!session.IsCapable(CapabilityType.BROWSER)) { Console.WriteLine("Not Supported \n Exiting"); return; } else { Console.WriteLine("Supported"); } #endregion #region Provision a new queue endpoint EndpointProperties endpointProps = new EndpointProperties(); // Set permissions to allow all permissions to others. endpointProps.Permission = EndpointProperties.EndpointPermission.Delete; // Set access type to exclusive. endpointProps.AccessType = EndpointProperties.EndpointAccessType.Exclusive; // Set quota to 100 MB. endpointProps.Quota = 100; string queueName = "solclient_dotnet_sample_QueueProvisionAndBrowse_" + (new Random()).Next(1000); queue = ContextFactory.Instance.CreateQueue(queueName); Console.WriteLine(String.Format("About to provision queue '{0}' on the appliance", queueName)); try { session.Provision(queue /* endpoint */, endpointProps /*endpoint properties */, ProvisionFlag.WaitForConfirm /* block waiting for confirmation */, null /*no correlation key*/); Console.WriteLine("Endpoint queue successfully provisioned on the appliance"); } catch (Exception ex) { PrintException(ex); Console.WriteLine("Exiting"); return; } #endregion #region Publishing some messages to this newly provisioned queue IMessage msg = ContextFactory.Instance.CreateMessage(); msg.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT); msg.DeliveryMode = MessageDeliveryMode.Persistent; msg.Destination = queue; int howManyToPublish = 10; Console.WriteLine(String.Format("About to publish {0} messages", howManyToPublish)); for (int i = 0; i < howManyToPublish; i++) { if (session.Send(msg) == ReturnCode.SOLCLIENT_OK) { Console.Write("."); } Thread.Sleep(100); // wait for 0.5 seconds } Console.WriteLine("\nDone"); #endregion #region Create a Browser to the newly provisioned Queue, and selectively remove the spooled messages. BrowserProperties browserProps = new BrowserProperties(); browser = session.CreateBrowser(queue, browserProps); Console.WriteLine(string.Format("Browsing queue {0} ", queueName)); int count = 0, removedCount = 0; while ((msg = browser.GetNext()) != null) { Console.WriteLine(msg.Dump()); count++; if (count % 3 == 0) { // A message may be removed by calling IBrowser.remove(). // This deletes it from the appliance's message spool. Console.WriteLine("Removing spooled message ({0}).", count); browser.Remove(msg); removedCount++; } } Console.WriteLine(string.Format("Browsed {0} messages, removed {1} ", count, removedCount)); #endregion } catch (Exception ex) { PrintException(ex); Console.WriteLine("Exiting"); } finally { if (browser != null) { browser.Dispose(); } if (session != null) { session.Deprovision(queue, ProvisionFlag.WaitForConfirm, null); session.Dispose(); } if (context != null) { context.Dispose(); } // Must cleanup after. CleanupContext(); } }
private void SendMessage(ISession session) { // Provision the queue string queueName = "Q/tutorial"; Console.WriteLine("Attempting to provision the queue '{0}'...", queueName); List <MsgInfo> msgList = new List <MsgInfo>(); // Create the queue using (IQueue queue = ContextFactory.Instance.CreateQueue(queueName)) { // Set queue permissions to "consume" and access-type to "exclusive" EndpointProperties endpointProps = new EndpointProperties() { Permission = EndpointProperties.EndpointPermission.Consume, AccessType = EndpointProperties.EndpointAccessType.Exclusive }; // Provision it, and do not fail if it already exists session.Provision(queue, endpointProps, ProvisionFlag.IgnoreErrorIfEndpointAlreadyExists & ProvisionFlag.WaitForConfirm, null); Console.WriteLine("Queue '{0}' has been created and provisioned.", queueName); // Create the message using (IMessage message = ContextFactory.Instance.CreateMessage()) { // Message's destination is the queue and the message is persistent message.Destination = queue; message.DeliveryMode = MessageDeliveryMode.Persistent; // Send it to the mapped topic a few times with different content for (int i = 0; i < TotalMessages; i++) { // Create the message content as a binary attachment message.BinaryAttachment = Encoding.ASCII.GetBytes( string.Format("Confirmed Publish Tutorial! Message ID: {0}", i)); // Create a message correlation object MsgInfo msgInfo = new MsgInfo(message, i); message.CorrelationKey = msgInfo; msgList.Add(msgInfo); // Send the message to the queue on the Solace messaging router Console.WriteLine("Sending message to queue {0}...", queueName); ReturnCode returnCode = session.Send(message); if (returnCode != ReturnCode.SOLCLIENT_OK) { Console.WriteLine("Sending failed, return code: {0}", returnCode); } } } } Console.WriteLine("{0} messages sent. Processing replies.", TotalMessages); // block the current thread until a confirmation received CountdownEvent.Wait(); foreach (MsgInfo msgInfo in msgList) { if (msgInfo.Accepted) { Console.WriteLine("Message {0} was accepted by the router.", msgInfo.Id); } if (msgInfo.Acked) { Console.WriteLine("Message {0} was acknowledged by the router.", msgInfo.Id); } } }
private void SubscribeAndSendMessage(ISession session) { // Provision the queue string queueName = "Q/tutorial/topicToQueueMapping"; Console.WriteLine("Attempting to provision the queue '{0}'...", queueName); // Create the queue using (IQueue queue = ContextFactory.Instance.CreateQueue(queueName)) { // Set queue permissions to "consume" and access-type to "exclusive" EndpointProperties endpointProps = new EndpointProperties() { Permission = EndpointProperties.EndpointPermission.Consume, AccessType = EndpointProperties.EndpointAccessType.Exclusive, }; // Provision it, and do not fail if it already exists session.Provision(queue, endpointProps, ProvisionFlag.IgnoreErrorIfEndpointAlreadyExists | ProvisionFlag.WaitForConfirm, null); Console.WriteLine("Queue '{0}' has been created and provisioned.", queueName); // Add subscription to the topic mapped to the queue ITopic tutorialTopic = ContextFactory.Instance.CreateTopic("T/mapped/topic/sample"); session.Subscribe(queue, tutorialTopic, SubscribeFlag.WaitForConfirm, null); // Create the message using (IMessage message = ContextFactory.Instance.CreateMessage()) { // Message's destination is the queue topic and the message is persistent message.Destination = tutorialTopic; message.DeliveryMode = MessageDeliveryMode.Persistent; // Send it to the mapped topic a few times with different content for (int i = 0; i < TotalMessages; i++) { // Create the message content as a binary attachment message.BinaryAttachment = Encoding.ASCII.GetBytes( string.Format("Topic to Queue Mapping Tutorial! Message ID: {0}", i)); // Send the message to the queue on the Solace messaging router Console.WriteLine("Sending message ID {0} to topic '{1}' mapped to queue '{2}'...", i, tutorialTopic.Name, queueName); ReturnCode returnCode = session.Send(message); if (returnCode == ReturnCode.SOLCLIENT_OK) { Console.WriteLine("Done."); } else { Console.WriteLine("Sending failed, return code: {0}", returnCode); } } } Console.WriteLine("{0} messages sent. Processing replies.", TotalMessages); // Create and start flow to the newly provisioned queue // NOTICE HandleMessageEvent as the message event handler // and HandleFlowEvent as the flow event handler Flow = session.CreateFlow(new FlowProperties() { AckMode = MessageAckMode.ClientAck }, queue, null, HandleMessageEvent, HandleFlowEvent); Flow.Start(); // block the current thread until a confirmation received CountdownEvent.Wait(); } }
/// <summary> /// Main function in the sample. /// </summary> /// <param name="args"></param> public override void SampleCall(string[] args) { #region Parse Arguments ArgParser cmdLineParser = new ArgParser(); if (!cmdLineParser.Parse(args)) { // parse failed PrintUsage(INVALID_ARGUMENTS_ERROR); return; } if (!SampleParseArgs(cmdLineParser)) { // parse failed for sample's arguments PrintUsage(INVALID_ARGUMENTS_ERROR); return; } #endregion #region Initialize properties from command line // Initialize the properties. ContextProperties contextProps = new ContextProperties(); SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config); #endregion // Define IContext and ISession. IContext context = null; ISession session = null; IQueue queue = null; try { InitContext(cmdLineParser.LogLevel); Console.WriteLine("About to create the Context ..."); context = ContextFactory.Instance.CreateContext(contextProps, null); Console.WriteLine("Context successfully created. "); Console.WriteLine("About to create the Session ..."); session = context.CreateSession(sessionProps, SampleUtils.HandleMessageEvent, SampleUtils.HandleSessionEvent); Console.WriteLine("Session successfully created."); Console.WriteLine("About to connect the Session ..."); if (session.Connect() == ReturnCode.SOLCLIENT_OK) { Console.WriteLine("Session successfully connected"); Console.WriteLine(GetRouterInfo(session)); } if (!session.IsCapable(CapabilityType.SUB_FLOW_GUARANTEED) || !(session.IsCapable(CapabilityType.TEMP_ENDPOINT))) { Console.WriteLine(string.Format("Capabilities '{0}' and '{1}' are required to run this sample", CapabilityType.SUB_FLOW_GUARANTEED, CapabilityType.TEMP_ENDPOINT)); return; } #region Provision an exclusive queue EndpointProperties endpointProps = new EndpointProperties(); // Set permissions to allow all permissions to others. endpointProps.Permission = EndpointProperties.EndpointPermission.Delete; // Set access type to exclusive. endpointProps.AccessType = EndpointProperties.EndpointAccessType.Exclusive; // Set quota to 100 MB. endpointProps.Quota = 100; string queueName = "solclient_dotnet_sample_ActiveFlowIndication_" + (new Random()).Next(1000); queue = ContextFactory.Instance.CreateQueue(queueName); Console.WriteLine(String.Format("About to provision queue '{0}' on the appliance", queueName)); try { session.Provision(queue /* endpoint */, endpointProps /*endpoint properties */, ProvisionFlag.WaitForConfirm /* block waiting for confirmation */, null /*no correlation key*/); Console.WriteLine("Endpoint queue successfully provisioned on the appliance"); } catch (Exception ex) { PrintException(ex); Console.WriteLine("Exiting"); return; } #endregion FlowProperties flowProps = new FlowProperties(); // The Flow is created in a started state, so it is ready to receive messages. flowProps.FlowStartState = true; // AutoAck means that the received messages on the Flow // will be implicitly acked on return from the message event handler // specified in CreateFlow(). flowProps.AckMode = MessageAckMode.AutoAck; //Activate the active flow indication events flowProps.ActiveFlowInd = true; EventWaitHandle waitForFlowActiveEvent = new AutoResetEvent(false); flow1 = session.CreateFlow(flowProps, queue, null, SampleUtils.HandleMessageEvent, new EventHandler <FlowEventArgs>( delegate(object source, FlowEventArgs evt) { switch (evt.Event) { case FlowEvent.FlowActive: Console.Out.WriteLine("Flow 1 Active event received"); waitForFlowActiveEvent.Set(); break; } })); if (waitForFlowActiveEvent.WaitOne(5000, false)) { waitForFlowActiveEvent.Reset(); } else { // We did not get a FlowEvent.UpNotice within five seconds. Console.Out.WriteLine("Did not get a FlowEvent.FlowActive for flow 1 within 5 secs, exiting ..."); return; } flow2 = session.CreateFlow(flowProps, queue, null, SampleUtils.HandleMessageEvent, new EventHandler <FlowEventArgs>( delegate(object source, FlowEventArgs evt) { switch (evt.Event) { case FlowEvent.FlowInactive: Console.Out.WriteLine("Flow 2 Inactive event received"); break; case FlowEvent.FlowActive: Console.Out.WriteLine("Flow 2 Active event received"); waitForFlowActiveEvent.Set(); break; } })); Console.WriteLine("Flow 2 started."); Console.WriteLine("Stopping flow 1."); if (flow1.Stop() == ReturnCode.SOLCLIENT_OK) { Console.WriteLine("Flow 1 stopped."); } else { Console.WriteLine("Failure while stopping flow 1. Exiting ..."); return; } Console.WriteLine("Disposing of flow 1"); flow1.Dispose(); flow1 = null; Console.WriteLine("Flow 1 has been disposed"); if (waitForFlowActiveEvent.WaitOne(5000, false)) { waitForFlowActiveEvent.Reset(); } else { // We did not get a FlowEvent.UpNotice within five seconds. Console.Out.WriteLine("Did not get a FlowEvent.FlowActive for flow 2 within 5 secs, exiting ..."); return; } Console.WriteLine(string.Format("\nDone\n Sleeping for {0} secs before exiting ", Timeout / 1000)); Thread.Sleep(Timeout); } catch (Exception ex) { PrintException(ex); } finally { if (flow1 != null) { flow1.Dispose(); } if (flow2 != null) { flow2.Dispose(); } if (queue != null) { if (session != null) { session.Deprovision(queue, ProvisionFlag.WaitForConfirm, null); } queue.Dispose(); } if (session != null) { session.Dispose(); } if (context != null) { context.Dispose(); } // Must cleanup after. CleanupContext(); } }