// Cumulocity Subscribe - Request - Response
        public SubscribeResponse[] DeviceCloudSubscribe(SubscribeRequest subscribeRequest, string service_url)
        {
            SubscribeResponse[] subscribeResp = new SubscribeResponse[0];
            try
            {
                HttpWebRequest             request = deviceCloudHttpRequest(service_url);
                DataContractJsonSerializer ser     = new DataContractJsonSerializer(subscribeRequest.GetType());
                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, subscribeRequest);
                String       json   = Encoding.UTF8.GetString(ms.ToArray());
                StreamWriter writer = new StreamWriter(request.GetRequestStream());
                ms.Close();
                writer.Write(json);
                writer.Close();

                using (var httpwebResponse = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(httpwebResponse.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        string responseJsonText = reader.ReadToEnd();
                        subscribeResp = js.Deserialize <SubscribeResponse[]>(responseJsonText);
                        // ==========================
                        ServiceEventSource.Current.ServiceMessage(this, "Subscribe to Cumulocity succeeded - {0}", subscribeResp[0].successful);
                        // ==========================
                        reader.Close();
                    }
                }
                request.Abort();
            }
            catch (Exception e)
            {
                // ==========================
                ServiceEventSource.Current.ServiceMessage(this, "Exception caught - {0} - unknown error during Subscribe request", System.Convert.ToString(e));
                // ==========================
                //System.Diagnostics.Trace.WriteLine("Exception caught" + System.Convert.ToString(e), "Error");
                subscribeResp[0].successful = false;
                subscribeResp[0].error      = "Exeption - unknown error during Subscribe request";
            }

            return(subscribeResp);
        }
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancelServiceInstance">Canceled when Service Fabric terminates this instance.</param>
        protected override async Task RunAsync(CancellationToken cancelServiceInstance)
        {
            // ServiceMassage Status
            ServiceEventSource.Current.ServiceMessage(this, "Start FabricService - DeviceEvents Service");

            // Initializing Cumulocity Device Cloud Communication
            List <ConnectResponse>    connectResponse    = new List <ConnectResponse>();
            List <DisconnectResponse> disconnectResponse = new List <DisconnectResponse>();
            Advice handshakeAdvise = new Advice();

            // extended timeout to 9 min.
            handshakeAdvise.timeout  = 90000;
            handshakeAdvise.interval = 0;
            string[] connectionTypes = new string[1] {
                "long-polling"
            };
            HandshakeRequest handshake = new HandshakeRequest();

            handshake.channel                  = "/meta/handshake";
            handshake.version                  = "1.0";
            handshake.minimumVersion           = "0.9";
            handshake.supportedConnectionTypes = connectionTypes;
            handshake.advice = handshakeAdvise;

            // This service instance continues processing until the instance is terminated.
            while (!cancelServiceInstance.IsCancellationRequested)
            {
                ServiceEventSource.Current.ServiceMessage(this, "Start Cumulocity Communication");
                // ======================================================================================
                // Implementation of Cumulocity Device Cloud
                // ======================================================================================

                HandshakeResponse[] handshakeResponse = DeviceCloudHandshake(handshake, devicecloud_url);
                if (handshakeResponse[0].successful == true)
                {
                    SubscribeRequest subscribeRequest = new SubscribeRequest();
                    subscribeRequest.channel      = "/meta/subscribe";
                    subscribeRequest.clientId     = handshakeResponse[0].clientId;
                    subscribeRequest.subscription = "/measurements/*";
                    SubscribeResponse[] subscribeResponse = DeviceCloudSubscribe(subscribeRequest, devicecloud_url);
                    subscribeRequest = null;
                    if (subscribeResponse[0].successful == true)
                    {
                        ConnectRequest connectRequest = new ConnectRequest();
                        connectRequest.clientId       = handshakeResponse[0].clientId;
                        connectRequest.channel        = "/meta/connect";
                        connectRequest.connectionType = "long-polling";
                        connectRequest.advice         = handshakeAdvise;

                        // ======================================================================================
                        DateTime endTime           = DateTime.Now.AddMinutes(10);
                        bool     connectionTimeOut = false;
                        while (!connectionTimeOut && !cancelServiceInstance.IsCancellationRequested)
                        {
                            ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - SendIoTEvents startet - {0}", System.Convert.ToString(DateTime.Now));

                            //// call SendIoTEvents here
                            connectResponse = DeviceCloudConnect(connectRequest, devicecloud_url);
                            connectResponse.ForEach(delegate(ConnectResponse singleResponse)
                            {
                                if (singleResponse.channel != "/meta/connect")
                                {
                                    SendIoTEvents(singleResponse);
                                }
                            });
                            //Thread.Sleep(1000);
                            await Task.Delay(TimeSpan.FromMilliseconds(200), cancelServiceInstance);

                            if (DateTime.Now >= endTime)
                            {
                                connectionTimeOut = true;
                            }
                            ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - SendIoTEvents succeeded - {0}", System.Convert.ToString(DateTime.Now));
                        }
                        ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - reached communicationTimeout 10 min.");
                        // ======================================================================================
                        connectRequest  = null;
                        connectResponse = null;

                        DisconnectRequest disconnectRequest = new DisconnectRequest();
                        disconnectRequest.clientId = handshakeResponse[0].clientId;
                        disconnectRequest.channel  = "/meta/disconnect";
                        disconnectResponse         = DeviceCloudDisconnect(disconnectRequest, devicecloud_url);
                        disconnectRequest          = null;
                        disconnectResponse         = null;

                        UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest();
                        unsubscribeRequest.channel      = "/meta/unsubscribe";
                        unsubscribeRequest.clientId     = handshakeResponse[0].clientId;
                        unsubscribeRequest.subscription = "/measurements/*";
                        UnsubscribeResponse[] unsubscribeResponse = DeviceCloudUnsubscribe(unsubscribeRequest, devicecloud_url);
                        unsubscribeRequest  = null;
                        unsubscribeResponse = null;
                    }
                    else
                    {
                        ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - subscribeResponse[0].succesfull == false");
                        deviceCloudResult = HttpStatusCode.BadRequest;
                    }
                }
                else
                {
                    ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - handshakeResponse[0].succesfull == false");
                    deviceCloudResult = HttpStatusCode.BadRequest;
                }
                // Pause for 1 second before continue processing.
                await Task.Delay(TimeSpan.FromSeconds(1), cancelServiceInstance);
            }
            handshake = null;
        }
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancelServiceInstance">Canceled when Service Fabric terminates this instance.</param>
        protected override async Task RunAsync(CancellationToken cancelServiceInstance)
        {
            // ServiceMassage Status
            ServiceEventSource.Current.ServiceMessage(this, "Start FabricService - DeviceEvents Service");

            // Initializing Cumulocity Device Cloud Communication
            List<ConnectResponse> connectResponse = new List<ConnectResponse>();
            List<DisconnectResponse> disconnectResponse = new List<DisconnectResponse>();
            Advice handshakeAdvise = new Advice();
            // extended timeout to 9 min.
            handshakeAdvise.timeout = 90000;
            handshakeAdvise.interval = 0;
            string[] connectionTypes = new string[1] { "long-polling" };
            HandshakeRequest handshake = new HandshakeRequest();
            handshake.channel = "/meta/handshake";
            handshake.version = "1.0";
            handshake.minimumVersion = "0.9";
            handshake.supportedConnectionTypes = connectionTypes;
            handshake.advice = handshakeAdvise;

            // This service instance continues processing until the instance is terminated.
            while (!cancelServiceInstance.IsCancellationRequested)
            {
                ServiceEventSource.Current.ServiceMessage(this, "Start Cumulocity Communication");
                // ======================================================================================
                // Implementation of Cumulocity Device Cloud 
                // ======================================================================================

                HandshakeResponse[] handshakeResponse = DeviceCloudHandshake(handshake, devicecloud_url);
                if (handshakeResponse[0].successful == true)
                {
                    SubscribeRequest subscribeRequest = new SubscribeRequest();
                    subscribeRequest.channel = "/meta/subscribe";
                    subscribeRequest.clientId = handshakeResponse[0].clientId;
                    subscribeRequest.subscription = "/measurements/*";
                    SubscribeResponse[] subscribeResponse = DeviceCloudSubscribe(subscribeRequest, devicecloud_url);
                    subscribeRequest = null;
                    if (subscribeResponse[0].successful == true)
                    {
                        ConnectRequest connectRequest = new ConnectRequest();
                        connectRequest.clientId = handshakeResponse[0].clientId;
                        connectRequest.channel = "/meta/connect";
                        connectRequest.connectionType = "long-polling";
                        connectRequest.advice = handshakeAdvise;

                        // ======================================================================================
                        DateTime endTime = DateTime.Now.AddMinutes(10);
                        bool connectionTimeOut = false;
                        while (!connectionTimeOut && !cancelServiceInstance.IsCancellationRequested)
                        {
                            ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - SendIoTEvents startet - {0}", System.Convert.ToString(DateTime.Now));

                            //// call SendIoTEvents here
                            connectResponse = DeviceCloudConnect(connectRequest, devicecloud_url);
                            connectResponse.ForEach(delegate (ConnectResponse singleResponse)
                            {
                                if (singleResponse.channel != "/meta/connect")
                                {
                                    SendIoTEvents(singleResponse);
                                }
                            });
                            //Thread.Sleep(1000);
                            await Task.Delay(TimeSpan.FromMilliseconds(200), cancelServiceInstance);

                            if (DateTime.Now >= endTime) connectionTimeOut = true;
                            ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - SendIoTEvents succeeded - {0}", System.Convert.ToString(DateTime.Now));
                        }
                        ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - reached communicationTimeout 10 min.");
                        // ======================================================================================
                        connectRequest = null;
                        connectResponse = null;

                        DisconnectRequest disconnectRequest = new DisconnectRequest();
                        disconnectRequest.clientId = handshakeResponse[0].clientId;
                        disconnectRequest.channel = "/meta/disconnect";
                        disconnectResponse = DeviceCloudDisconnect(disconnectRequest, devicecloud_url);
                        disconnectRequest = null;
                        disconnectResponse = null;

                        UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest();
                        unsubscribeRequest.channel = "/meta/unsubscribe";
                        unsubscribeRequest.clientId = handshakeResponse[0].clientId;
                        unsubscribeRequest.subscription = "/measurements/*";
                        UnsubscribeResponse[] unsubscribeResponse = DeviceCloudUnsubscribe(unsubscribeRequest, devicecloud_url);
                        unsubscribeRequest = null;
                        unsubscribeResponse = null;
                    }
                    else
                    {
                        ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - subscribeResponse[0].succesfull == false");
                        deviceCloudResult = HttpStatusCode.BadRequest;
                    }
                }
                else
                {
                    ServiceEventSource.Current.ServiceMessage(this, "Cumulocity communication - handshakeResponse[0].succesfull == false");
                    deviceCloudResult = HttpStatusCode.BadRequest;
                }
                // Pause for 1 second before continue processing.
                await Task.Delay(TimeSpan.FromSeconds(1), cancelServiceInstance);
            }
            handshake = null;
        }
        // Cumulocity Subscribe - Request - Response
        public SubscribeResponse[] DeviceCloudSubscribe(SubscribeRequest subscribeRequest, string service_url)
        {
            SubscribeResponse[] subscribeResp = new SubscribeResponse[0];
            try
            {
                HttpWebRequest request = deviceCloudHttpRequest(service_url);
                DataContractJsonSerializer ser = new DataContractJsonSerializer(subscribeRequest.GetType());
                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, subscribeRequest);
                String json = Encoding.UTF8.GetString(ms.ToArray());
                StreamWriter writer = new StreamWriter(request.GetRequestStream());
                ms.Close();
                writer.Write(json);
                writer.Close();

                using (var httpwebResponse = (HttpWebResponse)request.GetResponse())
                {
                    using (var reader = new StreamReader(httpwebResponse.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        string responseJsonText = reader.ReadToEnd();
                        subscribeResp = js.Deserialize<SubscribeResponse[]>(responseJsonText);
                        // ==========================
                        ServiceEventSource.Current.ServiceMessage(this, "Subscribe to Cumulocity succeeded - {0}", subscribeResp[0].successful);
                        // ==========================
                        reader.Close();
                    }
                }
                request.Abort();
            }
            catch (Exception e)
            {
                // ==========================
                ServiceEventSource.Current.ServiceMessage(this, "Exception caught - {0} - unknown error during Subscribe request", System.Convert.ToString(e));
                // ==========================
                //System.Diagnostics.Trace.WriteLine("Exception caught" + System.Convert.ToString(e), "Error");
                subscribeResp[0].successful = false;
                subscribeResp[0].error = "Exeption - unknown error during Subscribe request";
            }

            return subscribeResp;
        }