Example #1
0
        /// <summary>
        /// Publishes the specified payload.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="payload">The payload.</param>
        /// <param name="config">The configuration.</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public virtual IFluentRabbit Publish <T>(T payload, PublishConfig config)
        {
            return(TryCatch_Trace(MethodBase.GetCurrentMethod(),
                                  () =>
            {
                byte[] body = null;

                if (config.PayloadFormat == PayloadFormat.String)
                {
                    payload.ThrowExceptionIf(p => p.GetType() != typeof(string), "Payload type is not a string!");
                    body = Encoding.UTF8.GetBytes(payload.ToString());
                }
                else if (config.PayloadFormat == PayloadFormat.ByteArray)
                {
                    if (typeof(T) == typeof(byte[]))
                    {
                        body = payload as byte[];
                    }
                    else
                    {
                        var bf = new BinaryFormatter();
                        using var ms = new MemoryStream();
                        bf.Serialize(ms, payload);

                        body = ms.ToArray();
                    }
                }

                Publish(body, config);
            }));
        }
Example #2
0
        public async static Task <string> ApiCall()
        {
            var           client        = new HttpClient();
            PublishConfig publishConfig = new PublishConfig();

            var body = JsonConvert.SerializeObject(publishConfig);

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8e58705e846746929c09bde10ef6844f");

            var uri = "https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/7f7a0d7e-842b-4cdc-bb8e-e51e12b081f4/publish?";

            HttpResponseMessage response;

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes(body);

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = await client.PostAsync(uri, content);

                string result = await response.Content.ReadAsStringAsync();

                return(result);
            }
        }
Example #3
0
 private Config(GeneralConfig generalConfig, PackageMeta packageMeta, InitConfig initConfig, BuildConfig buildConfig, PublishConfig publishConfig, AuthConfig authConfig)
 {
     api           = new Lazy <ApiHelper>(() => new ApiHelper(this));
     GeneralConfig = generalConfig;
     PackageMeta   = packageMeta;
     InitConfig    = initConfig;
     BuildConfig   = buildConfig;
     PublishConfig = publishConfig;
     AuthConfig    = authConfig;
 }
Example #4
0
        public void SubscribeReceiveTest()
        {
            var finished = new ManualResetEventSlim(false);

            var testMessage = "Test";

            string results = string.Empty;

            var client = BusClientFactory.CreateDefault <AdvancedMessageContext>();

            var pubcfg = new PublishConfig()
            {
                Name         = "SubscribeTest",
                ExchangeName = "SubscribeTestResponse",
                ExchangeType = ExchangeType.Topic
            };
            var config = new WorkerInstanceConfiguration()
            {
                SubsciptionConfig = new SubsciptionConfig()
                {
                    ExchangeName = "SubscribeTest",
                    ExchangeType = ExchangeType.Topic
                },
                PublishToConfig = new List <PublishConfig>
                {
                    pubcfg
                }
            };

            var testobj = new TestSubscribeWorker(async message =>
            {
                await Task.Yield();

                results = message.Message;
                finished.Set();
            }

                                                  );

            testobj.Init(client, config);

            client.PublishAsync(new TestMessage()
            {
                Message = testMessage
            }, Guid.NewGuid(),
                                c =>
                                c.WithExchange(
                                    e =>
                                    e.WithName(config.SubsciptionConfig.ExchangeName)
                                    .WithType(config.SubsciptionConfig.ExchangeType)));

            Assert.IsTrue(finished.Wait(2000));

            Assert.AreEqual(testMessage, results);
        }
Example #5
0
        /// <summary>
        /// Publishes the specified payload.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="payload">The payload.</param>
        /// <param name="configAction">The configuration action.</param>
        /// <returns></returns>
        public virtual IFluentRabbit Publish <T>(T payload, Action <PublishConfig> configAction)
        {
            return(TryCatch_Trace(MethodBase.GetCurrentMethod(),
                                  () =>
            {
                var config = new PublishConfig();
                configAction.Invoke(config);

                Publish(payload, config);
            }));
        }
Example #6
0
        public void OnBeforeSerialize()
        {
            name = name_space + "." + package_name;

            if (publishConfig != null)
            {
                if (string.IsNullOrEmpty(publishConfig.registry))
                {
                    publishConfig = null;
                }
            }
        }
Example #7
0
        /// <summary>
        /// Publishes the specified data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="config">The configuration.</param>
        /// <returns></returns>
        public virtual IFluentRabbit Publish(byte[] data, PublishConfig config)
        {
            return(TryCatch_Trace(MethodBase.GetCurrentMethod(),
                                  () =>
            {
                //validation
                config.ThrowExceptionIfNull <ArgumentNullException>(nameof(config));
                config.Validate();
                RabbitMqClient.Model.ThrowExceptionIfNull <ModelIsNullException>();

                //execution
                RabbitMqClient.Model.BasicPublish(config.ExchangeName, config.RoutingKey, config.Mandatory, config.BasicProperties, data);
            }));
        }
Example #8
0
    public static Config Parse(params IConfigProvider[] configProviders)
    {
        var generalConfig = new GeneralConfig();
        var packageMeta   = new PackageMeta();
        var initConfig    = new InitConfig();
        var buildConfig   = new BuildConfig();
        var publishConfig = new PublishConfig();
        var authConfig    = new AuthConfig();
        var result        = new Config(generalConfig, packageMeta, initConfig, buildConfig, publishConfig, authConfig);

        foreach (var provider in configProviders)
        {
            provider.Parse(result);
            Merge(generalConfig, provider.GetGeneralConfig(), false);
            Merge(packageMeta, provider.GetPackageMeta(), false);
            Merge(initConfig, provider.GetInitConfig(), false);
            Merge(buildConfig, provider.GetBuildConfig(), false);
            Merge(publishConfig, provider.GetPublishConfig(), false);
            Merge(authConfig, provider.GetAuthConfig(), false);
        }
        return(result);
    }
Example #9
0
        /// <summary>
        /// Method to start monitoring a node and publish the data to IoTHub.
        /// </summary>
        private ServiceResult OnPublishNodeCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            if (inputArguments[0] == null || inputArguments[1] == null)
            {
                Trace("PublishNode: Invalid Arguments when trying to publish a node.");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments!"));
            }

            NodeToPublishConfig nodeToPublish;
            NodeId nodeId      = null;
            Uri    endpointUri = null;

            try
            {
                if (string.IsNullOrEmpty(inputArguments[0] as string) || string.IsNullOrEmpty(inputArguments[1] as string))
                {
                    Trace($"PublishNode: Arguments (0 (nodeId), 1 (endpointUrl)) are not valid strings!");
                    return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"));
                }
                nodeId        = NodeId.Parse(inputArguments[0] as string);
                endpointUri   = new Uri(inputArguments[1] as string);
                nodeToPublish = new NodeToPublishConfig(nodeId, endpointUri, OpcSamplingInterval, OpcPublishingInterval);
            }
            catch (UriFormatException)
            {
                Trace($"PublishNode: The EndpointUri has an invalid format '{inputArguments[1] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as second argument!"));
            }
            catch (Exception e)
            {
                Trace(e, $"PublishNode: The NodeId has an invalid format '{inputArguments[0] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA NodeId in 'ns=' syntax as first argument!"));
            }

            // find/create a session to the endpoint URL and start monitoring the node.
            try
            {
                if (PublisherShutdownInProgress)
                {
                    return(ServiceResult.Create(StatusCodes.BadUnexpectedError, $"Publisher shutdown in progress."));
                }

                // find the session we need to monitor the node
                OpcSession opcSession = null;
                try
                {
                    OpcSessionsSemaphore.Wait();
                    opcSession = OpcSessions.FirstOrDefault(s => s.EndpointUri == nodeToPublish.EndpointUri);

                    // add a new session.
                    if (opcSession == null)
                    {
                        // create new session info.
                        opcSession = new OpcSession(nodeToPublish.EndpointUri, OpcSessionCreationTimeout);
                        OpcSessions.Add(opcSession);
                        Trace($"PublishNode: No matching session found for endpoint '{nodeToPublish.EndpointUri.OriginalString}'. Requested to create a new one.");
                    }
                    else
                    {
                        Trace($"PublishNode: Session found for endpoint '{nodeToPublish.EndpointUri.OriginalString}'");
                    }

                    // add the node info to the subscription with the default publishing interval
                    opcSession.AddNodeForMonitoring(OpcPublishingInterval, OpcSamplingInterval, nodeToPublish.NodeId);
                    Trace($"PublishNode: Requested to monitor item with NodeId '{nodeToPublish.NodeId.ToString()}' (PublishingInterval: {OpcPublishingInterval}, SamplingInterval: {OpcSamplingInterval})");
                }
                finally
                {
                    OpcSessionsSemaphore.Release();
                }

                // update our data
                try
                {
                    PublishDataSemaphore.Wait();
                    PublishConfig.Add(nodeToPublish);

                    // add it also to the publish file
                    var publisherConfigFileEntry = new PublisherConfigFileEntry()
                    {
                        EndpointUri = endpointUri,
                        NodeId      = nodeId
                    };
                    PublisherConfigFileEntries.Add(publisherConfigFileEntry);
                    File.WriteAllText(NodesToPublishAbsFilename, JsonConvert.SerializeObject(PublisherConfigFileEntries));
                }
                finally
                {
                    PublishDataSemaphore.Release();
                }
                return(ServiceResult.Good);
            }
            catch (Exception e)
            {
                Trace(e, $"PublishNode: Exception while trying to configure publishing node '{nodeToPublish.NodeId.ToString()}'");
                return(ServiceResult.Create(e, StatusCodes.BadUnexpectedError, $"Unexpected error publishing node: {e.Message}"));
            }
        }