public async Task SaveDeviceTwinAsync(string eventData, string tenant, string deviceId, double timeReceived)
        {
            try
            {
                string cosmosDbcollection = $"twin-change-{tenant}";
                int    cosmosCollRus      = Convert.ToInt32(Environment.GetEnvironmentVariable("CosmosDBRus", EnvironmentVariableTarget.Process));
                string cosmosDatabase     = Environment.GetEnvironmentVariable("DeviceStreamDatabaseId", EnvironmentVariableTarget.Process);

                CosmosOperations docClient = await CosmosOperations.GetClientAsync();

                bool updateStatus = await docClient.CreateCollectionIfNotExistsAsync(cosmosDatabase, cosmosDbcollection, cosmosCollRus, CosmosOperation.Device);

                if (updateStatus)
                {
                    JObject deviceTwinJson = JObject.Parse(eventData);
                    deviceTwinJson.Add(DeviceTelemetryKeyConstants.Id, deviceId);
                    deviceTwinJson.Add(DeviceTelemetryKeyConstants.DeviceId, deviceId);
                    deviceTwinJson.Add(DeviceTelemetryKeyConstants.TimeReceived, timeReceived);
                    deviceTwinJson.Add(DeviceTelemetryKeyConstants.Schema, DeviceTelemetryKeyConstants.TwinChangeSchema);

                    await docClient.SaveDocumentAsync(deviceTwinJson, this.GenerateCollectionLink(cosmosDatabase, cosmosDbcollection));
                }
            }
            catch (Exception exception)
            {
                throw new ApplicationException($"Save Device Twin failed: {exception},  tenant: {tenant}, deviceId: {deviceId}");
            }
        }
        public async Task SaveDeviceLifeCycleOperationAsync(string eventData, string tenant, string deviceId, string operationType)
        {
            try
            {
                string cosmosDbcollection = $"lifecycle-{tenant}";
                int    cosmosCollRus      = Convert.ToInt32(Environment.GetEnvironmentVariable("CosmosDBRus", EnvironmentVariableTarget.Process));
                string cosmosDatabase     = Environment.GetEnvironmentVariable("DeviceStreamDatabaseId", EnvironmentVariableTarget.Process);

                CosmosOperations docClient = await CosmosOperations.GetClientAsync();

                bool updateStatus = await docClient.CreateCollectionIfNotExistsAsync(cosmosDatabase, cosmosDbcollection, cosmosCollRus, CosmosOperation.Device);

                if (updateStatus)
                {
                    if (operationType.Equals("createDeviceIdentity"))
                    {
                        JObject deviceTwinJson = JObject.Parse(eventData);
                        deviceTwinJson.Add(DeviceTelemetryKeyConstants.Id, deviceId);
                        docClient = await CosmosOperations.GetClientAsync();

                        await docClient.SaveDocumentAsync(deviceTwinJson, this.GenerateCollectionLink(cosmosDatabase, cosmosDbcollection));
                    }
                    else
                    {
                        docClient = await CosmosOperations.GetClientAsync();

                        await docClient.DeleteDocumentAsync(deviceId, this.GenerateCollectionLink(cosmosDatabase, cosmosDbcollection));
                    }
                }
            }
            catch (Exception exception)
            {
                throw new ApplicationException($"Save Device Lifecycle operation failed: {exception}, operation type: {operationType}, tenant: {tenant}, deviceId {deviceId}");
            }
        }
Пример #3
0
        public static async Task <CosmosOperations> GetClientAsync()
        {
            await semaphoreSlim.WaitAsync();

            try
            {
                return(instance ?? (instance = CreateInstance()));
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
        public async Task SaveTelemetryToCosmosAsync(string telemetryMessage, string tenant)
        {
            try
            {
                string cosmosDbcollection = $"telemetry-{tenant}";
                int    cosmosCollRus      = Convert.ToInt32(Environment.GetEnvironmentVariable("CosmosDBRus", EnvironmentVariableTarget.Process));
                string cosmosDatabase     = Environment.GetEnvironmentVariable("DeviceStreamDatabaseId", EnvironmentVariableTarget.Process);

                CosmosOperations docClient = await CosmosOperations.GetClientAsync();

                bool updateStatus = await docClient.CreateCollectionIfNotExistsAsync(cosmosDatabase, cosmosDbcollection, cosmosCollRus, CosmosOperation.Device);

                if (updateStatus)
                {
                    await docClient.SaveDocumentAsync(JsonConvert.DeserializeObject(telemetryMessage), this.GenerateCollectionLink(cosmosDatabase, cosmosDbcollection));
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Save Telemetry message failed", ex);
            }
        }
Пример #5
0
        public async Task <bool> UpdateDevicePropertiesAsync(string eventData, string tenant)
        {
            bool updateStatus = false;
            DevicePropertyServiceModel existingDevProperties = null;
            ValueServiceModel          deviceCacheValue      = null;
            CosmosOperations           docClient             = null;

            try
            {
                this.cosmosDbcoll           = $"{CollectionKey}-{tenant}";
                this.cosmosDb               = Environment.GetEnvironmentVariable("DevicePropertiesCacheDatabaseId", EnvironmentVariableTarget.Process);
                this.whitelist              = Environment.GetEnvironmentVariable("WhiteList", EnvironmentVariableTarget.Process);
                this.cosmosDbRus            = Convert.ToInt32(Environment.GetEnvironmentVariable("CosmosDBRus", EnvironmentVariableTarget.Process));
                this.cosmosConnectionString = Environment.GetEnvironmentVariable("CosmosDbConnectionString", EnvironmentVariableTarget.Process);

                docClient = await CosmosOperations.GetClientAsync();

                updateStatus = await docClient.CreateCollectionIfNotExistsAsync(this.cosmosDb, this.cosmosDbcoll, this.cosmosDbRus, CosmosOperation.DeviceCache);

                // CosmosHelper cosmosHelper = new CosmosHelper(cosmosConnectionString, cosmosDbcoll, cosmosDb, tenant, cosmosDbRus, CosmosOperation.devicecache);
                try
                {
                    deviceCacheValue = await docClient.GetDocumentAsync(this.GenerateCollectionLink(this.cosmosDb, this.cosmosDbcoll), CollectionId, Key);

                    existingDevProperties = JsonConvert.DeserializeObject <DevicePropertyServiceModel>(deviceCacheValue.Data);
                }
                catch (ResourceNotFoundException)
                {
                    // Do nothing
                }
                catch (Exception exception)
                {
                    throw new ApplicationException("Get Device Properties failed", exception);
                }

                DeviceTwinNameOperations devTwinOps     = new DeviceTwinNameOperations();
                DeviceTwinName           deviceTwinName = devTwinOps.GetValidNames(this.whitelist, existingDevProperties, eventData);

                if (deviceTwinName != null)
                {
                    DevicePropertyServiceModel devicePropertyModel = new DevicePropertyServiceModel
                    {
                        Tags     = deviceTwinName.Tags,
                        Reported = deviceTwinName.ReportedProperties,
                    };

                    ValueServiceModel valueSvcModel = new ValueServiceModel(new KeyValueDocument(CollectionId, Key, JsonConvert.SerializeObject(devicePropertyModel)));

                    if (devicePropertyModel != null && existingDevProperties == null)
                    {
                        // Create the document
                        if (deviceCacheValue == null)
                        {
                            await docClient.SaveDocumentAsync(CollectionId, Key, valueSvcModel, this.GenerateCollectionLink(this.cosmosDb, this.cosmosDbcoll));

                            updateStatus = true;
                        }
                    }
                    else
                    {
                        // update only if the Tags or the reported properties are different from ones stored in cosmos
                        if (existingDevProperties != null && (!existingDevProperties.Tags.SetEquals(devicePropertyModel.Tags) || !existingDevProperties.Reported.SetEquals(devicePropertyModel.Reported)))
                        {
                            await docClient.SaveDocumentAsync(CollectionId, Key, valueSvcModel, this.GenerateCollectionLink(this.cosmosDb, this.cosmosDbcoll));

                            updateStatus = true;
                        }
                    }
                }
                else
                {
                    updateStatus = true;
                }
            }
            catch (Exception exception)
            {
                throw new ApplicationException($"Update Device Properties failed {exception}, tenant: {tenant}");
            }

            return(updateStatus);
        }