Ejemplo n.º 1
0
        private static TActor CreateActor <TActor>(
            ActorService service,
            ActorId id)
            where TActor : Actor
        {
            TActor actor;
            IServiceEventSource eventSource = null;

            try
            {
                var actorContainer = GetActorContainer(service, id);

                eventSource = actorContainer.GetInstance <IServiceEventSource>();
                eventSource.ServiceTypeRegistered(Process.GetCurrentProcess().Id, Naming.GetServiceName <TActor>());

                actor = actorContainer.GetInstance <TActor>();

                var stateManager = (LazyActorStateManager)actorContainer.GetInstance <IActorStateManager>();
                stateManager.SetActorStateManager(actor.StateManager);
            }
            catch (Exception e)
            {
                eventSource?.ServiceHostInitializationFailed(e.ToString());
                throw;
            }

            return(actor);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// ConfigurationProvider constructor.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="context">CodePackageActivationContext instance.</param>
        /// <param name="eventSource">IServiceEventSource instance for logging.</param>
        /// <param name="partition">Partition identifier.</param>
        /// <param name="replica">Replica or instance identifier.</param>
        public ConfigurationProvider(Uri serviceName, ICodePackageActivationContext context, IServiceEventSource eventSource, Guid partition, long replica)
        {
            Guard.ArgumentNotNull(serviceName, nameof(serviceName));
            Guard.ArgumentNotNull(context, nameof(context));

            _serviceNameUri      = serviceName;
            _serviceName         = _serviceNameUri.Segments[_serviceNameUri.Segments.Length - 1];
            _eventSource         = eventSource;
            _partitionId         = partition;
            _replicaOrInstanceId = replica;

            // Subscribe to configuration change events if the context was passed. It will not be passed for unit tests.
            if (null != context)
            {
                context.ConfigurationPackageAddedEvent    += CodePackageActivationContext_ConfigurationPackageAddedEvent;
                context.ConfigurationPackageModifiedEvent += CodePackageActivationContext_ConfigurationPackageModifiedEvent;
                context.ConfigurationPackageRemovedEvent  += Context_ConfigurationPackageRemovedEvent;
            }

            // Configuration has already been loaded by the time we subscribe to the events above, initialize the configuration the first time.
            IList <string>       names = context.GetConfigurationPackageNames();
            ConfigurationPackage pkg   = context.GetConfigurationPackageObject(c_ConfigurationPackageObjectName);

            // Create the add event parameters and call.
            PackageAddedEventArgs <ConfigurationPackage> evt = new PackageAddedEventArgs <ConfigurationPackage>();

            evt.Package = pkg;
            CodePackageActivationContext_ConfigurationPackageAddedEvent(null, evt);
        }
Ejemplo n.º 3
0
        public static void Add(
            this IServiceCollection @this,
            IServiceEventSource serviceEventSource)
        {
            if (@this == null)
            {
                throw new ArgumentNullException(nameof(@this));
            }

            if (serviceEventSource == null)
            {
                throw new ArgumentNullException(nameof(serviceEventSource));
            }

            var type = serviceEventSource.GetType();

            foreach (var @interface in type
                     .GetInterfaces()
                     .Where(@interface => typeof(IServiceEventSourceInterface).IsAssignableFrom(@interface)))
            {
                @this.Add(new ServiceDescriptor(@interface, serviceEventSource));
            }

            @this.Add(new ServiceDescriptor(type, serviceEventSource));
            @this.Add(new ServiceDescriptor(typeof(IServiceEventSource), serviceEventSource));
        }
 public ServiceHostDelegateLogger(
     ServiceContext serviceContext,
     IServiceEventSource eventSource,
     string eventCategoryName,
     IConfigurableObjectLoggerOptions options)
     : base(serviceContext, eventSource, eventCategoryName, options)
 {
 }
Ejemplo n.º 5
0
        public Owin(StatelessServiceContext serviceContext, IServiceEventSource serviceEventSource,
                    Action <IAppBuilder> appBuilder) : base(serviceContext)
        {
            Requires.IsNotNull(serviceEventSource, nameof(serviceEventSource));
            Requires.IsNotNull(appBuilder, nameof(appBuilder));

            _serviceEventSource = serviceEventSource;
            _appBuilder         = appBuilder;
        }
 public ServiceHostGenericListenerLogger(
     IServiceHostGenericListenerInformation listenerInformation,
     ServiceContext serviceContext,
     IServiceEventSource eventSource,
     string eventCategoryName,
     IConfigurableObjectLoggerOptions options)
     : base(listenerInformation, serviceContext, eventSource, eventCategoryName, options)
 {
 }
Ejemplo n.º 7
0
        /// <summary>
        /// OwinCommunicationListener constructor.
        /// </summary>
        /// <param name="appRoot">String containing the application root name of the service. Defaults to the service type name if not specified.</param>
        /// <param name="instance">Partition operation class instance.</param>
        /// <param name="context">ServiceContext instance containing information about the service instance.</param>
        /// <param name="evtSrc">IServiceEventSource to allow diagnostic logging from within this instance.</param>
        public StatefulOwinCommunicationListener(string appRoot, TOperations instance, ServiceContext context, IServiceEventSource evtSrc)
        {
            Guard.ArgumentNotNull(instance, nameof(instance));
            Guard.ArgumentNotNull(context, nameof(context));
            Guard.ArgumentNotNull(evtSrc, nameof(evtSrc));

            _appRoot             = string.IsNullOrWhiteSpace(appRoot) ? context.ServiceTypeName : appRoot.TrimEnd('/');
            _partitionOperations = instance;
            _context             = context;
            _eventSource         = evtSrc;
        }
Ejemplo n.º 8
0
 protected ServiceHostListenerLogger(
     IServiceHostListenerInformation listenerInformation,
     ServiceContext serviceContext,
     IServiceEventSource eventSource,
     string eventCategoryName,
     IConfigurableObjectLoggerOptions options)
     : base(serviceContext, eventSource, eventCategoryName, options)
 {
     this.listenerInformation = listenerInformation
                                ?? throw new ArgumentNullException(nameof(listenerInformation));
 }
 protected BackupRestoreActorService(StatefulServiceContext context,
                                     ActorTypeInformation actorTypeInfo,
                                     IFileStore fileStore,
                                     IServiceEventSource serviceEventSource, Func <ActorService, ActorId, ActorBase> actorFactory = null,
                                     Func <ActorBase, IActorStateProvider, IActorStateManager> stateManagerFactory = null,
                                     IActorStateProvider stateProvider = null,
                                     ActorServiceSettings settings     = null)
     : base(context, actorTypeInfo, actorFactory, stateManagerFactory, stateProvider, settings)
 {
     this._serviceEventSource = serviceEventSource;
     this._fileStore          = fileStore;
 }
        public OwinCommunicationListener(Action <IAppBuilder> startup, ServiceContext serviceContext, IServiceEventSource eventSource, string endpointName, string appRoot)
        {
            Requires.IsNotNull(startup, nameof(startup));
            Requires.IsNotNull(serviceContext, nameof(serviceContext));
            Requires.IsNotNull(endpointName, nameof(endpointName));
            Requires.IsNotNull(eventSource, nameof(eventSource));

            _startup        = startup;
            _serviceContext = serviceContext;
            _endpointName   = endpointName;
            _eventSource    = eventSource;
            _appRoot        = appRoot;
        }
        public MockStatelessService(
            StatelessServiceContext serviceContext,
            IServiceEventSource serviceEventSource,
            IServicePartition servicePartition)
        {
            this.serviceContext = serviceContext
                                  ?? throw new ArgumentNullException(nameof(serviceContext));

            this.serviceEventSource = serviceEventSource
                                      ?? throw new ArgumentNullException(nameof(serviceEventSource));

            this.servicePartition = servicePartition
                                    ?? throw new ArgumentNullException(nameof(servicePartition));
        }
Ejemplo n.º 12
0
        public ServiceHostDelegateLoggerProvider(
            ServiceContext serviceContext,
            IServiceEventSource eventSource,
            IConfigurableObjectLoggerOptions loggerOptions)
        {
            this.serviceContext = serviceContext
                                  ?? throw new ArgumentNullException(nameof(serviceContext));

            this.loggerOptions = loggerOptions
                                 ?? throw new ArgumentNullException(nameof(loggerOptions));

            this.eventSource = eventSource
                               ?? throw new ArgumentNullException(nameof(eventSource));
        }
Ejemplo n.º 13
0
 public virtual void Run <T>(string serviceTypeName, IServiceEventSource serviceEventSourceBase)
 {
     _eventSource = serviceEventSourceBase;
     //ILogger logger = null;
     try
     {
         //logger = LoggerFactoryCreator.GetLoggerFactory().Create($"Initialization.{typeof(T).Name}");
         RunSpecific(serviceTypeName);
     }
     catch (Exception ex)
     {
         serviceEventSourceBase.ServiceHostInitializationFailed(ex.ToString());
         //logger?.Error("Failed to initialize service", e);
         throw;
     }
 }
        public MockStatefulService(
            StatefulServiceContext serviceContext,
            IServiceEventSource serviceEventSource,
            IServicePartition servicePartition,
            IReliableStateManager reliableStateManager)
        {
            this.serviceContext = serviceContext
                                  ?? throw new ArgumentNullException(nameof(serviceContext));

            this.serviceEventSource = serviceEventSource
                                      ?? throw new ArgumentNullException(nameof(serviceEventSource));

            this.servicePartition = servicePartition
                                    ?? throw new ArgumentNullException(nameof(servicePartition));

            this.reliableStateManager = reliableStateManager;
        }
        public ServiceHostRemotingListenerLoggerProvider(
            IServiceHostRemotingListenerInformation listenerInformation,
            ServiceContext serviceContext,
            IServiceEventSource eventSource,
            IConfigurableObjectLoggerOptions loggerOptions)
        {
            this.serviceContext = serviceContext
                                  ?? throw new ArgumentNullException(nameof(serviceContext));

            this.listenerInformation = listenerInformation
                                       ?? throw new ArgumentNullException(nameof(listenerInformation));

            this.loggerOptions = loggerOptions
                                 ?? throw new ArgumentNullException(nameof(loggerOptions));

            this.eventSource = eventSource
                               ?? throw new ArgumentNullException(nameof(eventSource));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// QueueService constructor.
        /// </summary>
        /// <param name="context">StatefulServiceContext instance.</param>
        /// <param name="eventSource">IStatefulServiceEventSource instance for diagnostic logging.</param>
        public GenericInt64PartitionService(StatefulServiceContext context, IServiceEventSource eventSource)
            : base(context)
        {
            // Check passed parameters.
            Guard.ArgumentNotNull(context, nameof(context));
            Guard.ArgumentNotNull(eventSource, nameof(eventSource));

            _eventSource = eventSource;

            TokenSource = new CancellationTokenSource();

            // Parse the service name into an application name.
            string appName = (Context.ServiceName.Segments.Length > 2) ? Context.ServiceName.Segments[1].Replace("/", "") : "";

            Application = new Uri($"fabric:/{appName}");

            ConfigurationProvider = new ConfigurationProvider <TConfiguration>(context.ServiceName, context.CodePackageActivationContext, eventSource, Context.PartitionId, Context.ReplicaOrInstanceId);
            _eventSource?.ServicePartitionConfigurationChanged(Context.ServiceTypeName, Context.PartitionId, Context.ReplicaOrInstanceId);
        }
        protected ServiceHostLogger(
            ServiceContext serviceContext,
            IServiceEventSource eventSource,
            string eventCategoryName,
            IConfigurableObjectLoggerOptions options)
        {
            this.serviceContext = serviceContext
                                  ?? throw new ArgumentNullException(nameof(serviceContext));

            this.eventSource = eventSource
                               ?? throw new ArgumentNullException(nameof(eventSource));

            this.eventCategoryName = eventCategoryName
                                     ?? throw new ArgumentNullException(nameof(eventCategoryName));

            this.scope = new AsyncLocal <Scope>();

            this.options = options
                           ?? throw new ArgumentNullException(nameof(options));
        }
Ejemplo n.º 18
0
        private static TService CreateService <TService>(StatefulServiceContext context) where TService : StatefulService
        {
            TService            service;
            IServiceEventSource eventSource = null;

            try
            {
                var container = GetContainer(context);

                eventSource = container.GetInstance <IServiceEventSource>();
                eventSource.ServiceTypeRegistered(Process.GetCurrentProcess().Id, Naming.GetServiceName <TService>());
                service = container.GetInstance <TService>();
            }
            catch (Exception e)
            {
                eventSource?.ServiceHostInitializationFailed(e.ToString());
                throw;
            }

            return(service);
        }
 public KitchenActorService(StatefulServiceContext context, ActorTypeInformation actorTypeInfo, IFileStore fileStore,
                            IServiceEventSource serviceEventSource, Func <ActorService, ActorId, ActorBase> actorFactory = null,
                            Func <ActorBase, IActorStateProvider, IActorStateManager> stateManagerFactory = null, IActorStateProvider stateProvider = null,
                            ActorServiceSettings settings = null) : base(context, actorTypeInfo, fileStore, serviceEventSource, actorFactory, stateManagerFactory, stateProvider, settings)
 {
 }
        public static async Task <EmbedConfig> GetEmbedReportConfigData(string clientId, string groupId, string username, string password, string authorityUrl, string resourceUrl, string apiUrl, string reportUniqueId, string reportName, ServiceContext serviceContext, IServiceEventSource serviceEventSource)
        {
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);
            var result = new EmbedConfig();
            var roles  = "";

            try
            {
                var error = GetWebConfigErrors(clientId, groupId, username, password);
                if (error != null)
                {
                    result.ErrorMessage = error;
                    return(result);
                }

                // Create a user password cradentials.
                var credential = new UserPasswordCredential(username, password);

                // Authenticate using created credentials
                var authenticationContext = new AuthenticationContext(authorityUrl);
                var authenticationResult  = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);

                if (authenticationResult == null)
                {
                    result.ErrorMessage = "Authentication Failed.";
                    return(result);
                }

                var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

                // Create a Power BI Client object. It will be used to call Power BI APIs.
                using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))
                {
                    // Get a list of reports.
                    var reports = await client.Reports.GetReportsInGroupAsync(groupId);

                    Report report;
                    if (string.IsNullOrEmpty(reportName))
                    {
                        // Get the first report in the group.
                        report = reports.Value.FirstOrDefault();
                    }
                    else
                    {
                        report = reports.Value.FirstOrDefault(r => r.Name.Equals(reportName));
                    }

                    if (report == null)
                    {
                        result.ErrorMessage = $"PowerBI Group has no report registered for Name[{reportName}].";
                        return(result);
                    }

                    var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(groupId, report.DatasetId);

                    result.IsEffectiveIdentityRequired      = datasets.IsEffectiveIdentityRequired;
                    result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                    GenerateTokenRequest generateTokenRequestParameters;

                    // This is how you create embed token with effective identities
                    if ((result.IsEffectiveIdentityRequired != null && result.IsEffectiveIdentityRequired == true) &&
                        (result.IsEffectiveIdentityRolesRequired != null && result.IsEffectiveIdentityRolesRequired == true) &&
                        !string.IsNullOrEmpty(username))
                    {
                        var rls = new EffectiveIdentity(username, new List <string> {
                            report.DatasetId
                        });
                        if (!string.IsNullOrWhiteSpace(roles))
                        {
                            var rolesList = new List <string>();
                            rolesList.AddRange(roles.Split(','));
                            rls.Roles = rolesList;
                        }
                        // Generate Embed Token with effective identities.
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> {
                            rls
                        });
                    }
                    else
                    {
                        // Generate Embed Token for reports without effective identities.
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                    }

                    var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(groupId, report.Id, generateTokenRequestParameters);

                    if (tokenResponse == null)
                    {
                        serviceEventSourceHelper.ServiceMessage(serviceContext, $"Embed Report - Error during user authentication for report - Result=[{tokenResponse.ToString()}]");
                        result.ErrorMessage = "Failed to authenticate user for report request";
                        return(result);
                    }

                    // Generate Embed Configuration.
                    result.EmbedToken = tokenResponse;
                    result.EmbedUrl   = report.EmbedUrl;
                    result.Id         = report.Id;
                    return(result);
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = string.Format($"Status: {exc.Response.StatusCode} Response Content: [{exc.Response.Content}] RequestId: {exc.Response.Headers["RequestId"].FirstOrDefault()}");
            }
            catch (Exception exc)
            {
                result.ErrorMessage = exc.ToString();
            }

            return(result);
        }
        public static async Task <bool> PublishReportDataFor(string reportUniqueId, string datasetName, List <DeviceMessage> deviceMessagelList, ServiceContext serviceContext, HttpClient httpClient, CancellationToken cancellationToken, IServiceEventSource serviceEventSource, int resampleSetsLimit = 0, int minMagnitudeAllowed = 1)
        {
            bool bRet          = false;
            int  maxSendingSet = 9999;
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);
            DatasetConfiguration     datasetConfiguration     = DatasetRegistry.GetDatasetConfiguration(datasetName);
            int initialMessageCount = 0;

            serviceEventSourceHelper.ServiceMessage(serviceContext, $"PublishReportDataFor - About to publish data for Report id[{reportUniqueId}] Dataset Name[{datasetName}] Number of messages [{deviceMessagelList.Count}]");

            ReportStreamDataset reportStreamDataset = new ReportStreamDataset(reportUniqueId, datasetConfiguration, deviceMessagelList);

            if (reportStreamDataset.Count > 0 && resampleSetsLimit > 0)
            {
                initialMessageCount = reportStreamDataset.Count;
                int maxNumberOfMessagesToSend = (resampleSetsLimit * maxSendingSet);
                ReportStreamDataset resampledReportStreamDataset = new ReportStreamDataset(reportUniqueId, datasetConfiguration);

                if (reportStreamDataset.Count > maxNumberOfMessagesToSend)
                {
                    float selectInterval = reportStreamDataset.Count / maxNumberOfMessagesToSend;
                    int   selectedCount  = 0;
                    int   index          = 0;

                    foreach (DeviceMessage message in reportStreamDataset.DeviceMessageList)
                    {
                        if (index >= (selectedCount * selectInterval))
                        {
                            selectedCount++;
                            resampledReportStreamDataset.AddMessage(message);
                        }
                        index++;

                        if (selectedCount == maxNumberOfMessagesToSend)
                        {
                            break;
                        }
                    }
                    reportStreamDataset = resampledReportStreamDataset;
                }
            }

            serviceEventSourceHelper.ServiceMessage(serviceContext, $"PublishReportDataFor - Report id[{reportUniqueId}]  Final number of rows [{reportStreamDataset.Count}] generated from messages [{initialMessageCount}] requested for Dataset [{datasetName}]");

            if (reportStreamDataset.Count > 0)
            {
                int           messageCounter = 0;
                int           messageSet     = 1;
                bool          firstSet       = true;
                StringBuilder bodyContent    = new StringBuilder();
                bodyContent.Append("[");
                bool firstItem = true;

                foreach (DeviceMessage message in reportStreamDataset.DeviceMessageList)
                {
                    if (firstItem)
                    {
                        firstItem = false;
                    }
                    else
                    {
                        bodyContent.Append(",");
                    }

                    bodyContent.Append(datasetConfiguration.GetMessageToPublish(message));
                    messageCounter++;

                    if (messageCounter == maxSendingSet)
                    {
                        if (!firstSet)
                        {
                            await Task.Delay(global::Iot.Common.Names.IntervalBetweenReportStreamingCalls);
                        }

                        bodyContent.Append("]");
                        await RESTHandler.ExecuteHttpPOST(datasetConfiguration.PostUrl, bodyContent.ToString(), httpClient, cancellationToken, serviceEventSource);

                        serviceEventSourceHelper.ServiceMessage(serviceContext, $"PublishReportDataFor -  Sending set [{messageSet}] with number of rows [{messageCounter}] generated from messages [{reportStreamDataset.Count}] to dataset [{datasetName}]");

                        bodyContent.Clear();
                        bodyContent.Append("[");
                        firstItem      = true;
                        messageCounter = 0;
                        messageSet++;
                        firstSet = false;
                    }
                }

                if (reportStreamDataset.Count > 0)
                {
                    if (!firstSet)
                    {
                        await Task.Delay(global::Iot.Common.Names.IntervalBetweenReportStreamingCalls);
                    }
                    bodyContent.Append("]");
                    await RESTHandler.ExecuteHttpPOST(datasetConfiguration.PostUrl, bodyContent, httpClient, cancellationToken, serviceEventSource);

                    serviceEventSourceHelper.ServiceMessage(serviceContext, $"PublishReportDataFor -  Sending set [{messageSet}] with number of rows [{messageCounter}] generated from messages [{reportStreamDataset.Count}] to dataset [{datasetName}]");
                }
                bRet = true;
            }
            else
            {
                serviceEventSourceHelper.ServiceMessage(serviceContext, $"Embed Report - No data found to publish for Dataset [{datasetName}]");
            }

            return(bRet);
        }
 public MicroServiceProcessor(ServiceContext serviceContext, IServiceEventSource serviceEventSource = null)
 {
     _serviceEventSource = serviceEventSource;
     _serviceContext     = serviceContext;
 }
 public DinnerMenuService(StatefulServiceContext context, IDishStateManager dishStateManager,
                          IReliableStateManagerReplica2 stateManager, IFileStore fileStore, IServiceEventSource serviceEventSource)
     : base(context, stateManager, fileStore, serviceEventSource)
 {
     _dishStateManager = dishStateManager;
 }
Ejemplo n.º 24
0
        public static async Task <object> ExecuteFabricGETForEntity(Type targetObjectType, string targetServiceType, string servicePathAndQuery, string entityName, ServiceContext serviceContext, HttpClient httpClient, CancellationToken cancellationToken, IServiceEventSource serviceEventSource = null)
        {
            object objRet = null;
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);

            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(targetServiceType);
            Uri  serviceUri = uriBuilder.Build();
            long targetSiteServicePartitionKey = HashUtil.Hash(entityName);
            Uri  getUrl = new HttpServiceUriBuilder()
                          .SetServiceName(serviceUri)
                          .SetPartitionKey(targetSiteServicePartitionKey)
                          .SetServicePathAndQuery(servicePathAndQuery)
                          .Build();

            HttpResponseMessage response = await httpClient.GetAsync(getUrl, cancellationToken);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                serviceEventSourceHelper.ServiceMessage(serviceContext, $"On Execute Fabric GET - Service returned result[{response.StatusCode}] for entity[{entityName}] request[{servicePathAndQuery}]");
                objRet = response;
            }
            else
            {
                JsonSerializer serializer = new JsonSerializer();
                using (StreamReader streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                    {
                        objRet = serializer.Deserialize(jsonReader, targetObjectType);
                    }
                }
            }

            return(objRet);
        }
Ejemplo n.º 25
0
        public static async Task <bool> ExecuteHttpPOST(String postUrl, object bodyObject, HttpClient httpClient, CancellationToken cancellationToken, IEnumerable <KeyValuePair <string, IEnumerable <string> > > additionalHeaders = null, IServiceEventSource serviceEventSource = null)
        {
            bool bRet = false;
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);

            HttpContent postContent = null;

            if (bodyObject != null)
            {
                string jsonStr = "";

                if (bodyObject is string)
                {
                    jsonStr = (string)bodyObject;
                }
                else
                {
                    jsonStr = JsonConvert.SerializeObject(bodyObject);
                }

                if (jsonStr.Length > 0)
                {
                    MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
                    postContent = new StreamContent(mStrm);
                }
                else
                {
                    postContent = new StringContent("");
                }
                postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }
            else
            {
                postContent = new StringContent("");
                postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }

            if (additionalHeaders != null)
            {
                foreach (KeyValuePair <string, IEnumerable <string> > item in additionalHeaders)
                {
                    if (item.Key.Equals("Authorization"))
                    {
                        string scheme    = "Bearer";
                        string parameter = "";
                        int    counter   = 0;
                        foreach (string value in item.Value)
                        {
                            if (counter == 0)
                            {
                                scheme = value;
                            }
                            if (counter == 1)
                            {
                                parameter = value;
                            }
                            counter++;
                        }

                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(scheme, parameter);
                    }
                    else
                    {
                        if (item.Value.Count() > 1)
                        {
                            httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
                        }
                        else
                        {
                            string value = item.Value.FirstOrDefault();

                            httpClient.DefaultRequestHeaders.Add(item.Key, value);
                        }
                    }
                }
            }

            HttpResponseMessage response = await httpClient.PostAsync(postUrl, postContent, cancellationToken);

            if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                // This service expects the receiving target site service to return HTTP 400 if the device message was malformed.
                // In this example, the message is simply logged.
                // Your application should handle all possible error status codes from the receiving service
                // and treat the message as a "poison" message.
                // Message processing should be allowed to continue after a poison message is detected.

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

                serviceEventSourceHelper.Message($"On Execute HTTP POST - Service Returned BAD REQUEST - Response Content[{responseContent}]");
            }
            else
            {
                bRet = true;
            }

            return(bRet);
        }
        public static DeviceMessage DeserializeEvents(string deviceId, string arrayEventStr, ServiceContext serviceContext, IServiceEventSource serviceEventSource)
        {
            DeviceMessage deviceMessageRet = null;

            try
            {
                JArray jarr = JArray.Parse(arrayEventStr);

                deviceMessageRet = DeserializeEvents(deviceId, jarr, serviceContext, serviceEventSource);
            }
            catch (Exception ex)
            {
                serviceEventSource.ServiceMessage(serviceContext, $"Event Registry - Could not parse device id[{deviceId}] message [{arrayEventStr}] Error Message [{ex.Message}]");
            }

            return(deviceMessageRet);
        }
        public static JArray SerializeEvents(string deviceId, DeviceMessage deviceMessage, ServiceContext serviceContext, IServiceEventSource serviceEventSource)
        {
            JArray jarrRet = new JArray();

            foreach (DeviceEvent deviceEvent in deviceMessage.Events)
            {
                JObject jsonObj = SerializeEvent(deviceEvent);

                jarrRet.Add(jsonObj);
            }

            return(jarrRet);
        }
Ejemplo n.º 28
0
        public static async Task <bool> ExecuteFabricPOSTForEntity(Type targetObjectType, string targetServiceType, string servicePathAndQuery, string entityName, object bodyObject, ServiceContext serviceContext, HttpClient httpClient, CancellationToken cancellationToken, IServiceEventSource serviceEventSource = null)
        {
            bool bRet = false;
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);

            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(targetServiceType);
            Uri  serviceUri = uriBuilder.Build();
            long targetSiteServicePartitionKey = HashUtil.Hash(entityName);

            Uri postUrl = new HttpServiceUriBuilder()
                          .SetServiceName(serviceUri)
                          .SetPartitionKey(targetSiteServicePartitionKey)
                          .SetServicePathAndQuery(servicePathAndQuery)
                          .Build();

            string       jsonStr = JsonConvert.SerializeObject(bodyObject);
            MemoryStream mStrm   = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));

            using (StreamContent postContent = new StreamContent(mStrm))
            {
                postContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                HttpResponseMessage response = await httpClient.PostAsync(postUrl, postContent, cancellationToken);

                if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    // This service expects the receiving target site service to return HTTP 400 if the device message was malformed.
                    // In this example, the message is simply logged.
                    // Your application should handle all possible error status codes from the receiving service
                    // and treat the message as a "poison" message.
                    // Message processing should be allowed to continue after a poison message is detected.

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

                    serviceEventSourceHelper.ServiceMessage(serviceContext, $"On Execute Fabric POST - Service returned BAD REQUEST for entity[{entityName}] request[{servicePathAndQuery}] result=[{responseContent} requestBody[{await postContent.ReadAsStringAsync()}]");
                }
                else
                {
                    bRet = true;
                }
            }

            return(bRet);
        }
        public static DeviceMessage DeserializeEvents(string deviceId, JArray events, ServiceContext serviceContext, IServiceEventSource serviceEventSource)
        {
            DeviceMessage messageRet = null;
            bool          firstEvent = true;

            foreach (JObject evt in events)
            {
                String eventType = GetEventTypeFromEvent(evt);

                if (eventType.Equals(Names.EVENT_TYPE_DEFAULT))
                {
                    serviceEventSource.ServiceMessage(serviceContext, $"Event Registry - Could not find event configuration for event type [{eventType}] - Will parse the event as Default Type");
                }

                EventConfiguration eventConfiguration = EventRegistry.GetEventConfiguration(eventType);

                DeviceEvent deviceEvent = DeserializeEvent(eventConfiguration, evt);

                if (firstEvent)
                {
                    messageRet = new DeviceMessage(eventConfiguration.MessageType, deviceId, deviceEvent);
                    firstEvent = false;
                }
                else
                {
                    messageRet.AddEvent(deviceEvent);
                }
            }

            return(messageRet);
        }
Ejemplo n.º 30
0
 public static async Task <bool> ExecuteHttpPOST(String postUrl, object bodyObject, HttpClient httpClient, CancellationToken cancellationToken, IServiceEventSource serviceEventSource = null)
 {
     return(await ExecuteHttpPOST(postUrl, bodyObject, httpClient, cancellationToken, null, serviceEventSource));
 }