Beispiel #1
0
        private void AddProperties(object logSource, Exception exception, LoggingEvent loggingEvent)
        {
            loggingEvent.Properties["UserName"] = GetUserName();
            try
            {
                ContextProperties contextProperties = _contextService.GetContextProperties();
                if (contextProperties != null)
                {
                    try
                    {
                        loggingEvent.Properties["UserAgent"]  = contextProperties.UserAgent;
                        loggingEvent.Properties["RemoteHost"] = contextProperties.RemoteHost;
                        loggingEvent.Properties["Path"]       = contextProperties.Path;
                        loggingEvent.Properties["Query"]      = contextProperties.Query;
                        loggingEvent.Properties["RefererUrl"] = contextProperties.Referrer;
                        loggingEvent.Properties["RequestId"]  = contextProperties.RequestId;
                        loggingEvent.Properties["SessionId"]  = contextProperties.SessionId;
                    }
                    catch (Exception)
                    {
                    }
                }

                loggingEvent.Properties["ExceptionType"]       = exception == null ? "" : exception.GetType().ToString();
                loggingEvent.Properties["ExceptionMessage"]    = exception == null ? "" : exception.Message;
                loggingEvent.Properties["ExceptionStackTrace"] = exception == null ? "" : exception.StackTrace;
                loggingEvent.Properties["LogSource"]           = logSource.GetType().ToString();
            }
            catch (Exception ex)
            {
                var type   = typeof(Log4NetLoggingService);
                var logger = LogManager.GetLogger(type);
                logger.Logger.Log(type, Level.Fatal, "Exception when extracting properties: " + ex.Message, ex);
            }
        }
Beispiel #2
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;
            }
            #endregion

            #region Initialize Properties
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config);
            #endregion

            InitContext(cmdLineParser.LogLevel);

            using (Requestor requestor = new Requestor(contextProps, sessionProps))
                using (Responder responder = new Responder(contextProps, sessionProps))
                {
                    requestor.SendTo(responder.ReceivingOn);
                    requestor.Commit();

                    Log.Start("Waiting for message");
                    Log.AssertTrue(requestor.WaitForMessage(15000),
                                   "Timeout while waiting for message");
                }
        }
Beispiel #3
0
        protected override void InitializeTarget()
        {
            StackifyLib.Utils.StackifyAPILogger.Log("NLog InitializeTarget");

            _logClient = new LogClient("StackifyLib.net-nlog", apiKey, uri);

#pragma warning disable CS0618 // Type or member is obsolete
            if (logAllProperties == false)
#pragma warning restore CS0618 // Type or member is obsolete
            {
                IncludeEventProperties = false;
            }

            if (logMethodNames == true)
            {
                IncludeCallSite = true;
            }

            if (ContextProperties.Count == 0)
            {
                ContextProperties.Add(new TargetPropertyWithContext()
                {
                    Name = "ndc", Layout = "${ndc:topFrames=1}"
                });

#pragma warning disable CS0618 // Type or member is obsolete
                var globalContextKeyList = globalContextKeys?.Split(',').Select(s => s.Trim()) ?? Enumerable.Empty <string>();

                foreach (var gdcKey in globalContextKeyList)
                {
                    if (string.IsNullOrEmpty(gdcKey))
                    {
                        continue;
                    }
                    ContextProperties.Add(new TargetPropertyWithContext()
                    {
                        Name = gdcKey, Layout = $"${{gdc:item={gdcKey}}}"
                    });
                }

                var mappedContextKeyList = mappedContextKeys?.Split(',').Select(s => s.Trim()) ?? Enumerable.Empty <string>();
                foreach (var mdcKey in mappedContextKeyList)
                {
                    if (string.IsNullOrEmpty(mdcKey))
                    {
                        continue;
                    }
                    ContextProperties.Add(new TargetPropertyWithContext()
                    {
                        Name = mdcKey, Layout = $"${{mdc:item={mdcKey}}}"
                    });
                }

                if (!String.IsNullOrEmpty(callContextKeys))
                {
                    _CallContextKeys = callContextKeys.Split(',').Select(s => s.Trim()).ToList();
                }
#pragma warning restore CS0618 // Type or member is obsolete
            }
        }
Beispiel #4
0
        public static Context CreateFromType(Platform platform, DeviceTypeFlags deviceTypeFlags)
        {
            ContextProperties[] properties = new ContextProperties[3];
            properties[0] = ContextProperties.Platform;
            properties[1] = (ContextProperties)(platform.Handle);
            properties[2] = (ContextProperties)0;

            return(CreateFromType(properties, deviceTypeFlags));
        }
        public void connect2Solace()
        {
            Console.WriteLine("In connect2Solace");
            ContextFactoryProperties cfp = new ContextFactoryProperties();

            // Set log level.
            cfp.SolClientLogLevel = SolLogLevel.Warning;
            // Log errors to console.
            cfp.LogToConsoleError();
            // Must init the API before using any of its artifacts.
            ContextFactory.Instance.Init(cfp);
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = new SessionProperties();

            /******** Delete This ***********/
            sHost     = "54.219.47.90";
            sUserName = "******";
            sPassword = "******";
            sVPNName  = "default";
            /********************************/
            sessionProps.Host     = sHost;
            sessionProps.UserName = sUserName;
            sessionProps.Password = sPassword;
            sessionProps.SSLValidateCertificate = false;
            sessionProps.VPNName = sVPNName;

            //Connection retry logic
            sessionProps.ConnectRetries              = 3;    //-1 means try to connect forever.
            sessionProps.ConnectTimeoutInMsecs       = 5000; //10 seconds
            sessionProps.ReconnectRetries            = 3;    //-1 means try to reconnect forever.
            sessionProps.ReconnectRetriesWaitInMsecs = 5000; //wait for 5 seconds before retry

            // Compression is set as a number from 0-9, where 0 means "disable
            // compression", and 9 means max compression. The default is no
            // compression.
            // Selecting a non-zero compression level auto-selects the
            // compressed SMF port on the appliance, as long as no SMF port is
            // explicitly specified.
            //sessionProps.CompressionLevel = 9;

            #region Create the Context

            context = ContextFactory.Instance.CreateContext(contextProps, null);

            #endregion

            #region Create and connect the Session
            session = context.CreateSession(sessionProps, null, null);
            session.Connect();
            #endregion
        }
        private async Task <ConnectionEvent> ConnectAsyncInternal()
        {
            connectionState = ConnectionState.Opening;

            ConnectionEvent connectionEvent;

            tcsConnection = new TaskCompletionSource <ConnectionEvent>();

            // Create a new context
            var cp = new ContextProperties();

            context = ContextFactory.Instance.CreateContext(cp, null);

            // Ensure the connection & publish is done in a non-blocking fashion
            var sessionProps = solaceOptions.ToSessionProperties();

            sessionProps.ConnectBlocking = false;
            sessionProps.SendBlocking    = false;
            // Required for internal topic dispatching
            sessionProps.TopicDispatch = true;

            // Create the session with the event handlers
            session = context.CreateSession(sessionProps, MessageEventHandler, SessionEventHandler);

            // Connect the session - non-blocking
            var returnCode = session.Connect();

            if (returnCode == ReturnCode.SOLCLIENT_FAIL)
            {
                // Something bad happened before the connection attempt to Solace
                // broker
                var errorInfo = ContextFactory.Instance.GetLastSDKErrorInfo();
                throw new MessagingException(errorInfo.ErrorStr);
            }
            else
            {
                connectionEvent = await tcsConnection.Task.ConfigureAwait(false);

                if (connectionEvent.State == ConnectionState.Opened)
                {
                    var p2pinbox = session.GetProperty(SessionProperties.PROPERTY.P2PInboxInUse) as string;
                    ClientP2PInbox = new Topic(p2pinbox);
                }
            }

            return(connectionEvent);
        }
        public void EnsureNestedPropertiesWork( )
        {
            string key = "some property";

            var outerProperty = new ContextProperties( );

            outerProperty.Add(key, "original");
            Assert.AreSame("original", outerProperty.Find(key), "Check set get");

            ContextProperties innerProperty = outerProperty.CreateChildContext( );

            Assert.AreSame("original", innerProperty.Find(key), "Check set at parent get at child");

            innerProperty.Add(key, "childValue");
            Assert.AreSame("childValue", innerProperty.Find(key), "Check set at child overrides parent");
            Assert.AreNotSame("childValue", outerProperty.Find(key), "Check setting at child does not override parent");
        }
Beispiel #8
0
            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();
            }
Beispiel #9
0
        internal Context( Platform platform, ContextProperties[] properties, Device[] devices )
        {
            IntPtr[] intPtrProperties;
            IntPtr[] deviceIDs;
            ErrorCode result;

            Platform = platform;
            deviceIDs = InteropTools.ConvertDevicesToDeviceIDs( devices );

            intPtrProperties = new IntPtr[properties.Length];
            for( int i=0; i<properties.Length; i++ )
                intPtrProperties[i] = new IntPtr( (long)properties[i] );

            ContextID = (IntPtr)OpenCL.CreateContext( intPtrProperties,
                (uint)devices.Length,
                deviceIDs,
                null,
                IntPtr.Zero,
                out result );
            if( result!=ErrorCode.SUCCESS )
                throw new OpenCLException( "CreateContext failed: "+result , result);
            Is64BitContext = ContainsA64BitDevice();
        }
        /// <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;
            ITopicEndpoint topicEndpoint = 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;
                }
                ITopic topic = null;
                if (cmdLineParser.Config.UseDurableEndpoint)
                {
                    Console.WriteLine(string.Format("A durable topic endpoint with name '{0}' must be provisioned and accessible on the appliance in the same user's Message VPN.)", SampleUtils.SAMPLE_TOPICENDPOINT));
                    topicEndpoint = ContextFactory.Instance.CreateDurableTopicEndpointEx(SampleUtils.SAMPLE_TOPICENDPOINT);
                    topic         = ContextFactory.Instance.CreateTopic(SampleUtils.SAMPLE_TOPIC);
                }
                else
                {
                    Console.WriteLine("Creating a temporary Topic");
                    topic         = session.CreateTemporaryTopic();
                    topicEndpoint = session.CreateNonDurableTopicEndpoint();
                }
                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;
                // NON-BLOCKING FLOW CREATE: make sure that the flowProps.BindBlocking is set to false;
                flowProps.BindBlocking = false;

                // NON-BLOCKING FLOW CREATE: to demonstrate waiting on flow up event
                EventWaitHandle waitForFlowUpEvent = new AutoResetEvent(false);

                flow = session.CreateFlow(flowProps, topicEndpoint, topic,
                                          SampleUtils.HandleMessageEvent,
                                          new EventHandler <FlowEventArgs>(
                                              delegate(object source, FlowEventArgs evt)
                {
                    if (evt.Event == FlowEvent.UpNotice)
                    {
                        waitForFlowUpEvent.Set();
                    }
                }));

                if (waitForFlowUpEvent.WaitOne(5000, false))
                {
                    // We got a FlowEvent.UpNotice.
                    Console.Out.WriteLine("Flow created, we can proceed now");
                }
                else
                {
                    // We did not get a FlowEvent.UpNotice within five seconds.
                    Console.Out.WriteLine("Did not get a FlowEvent.UpNotice within 5 secs, exiting ...");
                    return;
                }
                // Send a number of messages to the Topic.
                IMessage message = SampleUtils.CreateMessage(cmdLineParser.Config, session);
                message.Destination = topic;
                Console.WriteLine(string.Format("About to send {0} messages ...", cmdLineParser.Config.NumberOfMessagesToPublish));
                for (int i = 0; i < cmdLineParser.Config.NumberOfMessagesToPublish; i++)
                {
                    if (session.Send(message) == ReturnCode.SOLCLIENT_OK)
                    {
                        Console.Write(".");
                    }
                    Thread.Sleep(1000); // wait for 1.0 seconds.
                }
                Console.WriteLine(string.Format("\nDone\n Sleeping for {0} secs before exiting ", Timeout / 1000));
                Thread.Sleep(Timeout);
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                bool flowWasConnected = (flow != null);
                if (flow != null)
                {
                    flow.Dispose();
                }
                // Durable Topic Endpoints will continue getting messages on the registered Topic
                // subscription if client applications do not unsubscribe.
                // Non-durable Topic Endpoints will be cleaned up automatically after client applications
                // dispose the Flows bound to them.
                //
                // The following code block demonstrates how to unsubscribe or remove a subscribed Topic on
                // the durable Topic Endpoint.
                // Two conditions must be met:
                // - The durable Topic Endpoint must have at least 'Modify Topic' permission enabled.
                // - No flows are currently bound to the durable Topic Endpoint in question.
                if (topicEndpoint != null && topicEndpoint.Durable && session != null && flowWasConnected)
                {
                    Console.WriteLine(string.Format("About to unsubscribe from durable Topic Endpoint '{0}'", ((ITopicEndpoint)topicEndpoint).Name));
                    session.Unsubscribe(topicEndpoint, "Unsubscribe Operation Correlation ID");
                }
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
        /// <summary>
        /// Main entry point to the sample
        /// </summary>
        /// <param name="args"></param>
        public override void SampleCall(string[] args)
        {
            // Parse command line arguments
            ArgParser cmdLineParser = new ArgParser();

            if (!cmdLineParser.Parse(args) || !SampleParseArgs(cmdLineParser))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }

            // Create the API components: starting with the properties
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = new SessionProperties();

            sessionProps.Host     = cmdLineParser.Config.IpPort.ip;
            sessionProps.UserName = cmdLineParser.Config.RouterUserVpn.user;
            sessionProps.Password = cmdLineParser.Config.UserPassword;
            sessionProps.SSLValidateCertificate = false;
            sessionProps.ReconnectRetries       = 3;
            if (cmdLineParser.Config.RouterUserVpn.vpn != null)
            {
                sessionProps.VPNName = cmdLineParser.Config.RouterUserVpn.vpn;
            }
            if (cmdLineParser.Config.Compression)
            {
                /* Compression is set as a number from 0-9, where 0 means "disable
                 * compression", and 9 means max compression. The default is no
                 * compression.
                 * Selecting a non-zero compression level auto-selects the
                 * compressed SMF port on the appliance, as long as no SMF port is
                 * explicitly specified. */
                sessionProps.CompressionLevel = 9;
            }

            // Create and connect the API components: create the context and session objects
            IContext context = null;

            session = null;
            IFlow     flow = null;
            IEndpoint provisionedEndpoint = null;

            try
            {
                // Creating the context
                InitContext(cmdLineParser.LogLevel);
                Console.WriteLine("Creating the context ...");
                context = ContextFactory.Instance.CreateContext(contextProps, null);

                // Creating the session
                Console.WriteLine("Creating the session ...");
                session = context.CreateSession(sessionProps, HandleRequestMessage, SampleUtils.HandleSessionEvent);

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

                // Provisioning the endpoint

                if (serviceTopic != null)
                {
                    // Provision a Durable Topic Endpoint
                    provisionedEndpoint = ContextFactory.Instance.CreateDurableTopicEndpointEx("cscsmp_sample_" + DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
                }
                else
                {
                    provisionedEndpoint = serviceQueue;
                }
                session.Provision(provisionedEndpoint, new EndpointProperties(), ProvisionFlag.WaitForConfirm, null);
                Console.WriteLine(string.Format("Provisioned new endpoint '{0}'", provisionedEndpoint));

                // Create and start flow to to the newly provisioned endpoint
                FlowProperties flowProperties = new FlowProperties();
                flowProperties.AckMode = MessageAckMode.AutoAck;
                flow = session.CreateFlow(flowProperties,
                                          provisionedEndpoint,  /* the newly created endpoint*/
                                          serviceTopic,         /* null if we're listening on a queue*/
                                          HandleRequestMessage, /* local delegate to process request messages and send corresponding reply messages */
                                          SampleUtils.HandleFlowEvent);
                flow.Start();
                Console.WriteLine("Listening for request messages ... Press any key(except for Ctrl+C) to exit");
                Console.In.Read();
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                Cleanup(flow, provisionedEndpoint, session, context);
            }
        }
        /// <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))
            {
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }

            #endregion

            #region Initialize properties from command line

            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = new SessionProperties();

            sessionProps.Host     = cmdLineParser.Config.IpPort.ip;
            sessionProps.UserName = cmdLineParser.Config.RouterUserVpn.user;
            sessionProps.Password = cmdLineParser.Config.UserPassword;
            sessionProps.SSLValidateCertificate = false;

            if (cmdLineParser.Config.RouterUserVpn.vpn != null)
            {
                sessionProps.VPNName = cmdLineParser.Config.RouterUserVpn.vpn;
            }

            // With reapply subscriptions enabled, the API maintains a
            // cache of added subscriptions in memory. These subscriptions
            // are automatically reapplied following a channel reconnect.
            sessionProps.ReconnectRetries     = 3;
            sessionProps.ReapplySubscriptions = true;

            if (cmdLineParser.Config.Compression)
            {
                // Compression is set as a number from 0-9, where 0 means "disable
                // compression", and 9 means max compression. The default is no
                // compression.
                // Selecting a non-zero compression level auto-selects the
                // compressed SMF port on the appliance, as long as no SMF port is
                // explicitly specified.
                sessionProps.CompressionLevel = 9;
            }

            #endregion

            IContext context = null;
            ISession session = null;

            try
            {
                InitContext(cmdLineParser.LogLevel);
                #region Create the Context

                Console.WriteLine("Creating the context ...");
                context = ContextFactory.Instance.CreateContext(contextProps, null);

                #endregion

                #region Create and connect the Session

                Console.WriteLine("Creating the session ...");
                session = context.CreateSession(sessionProps, HandleMessageEvent, SampleUtils.HandleSessionEvent);

                Console.WriteLine("Connecting the session ...");
                if (session.Connect() == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Session successfully connected");
                }

                #endregion

                #region Subscribe to the topic

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

                #endregion

                #region Publish the messages

                for (int msgsSent = 0; msgsSent < 10; msgsSent++)
                {
                    IMessage message = ContextFactory.Instance.CreateMessage();
                    message.Destination      = topic;
                    message.DeliveryMode     = MessageDeliveryMode.Direct;
                    message.BinaryAttachment = Encoding.ASCII.GetBytes(SampleUtils.MSG_ATTACHMENTTEXT);
                    session.Send(message);

                    // Wait 1 second between messages. This will also give time for the
                    // final message to be received.
                    Thread.Sleep(1000);
                }

                #endregion

                #region Unsubscribe from the topic

                if (session.Unsubscribe(topic, true) == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Successfully removed topic subscription");
                }

                #endregion
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
Beispiel #13
0
 internal extern static unsafe IntPtr CreateContextFromType(ContextProperties* properties, DeviceTypeFlags device_type, IntPtr pfn_notify, IntPtr user_data, [OutAttribute] OpenTK.Compute.CL10.ErrorCode* errcode_ret);
Beispiel #14
0
 internal extern static unsafe IntPtr CreateContext(ContextProperties* properties, uint num_devices, IntPtr* devices, IntPtr pfn_notify, IntPtr user_data, [OutAttribute] int* errcode_ret);
Beispiel #15
0
        /// <summary>
        /// Main entry point to the sample
        /// </summary>
        /// <param name="args"></param>
        public override void SampleCall(string[] args)
        {
            // Parse command line arguments
            ArgParser cmdLineParser = new ArgParser();

            if (!cmdLineParser.Parse(args) || !SampleParseArgs(cmdLineParser))
            {
                // Parse failed.
                PrintUsage(INVALID_ARGUMENTS_ERROR);
                return;
            }

            // Create the API components: starting with the properties
            ContextProperties contextProps = new ContextProperties();
            SessionProperties sessionProps = new SessionProperties();

            sessionProps.Host     = cmdLineParser.Config.IpPort.ip;
            sessionProps.UserName = cmdLineParser.Config.RouterUserVpn.user;
            sessionProps.Password = cmdLineParser.Config.UserPassword;
            sessionProps.SSLValidateCertificate = false;
            sessionProps.ReconnectRetries       = 3;
            if (cmdLineParser.Config.RouterUserVpn.vpn != null)
            {
                sessionProps.VPNName = cmdLineParser.Config.RouterUserVpn.vpn;
            }
            if (cmdLineParser.Config.Compression)
            {
                /* Compression is set as a number from 0-9, where 0 means "disable
                 * compression", and 9 means max compression. The default is no
                 * compression.
                 * Selecting a non-zero compression level auto-selects the
                 * compressed SMF port on the appliance, as long as no SMF port is
                 * explicitly specified. */
                sessionProps.CompressionLevel = 9;
            }

            // Create and connect the API components: create the context, session and flow objects
            IContext context = null;

            try
            {
                // Creating the context
                InitContext(cmdLineParser.LogLevel);
                Console.WriteLine("Creating the context ...");
                context = ContextFactory.Instance.CreateContext(contextProps, null);

                // Creating the session
                Console.WriteLine("Creating the session ...");
                session = context.CreateSession(sessionProps, SampleUtils.HandleMessageEvent, SampleUtils.HandleSessionEvent);

                // Connecting the session
                Console.WriteLine("Connecting the session ...");
                if (session.Connect() == ReturnCode.SOLCLIENT_OK)
                {
                    Console.WriteLine("Session successfully connected");
                }
                // Creating the temporary queue and corresponding flow
                IQueue         replyToQueue   = session.CreateTemporaryQueue();
                FlowProperties flowProperties = new FlowProperties();
                flow = session.CreateFlow(flowProperties,
                                          replyToQueue,
                                          null,               /* null when binding to a queue*/
                                          HandleReplyMessage, /* defined in this sample to handle receipt of reply message*/
                                          SampleUtils.HandleFlowEvent);
                flow.Start();

                doRequest(requestDestination, replyToQueue, Operation.PLUS, 5, 4);
                Thread.Sleep(1000);
                doRequest(requestDestination, replyToQueue, Operation.MINUS, 5, 4);
                Thread.Sleep(1000);
                doRequest(requestDestination, replyToQueue, Operation.TIMES, 5, 4);
                Thread.Sleep(1000);
                doRequest(requestDestination, replyToQueue, Operation.DIVIDE, 5, 4);
            }
            catch (Exception ex)
            {
                PrintException(ex);
            }
            finally
            {
                if (flow != null)
                {
                    flow.Dispose();
                }
                if (session != null)
                {
                    session.Dispose();
                }
                if (context != null)
                {
                    context.Dispose();
                }
                // Must cleanup after.
                CleanupContext();
            }
        }
Beispiel #16
0
 public ContextProperty(ContextProperties property, IntPtr value)
 {
     _propertyName = (uint)property;
     _propertyValue = value;
 }
Beispiel #17
0
 public ContextProperty(ContextProperties property)
 {
     _propertyName = (uint)property;
     _propertyValue = IntPtr.Zero;
 }
        /// <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();
            }
        }