Beispiel #1
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);
        }
Beispiel #2
0
        // read from all partititions
        public static async Task <object> ExecuteFabricGETForAllPartitions(Type targetType, string targetServiceType, string servicePathAndQuery, string entityName, ServiceContext serviceContext, HttpClient httpClient, FabricClient fabricClient, CancellationToken cancellationToken, IServiceEventSource serviceEventSource = null)
        {
            object objRet = null;
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);

            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(targetServiceType);
            Uri serviceUri = uriBuilder.Build();

            // service may be partitioned.
            // this will aggregate device IDs from all partitions
            ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

            foreach (Partition partition in partitions)
            {
                Uri getUrl = new HttpServiceUriBuilder()
                             .SetServiceName(serviceUri)
                             .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                             .SetServicePathAndQuery(servicePathAndQuery)
                             .Build();

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

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    serviceEventSourceHelper.ServiceMessage(serviceContext, $"On Execute Fabric GET (For All Partitions) - Service returned result[{response.StatusCode}] for entity[{entityName}] request[{servicePathAndQuery}]");
                    objRet = response;
                }

                JsonSerializer serializer = new JsonSerializer();
                using (StreamReader streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                    {
                        objRet = serializer.Deserialize(jsonReader, targetType);

                        if (objRet != null)
                        {
                            break;
                        }
                    }
                }
            }

            return(objRet);
        }
Beispiel #3
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 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);
        }
Beispiel #6
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);
        }
Beispiel #7
0
        public static async Task <object> ExecuteHttpGET(Type targetObjectType, String getUrl, HttpClient httpClient, CancellationToken cancellationToken, IEnumerable <KeyValuePair <string, IEnumerable <string> > > additionalHeaders = null, IServiceEventSource serviceEventSource = null)
        {
            object objRet = null;
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);

            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.GetAsync(getUrl, 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 GET - Service Returned BAD REQUEST - Response Content[{responseContent}]");
            }
            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);
        }
        public static async Task <bool> PublishReportDataFor(string reportUniqueId, string publishUrl, List <DeviceViewModelList> deviceViewModelList, 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);

            serviceEventSourceHelper.ServiceMessage(serviceContext, $"PublishReportDataFor - About to publish data for report id[{reportUniqueId}]  Number of messages [{deviceViewModelList.Count}] to URL [{publishUrl}]");

            if (deviceViewModelList.Count > 0)
            {
                DateTimeOffset           timestamp      = DateTimeOffset.UtcNow;;
                int                      messageCounter = 0;
                List <DeviceReportModel> messages       = new List <DeviceReportModel>();
                List <string>            deviceList     = new List <string>();
                int                      deviceIdIndex  = 0;
                List <DateTimeOffset>    timestampList  = new List <DateTimeOffset>();
                int                      timestampIndex = 0;

                foreach (DeviceViewModelList deviceModel in deviceViewModelList)
                {
                    if (deviceList.Contains(deviceModel.DeviceId))
                    {
                        deviceIdIndex = deviceList.IndexOf(deviceModel.DeviceId);
                    }
                    else
                    {
                        deviceList.Add(deviceModel.DeviceId);
                        deviceIdIndex = deviceList.IndexOf(deviceModel.DeviceId);
                    }

                    bool   firstItem = true;
                    string devId     = deviceModel.DeviceId;
                    IEnumerable <DeviceViewModel> evts = deviceModel.Events;
                    int    batteryLevel              = 3300;
                    int    batteryVoltage            = 0;
                    int    batteryMax                = 4;
                    int    batteryMin                = 2;
                    int    batteryTarget             = 3;
                    int    batteryPercentage         = 30;
                    int    batteryPercentageMax      = 100;
                    int    batteryPercentageMin      = 0;
                    int    batteryPercentageTarget   = 15;
                    int    temperatureExternal       = 0;
                    int    temperatureExternalMax    = 200;
                    int    temperatureExternalMin    = -50;
                    int    temperatureExternalTarget = 60;
                    int    temperatureInternal       = 0;
                    int    temperatureInternalMax    = 200;
                    int    temperatureInternalMin    = -50;
                    int    temperatureInternalTarget = 60;
                    int    dataPointsCount           = 0;
                    string measurementType           = "";
                    int    sensorIndex               = 0;
                    int    frequency           = 0;
                    int    magnitude           = 0;
                    bool   needReferenceEntry  = true;
                    int    minFrequancyAllowed = 0;

                    foreach (DeviceViewModel sensorMessage in evts)
                    {
                        if (firstItem)
                        {
                            batteryLevel   = sensorMessage.BatteryLevel;
                            batteryVoltage = batteryLevel / 1000;

                            if (batteryLevel < 2800)
                            {
                                batteryPercentage = 0;
                            }
                            else if (batteryLevel > 3600)
                            {
                                batteryPercentage = 100;
                            }
                            else
                            {
                                batteryPercentage = (batteryLevel - 2800) / 10;
                            }

                            timestamp           = sensorMessage.Timestamp;
                            measurementType     = sensorMessage.MeasurementType;
                            dataPointsCount     = sensorMessage.DataPointsCount;
                            temperatureExternal = sensorMessage.TempExternal;
                            temperatureInternal = sensorMessage.TempInternal;

                            firstItem = false;

                            if (timestampList.Contains(timestamp))
                            {
                                timestampIndex = timestampList.IndexOf(timestamp);
                            }
                            else
                            {
                                timestampList.Add(timestamp);
                                timestampIndex = timestampList.IndexOf(timestamp);
                            }
                        }

                        for (int index = 0; index < sensorMessage.Frequency.Length; index++)
                        {
                            sensorIndex = sensorMessage.SensorIndex;
                            frequency   = sensorMessage.Frequency[index];
                            magnitude   = sensorMessage.Magnitude[index];

                            if (minFrequancyAllowed == 0)
                            {
                                minFrequancyAllowed = frequency;
                            }

                            if (magnitude >= minMagnitudeAllowed)
                            {
                                needReferenceEntry = false;

                                messages.Add(new DeviceReportModel(reportUniqueId,
                                                                   timestamp,
                                                                   timestampIndex,
                                                                   devId,
                                                                   deviceIdIndex,
                                                                   batteryLevel,
                                                                   batteryVoltage,
                                                                   batteryMax,
                                                                   batteryMin,
                                                                   batteryTarget,
                                                                   batteryPercentage,
                                                                   batteryPercentageMax,
                                                                   batteryPercentageMin,
                                                                   batteryPercentageTarget,
                                                                   temperatureExternal,
                                                                   temperatureExternalMax,
                                                                   temperatureExternalMin,
                                                                   temperatureExternalTarget,
                                                                   temperatureInternal,
                                                                   temperatureInternalMax,
                                                                   temperatureInternalMin,
                                                                   temperatureInternalTarget,
                                                                   dataPointsCount,
                                                                   measurementType,
                                                                   sensorIndex,
                                                                   frequency,
                                                                   magnitude)
                                             );
                                messageCounter++;
                            }
                        }

                        if (needReferenceEntry)
                        {
                            messages.Add(new DeviceReportModel(reportUniqueId,
                                                               timestamp,
                                                               timestampIndex,
                                                               devId,
                                                               deviceIdIndex,
                                                               batteryLevel,
                                                               batteryVoltage,
                                                               batteryMax,
                                                               batteryMin,
                                                               batteryTarget,
                                                               batteryPercentage,
                                                               batteryPercentageMax,
                                                               batteryPercentageMin,
                                                               batteryPercentageTarget,
                                                               temperatureExternal,
                                                               temperatureExternalMax,
                                                               temperatureExternalMin,
                                                               temperatureExternalTarget,
                                                               temperatureInternal,
                                                               temperatureInternalMax,
                                                               temperatureInternalMin,
                                                               temperatureInternalTarget,
                                                               dataPointsCount,
                                                               measurementType,
                                                               sensorIndex,
                                                               minFrequancyAllowed,
                                                               minMagnitudeAllowed)
                                         );
                            messageCounter++;
                        }
                    }
                }

                serviceEventSourceHelper.ServiceMessage(serviceContext, $"PublishReportDataFor - Report id[{reportUniqueId}]  Total number of rows [{messageCounter}] generated from messages [{deviceViewModelList.Count}] requested for URL [{publishUrl}]");

                if (messageCounter > 0 && resampleSetsLimit > 0)
                {
                    int maxNumberOfMessagesToSend = (resampleSetsLimit * maxSendingSet);
                    List <DeviceReportModel> messagesResampledSet = new List <DeviceReportModel>();

                    if (messageCounter > maxNumberOfMessagesToSend)
                    {
                        float selectInterval = messageCounter / maxNumberOfMessagesToSend;
                        int   selectedCount  = 0;
                        int   index          = 0;
                        foreach (DeviceReportModel message in messages)
                        {
                            if (index >= (selectedCount * selectInterval))
                            {
                                selectedCount++;
                                messagesResampledSet.Add(message);
                            }
                            index++;

                            if (selectedCount == maxNumberOfMessagesToSend)
                            {
                                break;
                            }
                        }
                        messages = messagesResampledSet;
                    }
                }

                serviceEventSourceHelper.ServiceMessage(serviceContext, $"PublishReportDataFor - Report id[{reportUniqueId}]  Final number of rows [{messages.Count}] generated from messages [{deviceViewModelList.Count}] requested for URL [{publishUrl}]");
                if (messages.Count > 0)
                {
                    List <DeviceReportModel> messagesFinalSet = new List <DeviceReportModel>();
                    messageCounter = 0;
                    int  messageSet = 1;
                    bool firstSet   = true;

                    foreach (DeviceReportModel message in messages)
                    {
                        messagesFinalSet.Add(message);
                        messageCounter++;

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

                            await RESTHandler.ExecuteHttpPOST(publishUrl, messagesFinalSet, httpClient, cancellationToken, serviceEventSource);

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

                            messagesFinalSet.Clear();
                            messageCounter = 0;
                            messageSet++;
                            firstSet = false;
                        }
                    }

                    if (messagesFinalSet.Count > 0)
                    {
                        if (!firstSet)
                        {
                            await Task.Delay(global::Iot.Common.Names.IntervalBetweenReportStreamingCalls);
                        }

                        await RESTHandler.ExecuteHttpPOST(publishUrl, messagesFinalSet, httpClient, cancellationToken, serviceEventSource);

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

                bRet = true;
            }
            else
            {
                serviceEventSourceHelper.ServiceMessage(serviceContext, $"Embed Report - No data found to publish to [{publishUrl}]");
            }

            return(bRet);
        }