Exemple #1
0
        /// <summary>
        /// A Message receive callback delegate that prints the SDT content
        /// of received messages.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        public void PrintReceivedMessage(Object source, MessageEventArgs args)
        {
            IMessage      message   = args.Message;
            ISDTContainer container = SDTUtils.GetContainer(message);
            StringBuilder sb        = new StringBuilder();

            if (container is IMapContainer)
            {
                IMapContainer map = (IMapContainer)container;
                sb.Append("map={");
                while (map.HasNext())
                {
                    KeyValuePair <string, ISDTField> entry = map.GetNext();
                    sb.Append(string.Format("\n\tkey={0} value={1}", entry.Key, entry.Value.Value.ToString()));
                }
                sb.Append("}\n");
            }
            else if (container is IStreamContainer)
            {
                IStreamContainer stream = (IStreamContainer)container;
                sb.Append("stream={");
                while (stream.HasNext())
                {
                    ISDTField entry = stream.GetNext();
                    sb.Append(string.Format("\n\tvalue={0}", entry.Value.ToString()));
                }
                sb.Append("}\n");
            }
            SampleUtils.HandleMessageEvent(source, args);
            Console.WriteLine(sb.ToString());
        }
        /// <summary>
        /// Triggers the connection of secondary Sessions.
        /// </summary>
        private void triggerSecondaryConnection(ArgParser cmdLineParser)  
        {
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            IContext context = null;
            ISession session = null;
            context = ContextFactory.Instance.CreateContext(contextProps, null);
		    ITopic dummyTopic = ContextFactory.Instance.CreateTopic("dummy/topic");
            session = context.CreateSession(sessionProps,
                SampleUtils.HandleMessageEvent,
                SampleUtils.HandleSessionEvent);
            session.Connect();
            session.Subscribe(dummyTopic,true);
            session.Dispose();
	    }
Exemple #3
0
        /// <summary>
        /// The 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;
            }
            #endregion

            #region Initialize properties from command line
            // Initialize the properties.
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            // Define IContext.
            IContext context = null;
            try
            {
                InitContext(cmdLineParser.LogLevel);
                Console.WriteLine("About to create the context ...");
                context = ContextFactory.Instance.CreateContext(contextProps, null);
                Console.WriteLine("Context successfully created. ");

                // We will create two sessions, and give them different msg receiver callbacks.
                IdPrintingReceiver recvCallback1 = new IdPrintingReceiver("Client 1");
                IdPrintingReceiver recvCallback2 = new IdPrintingReceiver("Client 2");

                Console.WriteLine("About to create the Sessions...");
                session = context.CreateSession(sessionProps,
                                                recvCallback1.HandleMessageEvent,
                                                SampleUtils.HandleSessionEvent);
                session2 = context.CreateSession(sessionProps,
                                                 recvCallback2.HandleMessageEvent,
                                                 SampleUtils.HandleSessionEvent);
                Console.WriteLine("Sessions successfully created.");

                Console.WriteLine("About to connect the Session...");
                if (session.Connect() == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Session 1 successfully connected.");
                    Console.WriteLine(GetRouterInfo(session));
                }

                Console.Write(String.Format("Check for capability: {0}... ", CapabilityType.SUBSCRIPTION_MANAGER));
                if (!session.IsCapable(CapabilityType.SUBSCRIPTION_MANAGER))
                {
                    Console.WriteLine("Not Supported. Exiting.");
                    return;
                }
                else
                {
                    Console.WriteLine("OK");
                }
                // Appliance supports this sample, connect 2nd session.
                if (session2.Connect() == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Session 2 successfully connected");
                }

                // Create the Topic to subscribe and send messages to.
                ITopic serviceTopic = ContextFactory.Instance.CreateTopic(topic_str);

                // Once clients have been connected, their ClientNames can be extracted.
                ContextFactory cf             = ContextFactory.Instance;
                string         strClientName1 = (string)session.GetProperty(SessionProperties.PROPERTY.ClientName);
                string         strClientName2 = (string)session2.GetProperty(SessionProperties.PROPERTY.ClientName);
                IClientName    clientName1    = cf.CreateClientName(strClientName1);
                IClientName    clientName2    = cf.CreateClientName(strClientName2);

                Console.WriteLine("Client '{0}' adding subscription on behalf of client '{1}'", clientName1, clientName2);
                session.Subscribe(clientName2, serviceTopic, SubscribeFlag.RequestConfirm | SubscribeFlag.WaitForConfirm, null);
                Console.WriteLine("OK. Added subscription '{0}'.", serviceTopic);
                IMessage messageOne = SampleUtils.CreateMessage(cmdLineParser.Config, session);
                messageOne.Destination = serviceTopic;

                Console.WriteLine("Sending a message from Client 1...");
                session.Send(messageOne);
                Console.WriteLine("Sent.");
                Thread.Sleep(500);
                Console.WriteLine("Done.");
            } catch (Exception ex) {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
                if (session2 != null)
                {
                    session2.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
        /// <summary>
        /// The 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;
            }
            #endregion

            #region Initialize properties from command line
            // Initialize the properties
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            // Define context and session
            IContext context = null;
            ISession session = null;
            try
            {
                InitContext(cmdLineParser.LogLevel);
                Console.WriteLine("About to connect to appliance. \n[Ensure selected message-vpn has 'Publish Client Event Messages' enabled ]");
                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,
                    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));
                }

                // Build an event monitoring topic for client connect events and
                // subscribe to it.
                string routerHostname = (string) session.GetCapability(CapabilityType.PEER_ROUTER_NAME).Value.Value;
                string strEventTopic = string.Format("#LOG/INFO/CLIENT/{0}/CLIENT_CLIENT_CONNECT/>", routerHostname);
                ITopic eventTopic = ContextFactory.Instance.CreateTopic(strEventTopic);
                Console.WriteLine(string.Format("Adding subscription to '{0}'...", strEventTopic));
                try 
                {
                    if (session.Subscribe(eventTopic, true) == ReturnCode.SOLCLIENT_OK) 
                    {
                        Console.WriteLine("Successfully added event topic subscription");
                    }
                } 
                catch (OperationErrorException opex) 
                {
                    Console.WriteLine(string.Format("Failed to add susbscription to to event topic"));
                    PrintException(opex);
                }
                Console.WriteLine("Waiting to receive events ...");
                triggerSecondaryConnection(cmdLineParser);
                /* sleep to allow reception of event */
                Thread.Sleep(1000);
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after. 
                CleanupContext();
            }
        }
        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();
            }
        }
        /// <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.ParseCacheSampleArgs(args))
            {
                Console.WriteLine("Exception: " + INVALID_ARGUMENTS_ERROR);
                Console.Write(ArgParser.CacheArgUsage);
                return;
            }
            if (!SampleParseArgs(cmdLineParser))
            {
                // Parse failed for sample's arguments.
                Console.WriteLine("Exception: " + INVALID_ARGUMENTS_ERROR);
                Console.Write(ArgParser.CacheArgUsage);
                return;
            }
            #endregion

            #region Initialize properties from command line
            // Initialize the properties.
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            // Context and session.
            IContext context = null;
            ISession session = 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.SUPPORTS_XPE_SUBSCRIPTIONS))
                {
                    Console.WriteLine("This sample requires a SolOS-TR version of the appliance, aborting");
                    return;
                }
                #region PUBLISH A MESSAGE (just to make sure there is one cached)
                ITopic topic = null;
                topic = ContextFactory.Instance.CreateTopic(SampleUtils.SAMPLE_TOPIC);
                IMessage message = ContextFactory.Instance.CreateMessage();
                message.Destination = topic;
                if (cmdLineParser.Config.startSequenceId != null && cmdLineParser.Config.endSequenceId != null)
                {
                    message.DeliveryMode = MessageDeliveryMode.Persistent;
                }
                else
                {
                    message.DeliveryMode = MessageDeliveryMode.Direct;
                }
                message.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT);
                session.Send(message);
                #endregion

                CacheSessionConfiguration cacheConfig  = (CacheSessionConfiguration)cmdLineParser.Config;
                ICacheSession             cacheSession = SampleUtils.newCacheSession(session, cacheConfig);
                ReturnCode rc;
                if (cmdLineParser.Config.startSequenceId != null && cmdLineParser.Config.endSequenceId != null)
                {
                    rc = cacheSession.SendCacheRequest(1, topic, cacheConfig.Subscribe, cacheConfig.Action, HandleCacheRequestResponse,
                                                       cmdLineParser.Config.startSequenceId.Value, cmdLineParser.Config.endSequenceId.Value);
                }
                else
                {
                    rc = cacheSession.SendCacheRequest(1, topic, cacheConfig.Subscribe, cacheConfig.Action, HandleCacheRequestResponse);
                }
                Console.WriteLine("Cache Response: " + rc.ToString());
                Console.WriteLine(string.Format("Waiting for async event or {0} secs (Whichever comes first)...", Timeout / 1000));
                waitForEvent.WaitOne(Timeout, false);
                IDictionary <Stats_Rx, Int64> stats = session.GetRxStats();
                SampleUtils.PrintRxStats(stats);
                Console.WriteLine("\nDone");
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after
                CleanupContext();
            }
        }
        /// <summary>
        /// Main function in the sample.
        /// </summary>
        /// <param name="args"></param>
        public override void SampleCall(string[] args)
        {
            #region Parse Arguments
            string    routerName    = null;
            bool      verbose       = true;
            ArgParser cmdLineParser = new ArgParser();
            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            if (cmdLineParser.Config.ArgBag.ContainsKey("-vo"))
            {
                verbose = false;
            }
            if (cmdLineParser.Config.ArgBag.ContainsKey("-sv"))
            {
                SOLTR_VERSION = cmdLineParser.Config.ArgBag["-sv"];
            }
            #endregion

            #region Initialize properties from command line.
            // Initialize the properties
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            // Define Context and Session.
            IContext context = null;
            ISession session = null;
            try
            {
                InitContext(cmdLineParser.LogLevel);
                Console.WriteLine("About to connect to appliance. \n[Ensure selected message-vpn is configured as the appliance's management message-vpn.]");
                Console.WriteLine("[Ensure selected message-vpn has semp-over-msgbus enabled]");
                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));
                }

                // The SEMP requestStr topic is built using the appliance name.
                //
                // The SEMP requestStr we perform asks to show the client's on the appliance.
                // It can be easily adapted to perform any other type
                // of SEMP show commands.
                ICapability cap_routerName = session.GetCapability(CapabilityType.PEER_ROUTER_NAME);
                if (cap_routerName.Value == null || cap_routerName.Value.Value.Equals(""))
                {
                    Console.WriteLine("Unable to load PEER_ROUTER_NAME. (Requires r4.6+ SolOS-TR appliance.)");
                    return;
                }
                // PEER_ROUTER_NAME is an ISDTField of type string.
                routerName = (string)cap_routerName.Value.Value;

                string SEMP_TOPIC_STRING = string.Format("#SEMP/{0}/SHOW", routerName);
                Console.WriteLine(string.Format("Loaded appliance name: '{0}', SEMP Topic: '{1}'", routerName, SEMP_TOPIC_STRING));
                ITopic SEMP_TOPIC            = ContextFactory.Instance.CreateTopic(SEMP_TOPIC_STRING);
                string SEMP_SHOW_CLIENT_NAME = "<rpc semp-version=\"soltr/" + SOLTR_VERSION +
                                               "\"><show><client><name>*</name></client></show></rpc>";

                // Make the request.
                IMessage requestMsg = ContextFactory.Instance.CreateMessage();
                requestMsg.Destination      = SEMP_TOPIC;
                requestMsg.BinaryAttachment = Encoding.UTF8.GetBytes(SEMP_SHOW_CLIENT_NAME);
                if (verbose)
                {
                    Console.WriteLine("REQUEST: " + SEMP_SHOW_CLIENT_NAME); // triggered by -v
                }
                // Make the requestStr.
                IMessage   replyMsg;
                ReturnCode rc = session.SendRequest(requestMsg, out replyMsg, 5000);
                if (rc == ReturnCode.SOLCLIENT_FAIL)
                {
                    Console.WriteLine("Failed to send a requestStr");
                    return;
                }
                byte[] binaryAttachment = null;
                if (replyMsg != null)
                {
                    binaryAttachment = replyMsg.BinaryAttachment;
                }
                else
                {
                    Console.WriteLine("Failed to receive a SEMP reply");
                    return;
                }
                if (binaryAttachment != null)
                {
                    string replyStr = Encoding.UTF8.GetString(binaryAttachment);
                    // Is this user allowed to make such SEMP requestStr?
                    if (replyStr.IndexOf("permission-error") != -1)
                    {
                        Console.WriteLine("Permission error, aborting");
                        Console.WriteLine("Make sure SEMP over message bus SHOW commands are enabled for this VPN");
                        Console.WriteLine("REPLY: " + replyStr);
                        return;
                    }
                    if (verbose)
                    {
                        Console.WriteLine("REPLY: " + replyStr); // triggered by -v
                    }
                }
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
Exemple #8
0
        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);
            // Uncomment the line below if you wish to send using a non-blocking mode
            // sessionProps.SendBlocking = false;
            #endregion

            // Define IContext and ISession.
            IContext context = null;
            ISession session = null;

            // Create the LinkedList.
            LinkedList <MessageRecord> msgRecords =
                new LinkedList <MessageRecord>();

            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,
                                                HandleSessionEvent);
                Console.WriteLine("Session successfully created.");

                // Connect the session.
                Console.WriteLine("About to connect the session ...");
                if (session.Connect() == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Session successfully connected");
                    Console.WriteLine(GetRouterInfo(session));
                }

                // Validate required capabilities.
                if (!session.IsCapable(CapabilityType.PUB_GUARANTEED))
                {
                    Console.WriteLine(string.Format("This sample requires capability '{0}' to be supported", CapabilityType.PUB_GUARANTEED));
                    return;
                }

                // Send cmdLineParser.Config.NumberOfMessagesToPublish messages.
                for (int i = 0; i < cmdLineParser.Config.NumberOfMessagesToPublish; i++)
                {
                    // Allocate a new message.
                    IMessage message = SampleUtils.CreateMessage(cmdLineParser.Config, session);
                    message.DeliveryMode = MessageDeliveryMode.Persistent;
                    try
                    {
                        // Create a record, and set it as CorrelationKey.
                        MessageRecord msgRecord = new MessageRecord(message);
                        message.CorrelationKey = msgRecord;
                        ReturnCode rc = session.Send(message);
                        Console.WriteLine("Sending message " + i + ": " + rc);
                        if (rc == ReturnCode.SOLCLIENT_OK)
                        {
                            // Add it to the list of send message records and send it.
                            msgRecord.MessageId = i;
                            msgRecords.AddLast(msgRecord);
                        }
                        else
                        {
                            // The message was not sent, free it up
                            message.Dispose();
                        }
                    }
                    catch (OperationErrorException opex)
                    {
                        // Ignore OperationErrorException if you don't want the publisher
                        // to abort on transient send errors
                        Console.WriteLine("Got an excpetion " + opex.ReturnCode);
                        message.Dispose();
                        continue;
                    }
                    // Sleep for 500 msecs and check to see if the message was acknowledged (positively or negatively).
                    Thread.Sleep(100);
                    while (msgRecords.First != null && msgRecords.First.Value.Acked)
                    {
                        MessageRecord record = msgRecords.First.Value;
                        msgRecords.RemoveFirst();
                        Console.WriteLine(
                            string.Format("Freeing memory for message {0}, Result: Acked ({1}), Accepted ({2})\n",
                                          record.MessageId, record.Acked, record.Accepted));
                        record.Message.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                Thread.Sleep(3000);
                // There should not be any left in the list, but just in case.
                foreach (MessageRecord record in msgRecords)
                {
                    Console.WriteLine(
                        string.Format("Freeing memory for message {0}, Result: Acked ({1}), Accepted ({2})\n",
                                      record.MessageId, record.Acked, record.Accepted));
                    record.Message.Dispose();
                }
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
Exemple #9
0
        /// <summary>
        /// The 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;
            }
            #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 and ITopic.
            IContext context = null;
            ISession session = null;
            ITopic   topic   = 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,
                                                PrintReceivedMessage,
                                                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));
                }

                topic = ContextFactory.Instance.CreateTopic(SampleUtils.SAMPLE_TOPIC);

                Console.WriteLine("About to subscribe to topic " + SampleUtils.SAMPLE_TOPIC);
                if (session.Subscribe(topic, true) == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Successfully added topic subscription");
                }

                // Create the message independent stream.
                IStreamContainer stream = SDTUtils.CreateStream(1024);

                // Populate the stream.
                stream.AddDouble(3.141592654);
                stream.AddString("message");

                // Create the message-independent map.
                IMapContainer map = SDTUtils.CreateMap(1024);

                // Add a well known integer to the map.
                map.AddInt32("mersenne", 43112609);

                // Create the message.
                IMessage message = ContextFactory.Instance.CreateMessage();

                // Set the message delivery options.
                message.DeliveryMode = MessageDeliveryMode.Direct;
                message.Destination  = topic;

                int numMsgsToSend = 10;
                Console.WriteLine(string.Format("About to send {0} messages ...", numMsgsToSend));
                for (int i = 0; i < numMsgsToSend; i++)
                {
                    // Overwrite the "message" field, set the container, and send.
                    map.DeleteField("message");
                    map.AddString("message", "message" + (i + 1));
                    // Set the user property map to the map.
                    message.UserPropertyMap = map;
                    SDTUtils.SetSDTContainer(message, stream);
                    session.Send(message);
                }

                // Dispose of the map, stream, and message.
                map.Dispose();
                stream.Dispose();
                message.Dispose();

                Thread.Sleep(500); // wait for 0.5 seconds
                Console.WriteLine("\nDone");
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    if (topic != null)
                    {
                        session.Unsubscribe(topic, true);
                    }
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
        public override void SampleCall(string[] args)
        {
            // Resources used in this sample.
            IContext context = null;
            ISession session = null;
            IQueue   queue   = null;
            IQueue   dmq     = null; // the DMQ

            // Parse arguments and initialize Session properties.
            ArgParser cmdLineParser = new ArgParser();

            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);

            try
            {
                InitContext(cmdLineParser.LogLevel);
                // Initialize the Context, connect the Session, and assert capabilities.
                InitializeAndAssertCapabilities(ref context, ref session, sessionProps);

                // Provision a new Queue and #DEAD_MSG if it does not already exist.
                string queueName = SampleUtils.SAMPLE_QUEUE + (new Random()).Next(1000);
                queue = ProvisionQueue(session, queueName, true);
                dmq   = ProvisionQueue(session, "#DEAD_MSG_QUEUE", false);

                // Publish a couple of messages to the Queue.
                IMessage msg = ContextFactory.Instance.CreateMessage();
                msg.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT);
                msg.DeliveryMode     = MessageDeliveryMode.Persistent;
                msg.Destination      = queue;
                // Send three messages:
                // message one (1):
                // TimeToLive = 2000 (2 secs) and DMQEligible is true
                // In this case, when the message expires, it will be moved to the DMQ
                msg.TimeToLive  = 2000;
                msg.DMQEligible = true;
                msg.UserData    = new byte[] { (byte)1 };
                session.Send(msg);

                // Send three messages:
                // message two (2):
                // TimeToLive = 5000 (5 secs) and DMQEligible is false
                // In this case, when the message expires, it will be deleted from the Queue,
                // but it will not end up on the DMQ.
                msg.TimeToLive  = 5000;
                msg.DMQEligible = false;
                msg.UserData    = new byte[] { (byte)2 };
                session.Send(msg);
                long expiration = msg.Expiration;

                // message three (3):
                // TimeToLive = 0 , DMQEligible is true and Expiration=(within 5 secs of the current time)
                msg.TimeToLive = 0;
                msg.Expiration = expiration;
                msg.UserData   = new byte[] { (byte)3 };
                session.Send(msg);

                // Start a flow to the Queue and verify that all three messages are there.
                DumpMessagesReceivedFromQueue(session, queue, 1000, false);

                // Wait for two seconds.
                Console.WriteLine("\n\nWaiting for 2 secs\n\n");
                Thread.Sleep(2000);

                // Start a flow to queue and verify that message one is no longer there, and
                // messages two and three are still there.
                DumpMessagesReceivedFromQueue(session, queue, 1000, false);

                // Wait for two seconds.
                Console.WriteLine("\n\nWaiting for 2 more secs\n\n");
                Thread.Sleep(2000);

                // Start a flow to the Queue and verify that message two is no longer there,
                // but message 3 is still there.
                DumpMessagesReceivedFromQueue(session, queue, 1000, false);

                // Start a flow to the DMQ and verify that message one (who has DMQEligible=true)
                // is there, but not message two or three.
                DumpMessagesReceivedFromQueue(session, dmq, 1000, true);

                Console.WriteLine("\nDone");
            }
            catch (Exception ex)
            {
                PrintException(ex);
                Console.WriteLine("Exiting");
            }
            finally
            {
                if (session != null)
                {
                    session.Deprovision(queue, ProvisionFlag.WaitForConfirm, null);
                    session.Deprovision(dmq, ProvisionFlag.WaitForConfirm, null);
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after
                CleanupContext();
            }
        }
Exemple #11
0
        public override void SampleCall(string[] args)
        {
            // Resources used in this sample.
            IContext context = null;
            ISession session = null;
            IQueue   queue   = null;
            ITopic   topicA  = ContextFactory.Instance.CreateTopic("topicA");
            ITopic   topicB  = ContextFactory.Instance.CreateTopic("topicB");

            // Parse arguments and initialize Session properties.
            ArgParser cmdLineParser = new ArgParser();

            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);

            try
            {
                InitContext(cmdLineParser.LogLevel);
                // Initialize the Context, connect the Session, and assert capabilities
                InitializeAndAssertCapabilities(ref context, ref session, sessionProps);

                // Provision a new Queue.
                string queueName = SampleUtils.SAMPLE_QUEUE + (new Random()).Next(1000);
                queue = ProvisionQueue(session, queueName, true);

                // Publish a couple of messages to topicA, topicB. Observe that none of them end up on the Queue.
                IMessage msg = ContextFactory.Instance.CreateMessage();
                msg.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT);
                msg.DeliveryMode     = MessageDeliveryMode.Persistent;
                msg.UserData         = new byte[] { 1 };
                msg.Destination      = topicA;
                session.Send(msg);
                msg.UserData    = new byte[] { 2 };
                msg.Destination = topicB;
                session.Send(msg);
                DumpMessagesReceivedFromQueue(session, queue, 1000, true);

                // Add Topic subscriptions for topicA and topicB, resend the two messages. Observe that both of them end up on the Queue.
                session.Subscribe(queue, topicA, SubscribeFlag.WaitForConfirm, null);
                session.Subscribe(queue, topicB, SubscribeFlag.WaitForConfirm, null);
                msg.UserData    = new byte[] { 1 };
                msg.Destination = topicA;
                session.Send(msg);
                msg.UserData    = new byte[] { 2 };
                msg.Destination = topicB;
                session.Send(msg);
                DumpMessagesReceivedFromQueue(session, queue, 1000, true);

                // Remove TopicA subscription and resend the two messages. Observe that only TopicB message end up on the Queue.
                session.Unsubscribe(queue, topicA, SubscribeFlag.WaitForConfirm, null);
                msg.UserData    = new byte[] { 1 };
                msg.Destination = topicA;
                session.Send(msg);
                msg.UserData    = new byte[] { 2 };
                msg.Destination = topicB;
                session.Send(msg);
                DumpMessagesReceivedFromQueue(session, queue, 1000, true);

                Console.WriteLine("\nDone");
            }
            catch (Exception ex)
            {
                PrintException(ex);
                Console.WriteLine("Exiting");
            }
            finally
            {
                if (session != null)
                {
                    session.Deprovision(queue, ProvisionFlag.WaitForConfirm, null);
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
        /// <summary>
        /// The main function in the sample.
        /// </summary>
        /// <param name="args"></param>
        public override void SampleCall(string[] args)
        {
            #region Parse Arguments
            string    routerHostname = null;
            bool      verbose        = false;
            ArgParser cmdLineParser  = new ArgParser();
            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            if (cmdLineParser.Config.ArgBag.ContainsKey("-v"))
            {
                verbose = true;
            }
            if (cmdLineParser.Config.ArgBag.ContainsKey("-sv"))
            {
                SOLTR_VERSION = cmdLineParser.Config.ArgBag["-sv"];
            }
            #endregion

            #region Initialize properties from command line
            // Initialize the properties.
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            // Define Context and Session.
            IContext context = null;
            ISession session = null;
            try
            {
                InitContext(cmdLineParser.LogLevel);
                Console.WriteLine("About to connect to appliance. \n[Ensure selected message-vpn is configured as the appliance's management message-vpn.]");
                Console.WriteLine("[Ensure selected message-vpn has semp-over-msgbus enabled]");
                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));
                }

                // The SEMP requestStr Topic is built using the appliance's host name.
                //
                // The SEMP requestStr we perform asks to show all Queues, and return five
                // results at a time. It can be easily adapted to perform any other type
                // of SEMP show commands.

                ICapability cap_routerName = session.GetCapability(CapabilityType.PEER_ROUTER_NAME);
                if (cap_routerName.Value == null || cap_routerName.Value.Value.Equals(""))
                {
                    Console.WriteLine("Unable to load PEER_ROUTER_NAME. (Requires r4.6+ SolOS-TR appliance.)");
                    return;
                }
                // PEER_ROUTER_NAME is an ISDTField of type string.
                routerHostname = (string)cap_routerName.Value.Value;

                string SEMP_TOPIC_STRING = string.Format("#SEMP/{0}/SHOW", routerHostname);
                Console.WriteLine(string.Format("Loaded appliance hostname: '{0}', SEMP Topic: '{1}'", routerHostname, SEMP_TOPIC_STRING));
                ITopic SEMP_TOPIC       = ContextFactory.Instance.CreateTopic(SEMP_TOPIC_STRING);
                string SEMP_SHOW_QUEUES = "<rpc semp-version=\"soltr/" + SOLTR_VERSION +
                                          "\"><show><queue><name>*</name><count/><num-elements>" +
                                          NUM_OF_ELEMENTS_PER_REQUEST + "</num-elements></queue></show></rpc>";
                string MORECOOKIE_START = "<more-cookie>";
                string MORECOOKIE_END   = "</more-cookie>";

                // Perform requests in a loop. Each new requestStr uses the
                // more-cookie from the previous response.
                //
                string next_request = SEMP_SHOW_QUEUES;
                while (next_request != null)
                {
                    // Create the requestStr message.
                    IMessage requestMsg = ContextFactory.Instance.CreateMessage();
                    requestMsg.Destination      = SEMP_TOPIC;
                    requestMsg.BinaryAttachment = Encoding.UTF8.GetBytes(next_request);
                    if (verbose)
                    {
                        Console.WriteLine("REQUEST: " + next_request); // triggered by -v
                    }
                    // Make the requestStr.
                    IMessage   replyMsg;
                    ReturnCode rc = session.SendRequest(requestMsg, out replyMsg, 5000);
                    if (rc == ReturnCode.SOLCLIENT_FAIL)
                    {
                        Console.WriteLine("Failed to send a requestStr.");
                        break;
                    }
                    byte[] binaryAttachment = null;
                    if (replyMsg != null)
                    {
                        binaryAttachment = replyMsg.BinaryAttachment;
                    }
                    else
                    {
                        Console.WriteLine("Failed to receive a SEMP reply.");
                        return;
                    }
                    if (binaryAttachment != null)
                    {
                        string replyStr = Encoding.UTF8.GetString(binaryAttachment);
                        // Is this user allowed to make such SEMP requestStr?
                        if (replyStr.IndexOf("permission-error") != -1)
                        {
                            Console.WriteLine("Permission error, aborting");
                            Console.WriteLine("REPLY: " + replyStr);
                            return;
                        }
                        if (verbose)
                        {
                            Console.WriteLine("REPLY: " + replyStr); // triggered by -v
                        }
                        XmlDocument replyDoc = new XmlDocument();
                        replyDoc.LoadXml(replyStr);
                        // Result
                        XmlNode result = replyDoc.SelectSingleNode("//execute-result/@code");
                        Console.WriteLine("Result: " + result.Value);
                        if (!"ok".Equals(result.Value))
                        {
                            Console.WriteLine("Failure occured, aborting");
                            break;
                        }

                        // List queues. Select text nodes under
                        // <queues><queue><name>NAME</name></queue><queues> in the
                        // response.
                        XmlNodeList queues = replyDoc.SelectNodes("//show/queue/queues/queue/name");
                        foreach (XmlNode node in queues)
                        {
                            Console.WriteLine("Queue= " + node.InnerText);
                        }
                        // Check for more data to requestStr with more-cookie.
                        int start_idx = replyStr.IndexOf(MORECOOKIE_START);
                        if (start_idx >= 0)
                        {
                            // More data available.
                            int end_idx = replyStr.IndexOf(MORECOOKIE_END);
                            next_request = replyStr.Substring(start_idx + MORECOOKIE_START.Length, end_idx - (start_idx + MORECOOKIE_START.Length));
                            Console.WriteLine("Found more-cookie...");
                        }
                        else
                        {
                            // Abort the loop; no more data.
                            next_request = null;
                        }
                    }
                    else
                    {
                        // Abort the loop.
                        Console.WriteLine("Reply message did not contain SEMP reply");
                        break;
                    }
                }             // End requestor loop.
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
        /// <summary>
        /// Main sample method
        /// </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;
            }
            cmdLineParser.Config.SetDestMode(DestMode.TOPIC);
            cmdLineParser.Config.DeliveryMode = MessageDeliveryMode.Direct;
            #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;
            IMessage message = null;
            try
            {
                InitContext();
                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));
                }
                message = SampleUtils.CreateMessage(cmdLineParser.Config, session);
                message.DeliveryMode = MessageDeliveryMode.Direct;
                message.Destination  = ContextFactory.Instance.CreateTopic(SampleUtils.SAMPLE_TOPIC);
                session.Send(message);
                Console.WriteLine("\nDone");
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
        public override void SampleCall(string[] args)
        {
            // Parse arguments and initialize Session properties.
            ArgParser cmdLineParser = new ArgParser();

            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            // Create Session properties from the command line options.
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);

            try
            {
                InitContext(cmdLineParser.LogLevel);

                // Create and connect 'sessionA' with No Local delivery set to false.
                sessionProps.NoLocal = false; // No Local is set to 'false' by default.
                InitializeAndAssertCapabilities(ref context, ref sessionA, "sessionA", sessionProps);

                // Create and connect 'sessionB' with No Local delivery set to true.
                sessionProps.NoLocal = true; // <-- this is how we set NoLocal at the session level
                InitializeAndAssertCapabilities(ref context, ref sessionB, "sessionB", sessionProps);

                // Create a Flow to a temporary Queue within sessionA.
                IQueue         queue     = sessionB.CreateTemporaryQueue();
                FlowProperties flowProps = new FlowProperties();
                flowProps.NoLocal      = true; // <-- this is how we set NoLocal at the flow level
                flowProps.BindBlocking = true;
                flowA = sessionA.CreateFlow(flowProps, queue, null, HandleMessageEvent, SampleUtils.HandleFlowEvent);
                flowA.Start();

                // Add a Topic subscription to sessionB.
                ITopic topic = ContextFactory.Instance.CreateTopic(SampleUtils.SAMPLE_TOPIC);
                sessionB.Subscribe(topic, true /*wait for confirm*/);

                // Publish a Direct message to Topic T from each Session; verify it is not delivered locally.
                IMessage msg = ContextFactory.Instance.CreateMessage();
                msg.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT);
                msg.Destination      = topic;
                msg.DeliveryMode     = MessageDeliveryMode.Direct;
                // Send from 'sessionA'.
                Console.WriteLine(string.Format("\nSending a direct message to topic '{0}' from sessionA", topic.ToString()));
                sessionA.Send(msg);
                Thread.Sleep(500);
                PrintCounters();
                Console.WriteLine(string.Format("Expecting msgCounterForSessionB to be 1, it's '{0}'", msgCounterForSessionB));
                Console.WriteLine(string.Format("Expecting msgCounterForSessionA to be 0, it's '{0}'", msgCounterForSessionA));
                ResetCounters();
                // Send from 'sessionB'.
                Console.WriteLine(string.Format("\nSending a direct message to topic '{0}' from sessionB", topic.ToString()));
                sessionB.Send(msg);
                Thread.Sleep(500);
                PrintCounters();
                Console.WriteLine(string.Format("Expecting msgCounterForSessionA to be 0, it's '{0}'", msgCounterForSessionA));
                Console.WriteLine(string.Format("Expecting msgCounterForSessionB to be 0, it's '{0}'", msgCounterForSessionB));
                ResetCounters();


                // Publish a message to the Queue on each Session; verify it is not delivered locally.
                msg.Destination  = queue;
                msg.DeliveryMode = MessageDeliveryMode.Persistent;
                // Send from 'sessionA'.
                Console.WriteLine(string.Format("\nSending a persistent message to queue '{0}' from sessionA", queue.ToString()));
                sessionA.Send(msg);
                Thread.Sleep(500);
                PrintCounters();
                Console.WriteLine(string.Format("Expecting msgCounterForFlowA to be 0, it's '{0}'", msgCounterForFlowA));
                ResetCounters();
                // Send from 'sessionB'.
                Console.WriteLine(string.Format("\nSending a persistent message to queue '{0}' from sessionB", queue.ToString()));
                sessionB.Send(msg);
                Thread.Sleep(500);
                PrintCounters();
                Console.WriteLine(string.Format("Expecting msgCounterForFlowA to be 1, it's '{0}'", msgCounterForFlowA));
                ResetCounters();
                Console.WriteLine("\nDone");
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (flowA != null)
                {
                    flowA.Dispose();
                }
                if (sessionA != null)
                {
                    sessionA.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
        /// <summary>
        /// The 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.ParseCacheSampleArgs(args))
            {
                // Parse failed.
                Console.WriteLine("Exception: " + INVALID_ARGUMENTS_ERROR);
                Console.Write(ArgParser.CacheArgUsage);
                return;
            }
            #endregion

            #region Initialize properties from command line
            // Initialize the properties.
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            // Context and session.
            IContext context = null;
            ISession session = 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));
                }
                #region PUBLISH A MESSAGE (just to make sure there is one cached)

                ITopic topic = null;
                topic = ContextFactory.Instance.CreateTopic(SampleUtils.SAMPLE_TOPIC);
                IMessage message = ContextFactory.Instance.CreateMessage();
                message.Destination      = topic;
                message.DeliveryMode     = MessageDeliveryMode.Direct;
                message.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT);
                session.Send(message);
                #endregion

                CacheSessionConfiguration cacheConfig  = (CacheSessionConfiguration)cmdLineParser.Config;
                ICacheSession             cacheSession = SampleUtils.newCacheSession(session, cacheConfig);
                ReturnCode rc = cacheSession.SendCacheRequest(1, topic, cacheConfig.Subscribe, cacheConfig.Action);
                Console.WriteLine("Cache Response: " + rc.ToString());
                IDictionary <Stats_Rx, Int64> stats = session.GetRxStats();
                SampleUtils.PrintRxStats(stats);
                Console.WriteLine("\nDone");
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
Exemple #16
0
 public void HandleMessageEvent(Object source, MessageEventArgs args)
 {
     Console.WriteLine("Received message on " + _n);
     SampleUtils.HandleMessageEvent(source, args);
 }
        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;

            // Create the LinkedList.
            LinkedList <MessageRecord> msgRecords =
                new LinkedList <MessageRecord>();

            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,
                                                HandleSessionEvent);
                Console.WriteLine("Session successfully created.");

                // Connect the session.
                Console.WriteLine("About to connect the session ...");
                if (session.Connect() == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Session successfully connected");
                    Console.WriteLine(GetRouterInfo(session));
                }
                else
                {
                    Console.WriteLine("Failed to connect session, aborting ...");
                    return;
                }

                // Validate required capabilities.
                if (!session.IsCapable(CapabilityType.PUB_GUARANTEED))
                {
                    Console.WriteLine(string.Format("This sample requires capability '{0}' to be supported", CapabilityType.PUB_GUARANTEED));
                    return;
                }

                // At this point the session is connected and not reconnecting
                sessionIsReconnecting = false;
                sessionIsReconnecting = false;

                // Send cmdLineParser.Config.NumberOfMessagesToPublish messages.
                for (int i = 0; i < cmdLineParser.Config.NumberOfMessagesToPublish; i++)
                {
                    // If the session is reconnecting the applications should not send messages
                    while (sessionIsReconnecting)
                    {
                        Thread.Sleep(100);
                    }

                    if (sessionIsDisconnected)
                    {
                        // No automatic reconnect attemps will be made by the API. It's up to the
                        // client application to reconnect the session
                        Console.WriteLine("About to connect the session ...");
                        if (session.Connect() == ReturnCode.SOLCLIENT_OK)
                        {
                            Console.WriteLine("Session successfully connected");
                        }
                        else
                        {
                            Console.WriteLine("Failed to connect session, aborting ...");
                            return;
                        }
                        // The client application in this case is responsible for re-pulishing all unacked message
                        foreach (MessageRecord record in msgRecords)
                        {
                            if (!record.Acked)
                            {
                                ReturnCode rc = session.Send(record.Message);
                                if (rc != ReturnCode.SOLCLIENT_OK)
                                {
                                    Console.WriteLine("Failed to send unacked messages, aborting ...");
                                    return;
                                }
                            }
                        }
                    }
                    // Allocate a new message.
                    IMessage message = SampleUtils.CreateMessage(cmdLineParser.Config, session);
                    message.DeliveryMode = MessageDeliveryMode.Persistent;
                    // Create a record, and set it as CorrelationKey.
                    MessageRecord msgRecord = new MessageRecord(message);
                    message.CorrelationKey = msgRecord;
                    // Add it to the list of send message records and send it.
                    msgRecords.AddLast(msgRecord);
                    session.Send(message);

                    // Sleep for 500 msecs and check to see if the message was acknowledged (positively or negatively).
                    Thread.Sleep(500);
                    while (msgRecords.First != null && msgRecords.First.Value.Acked)
                    {
                        MessageRecord record = msgRecords.First.Value;
                        msgRecords.RemoveFirst();
                        Console.WriteLine(
                            string.Format("Freeing memory for message {0}, Result: Acked ({1}))\n",
                                          i, record.Acked));
                        record.Message.Dispose();
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                // There should not be any left in the list, but just in case.
                foreach (MessageRecord record in msgRecords)
                {
                    record.Message.Dispose();
                }
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
        public override void SampleCall(string[] args)
        {
            // Resources used in this sample.
            IContext context = null;

            // The different Topics used in this sample.
            ITopic ASlashWildCard = ContextFactory.Instance.CreateTopic("a/>");
            ITopic ASlashB        = ContextFactory.Instance.CreateTopic("a/b");
            ITopic CSlashD        = ContextFactory.Instance.CreateTopic("c/d");
            ITopic CSlashWildCard = ContextFactory.Instance.CreateTopic("c/>");
            ITopic ASlashC        = ContextFactory.Instance.CreateTopic("a/c");
            ITopic CSlashE        = ContextFactory.Instance.CreateTopic("c/e");

            // Parse Arguments and initialize session properties.
            ArgParser cmdLineParser = new ArgParser();

            if (!cmdLineParser.Parse(args))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);

            sessionProps.TopicDispatch = true; // This session property must be set to use topic dispatch capabilities

            try
            {
                InitContext(cmdLineParser.LogLevel);
                // Initialize the Context, connect the Session and assert capabilities.
                InitializeAndAssertCapabilities(ref context, ref this.session, sessionProps);

                // Add "a/>" Topic subscription to the Session.
                session.Subscribe(ASlashWildCard, true /*wait for confirm*/);

                // Create three dispatch targets.
                dispatch_1 = session.CreateDispatchTarget(ASlashB, HandleMessageEvent);
                session.Subscribe(dispatch_1, SubscribeFlag.LocalDispatchOnly, null); // local dispatch only

                dispatch_2 = session.CreateDispatchTarget(CSlashWildCard, HandleMessageEvent);
                session.Subscribe(dispatch_2, SubscribeFlag.WaitForConfirm, null); // subscribe to the appliance

                dispatch_3 = session.CreateDispatchTarget(CSlashD, HandleMessageEvent);
                session.Subscribe(dispatch_3, SubscribeFlag.LocalDispatchOnly, null); // local dispatch only

                // Publish to Topic a/c, and verify receipt only on the Session's message handler.
                IMessage msg = ContextFactory.Instance.CreateMessage();
                msg.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT);
                msg.Destination      = ASlashC;
                session.Send(msg);
                Console.WriteLine("\nPublished message to topic a/c");
                Thread.Sleep(100);

                // Publish to Topic a/b, and verify receipt only on dispatch_1 message handler.
                msg.Destination = ASlashB;
                session.Send(msg);
                Console.WriteLine("\nPublished message to topic a/b");
                Thread.Sleep(100);

                // Publish to Topic c/d, and verify receipt on both dispatch functions 2 and 3.
                msg.Destination = CSlashD;
                session.Send(msg);
                Console.WriteLine("\nPublished message to Topic c/d");
                Thread.Sleep(100);

                // Publish on Topic c/e, and verify receipt on only dispatch function 2.
                msg.Destination = CSlashE;
                session.Send(msg);
                Console.WriteLine("\nPublished message to Topic c/e");
                Thread.Sleep(100);

                // Wait for messages to be delivered.
                Thread.Sleep(Timeout);
                Console.WriteLine("\nDone");
            }
            catch (Exception ex)
            {
                PrintException(ex);
                Console.WriteLine("Exiting");
            }
            finally
            {
                if (session != null)
                {
                    session.Unsubscribe(ContextFactory.Instance.CreateTopic(">"), true /*wait for confirm*/);
                }
                if (dispatch_1 != null)
                {
                    session.Unsubscribe(dispatch_1, SubscribeFlag.LocalDispatchOnly, null);
                }
                if (dispatch_2 != null)
                {
                    session.Unsubscribe(dispatch_2, SubscribeFlag.WaitForConfirm, null);
                }
                if (dispatch_3 != null)
                {
                    session.Unsubscribe(dispatch_3, SubscribeFlag.LocalDispatchOnly, null);
                }
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }